// Scripts for handling Featured menu in main page.

// Set initial properties for menu
var featuredMenu = {
	maxDisplayed:4, // The maximum number of items to display in the menu
	currentStartIndex:0, // The current top item in the menu 
	loadedMenuArr:[] // Array with all the menu data
}

// Initialize menu:
featuredMenu.init = function(){
	this.menuDIV = document.getElementById("featured"); // Define the HTML element in which the menu is created
	this.request("Scripts/hp/featuredMenu_data_XML.xml") // Activate data loading from external file
}

// Makes ajax request
// Parameter:
// url: path to file
// Calls handleRequest method
featuredMenu.request=function(url){
    var http_request = false;       
    
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        return false;
    }
	// When the request status changes, handle the request
    http_request.onreadystatechange = function() { featuredMenu.handleRequest(http_request); };

	// Call data from the file
	http_request.open('GET', url, true );
    
    http_request.send(null);
}

//executed after AJAX retrieved the file
featuredMenu.handleRequest=function(reqObj){
	
    if (reqObj.readyState == 4) {
        if (reqObj.status == 200) {
            // If the request was successful, parse the data
            this.parseData(reqObj.responseXML)
        } else {
        
            //handle ajax error here. display a message or whatever.
            alert('There was a problem with the request.');
        }
    }
}

//takes the file and splits the lines to an array (featuredMenu.loadedMenuArr)
featuredMenu.parseData=function(responseXML){
    
    var allMenuItemsArr = [];
    var myXML = stripWhiteSpace(responseXML); // Strip whitespace from XML response
    var menuItemsNode = myXML.getElementsByTagName("menuItems"); 
	if(menuItemsNode !=undefined)
	{
	
            var menuItemsArr = menuItemsNode[0].childNodes; 
            var numberOfItems = menuItemsArr.length;
             
            // Loop through the menu items XML and add each element to a temporary object
            for (var i = 0; i<numberOfItems; i++)
            {
                var menuItemObj = {}; // temporary object
                
                var currentMenuItem = menuItemsArr[i] // The current node
           
                 // Static Picture
			    var staticPicNode = currentMenuItem.getElementsByTagName("staticPic")[0];
			    if (staticPicNode != undefined)
			    {
				    var staticPic = staticPicNode.childNodes[0].nodeValue;
				    menuItemObj.staticPic = staticPic;
				  
				      
			    }
			    
			    
                 // Rollover Picture
                var rolloverPicNode = currentMenuItem.getElementsByTagName("rolloverPic")[0];
			    if (rolloverPicNode != undefined)
			    {
				    var rolloverPic = rolloverPicNode.childNodes[0].nodeValue;
				    menuItemObj.rolloverPic = rolloverPic;
				      
			    }
			    
			     // Destination URL
                var destinationNode = currentMenuItem.getElementsByTagName("destination")[0];
			    if (destinationNode != undefined)
			    {
				    var destination = destinationNode.childNodes[0].nodeValue;
				    menuItemObj.destination = destination;
				      
			    }
			    
			    // ALT text
                 var altTextNode = currentMenuItem.getElementsByTagName("altText")[0];
			    if (altTextNode != undefined)
			    {
				    var altText = altTextNode.childNodes[0].nodeValue;
				    menuItemObj.altText = altText;
				      
			    }
			    
			    // Target (_self or _blank)
                 var targetNode = currentMenuItem.getElementsByTagName("target")[0];
			    if (targetNode != undefined)
			    {
				    var target = targetNode.childNodes[0].nodeValue;
				    menuItemObj.target = target;
				      
			    }
			    
			    // Click function - function to activate when picture is clicked
			     var clickFunctionNode = currentMenuItem.getElementsByTagName("clickFunction")[0];
			    if (clickFunctionNode != undefined)
			    {
				    var clickFunction = clickFunctionNode.childNodes[0].nodeValue;
				    menuItemObj.clickFunction = clickFunction;
				      
			    }
			    
			    // Add object to items array
			    allMenuItemsArr.push(menuItemObj);
            }
    }
    
    if(allMenuItemsArr.length>0){
    // Define the loadedMenuArr property 
        featuredMenu.loadedMenuArr = allMenuItemsArr;
        // Create menu
         featuredMenu.createFeaturedMenu(featuredMenu.currentStartIndex)
    }
   
}


// Create dynamic menu:
featuredMenu.createFeaturedMenu = function(firstIndex)
{
	// Create HTML code for the menu
	var menuHTML ="<img src='images/hp/scroll_up.jpg' id='topArrow' />" // Top arrow
	
	// Loop through the array of menu items and add each item to the HTML code
	for(var i=firstIndex;i<firstIndex+this.maxDisplayed&&i<featuredMenu.loadedMenuArr.length;i++){
		
		
		var menuItemObj = featuredMenu.loadedMenuArr[i]
		preloadMenuImages([menuItemObj.rolloverPic])
		if(menuItemObj.clickFunction != null){
		
		    menuHTML += "<a href='"+menuItemObj.destination+"' target='"+menuItemObj.target+"' onclick="+menuItemObj.clickFunction+"><img width='215' height='72' src='"+menuItemObj.staticPic+"' id='img_"+i+"' alt='"+menuItemObj.altText+"' onmouseover=swapMenuImage(this,'"+menuItemObj.rolloverPic+"') onmouseout=swapMenuImage(this,'"+menuItemObj.staticPic+"') /></a>"
  
		}else{
		    menuHTML += "<a href='"+menuItemObj.destination+"' target='"+menuItemObj.target+"'><img width='215' height='72' src='"+menuItemObj.staticPic+"' id='img_"+i+"' alt='"+menuItemObj.altText+"' onmouseover=swapMenuImage(this,'"+menuItemObj.rolloverPic+"') onmouseout=swapMenuImage(this,'"+menuItemObj.staticPic+"') /></a>"
        }
	}
	
	menuHTML += "<img src='images/hp/scroll_down.jpg' id='bottomArrow' />" // Bottom arrow
	this.menuDIV.innerHTML = menuHTML; // Add HTML to the document
	
		this.initScroll() // Initiate scroll
	
}

// Scroll functions:

// Initiate the scroll properties
featuredMenu.initScroll = function(){
		
		this.topArrow = document.getElementById("topArrow") 
		this.bottomArrow =  document.getElementById("bottomArrow")
		
		this.updateArrows() // Update arrow state
		
		// Preload the arrow images
		preloadMenuImages(["images/hp/scroll_up_gray.jpg","images/hp/scroll_down_gray.jpg","images/hp/scroll_up.jpg","images/hp/scroll_down.jpg","images/hp/scroll_up_over.jpg","images/hp/scroll_down_over.jpg"])
}

// Scroll down action:
// If the menu isn't all scrolled down updatte the featuredMenu.currentStartIndex value and redraw the menu
featuredMenu.scrollDown = function(){
		if(featuredMenu.currentStartIndex<featuredMenu.loadedMenuArr.length-2){
			featuredMenu.currentStartIndex++
		
			featuredMenu.createFeaturedMenu(featuredMenu.currentStartIndex);
		}
		// Update the state of the arrows
		featuredMenu.updateArrows()
}

// Scroll up action:
// If the menu isn't at top, updatte the featuredMenu.currentStartIndex value and redraw the menu
featuredMenu.scrollUp = function(){
		if(featuredMenu.currentStartIndex>0){
			featuredMenu.currentStartIndex--
			featuredMenu.createFeaturedMenu(featuredMenu.currentStartIndex);
		}
		// Update the state of the arrows
		featuredMenu.updateArrows()
}


// Update the state and behaviors of the arrow.
featuredMenu.updateArrows = function(){
	if(featuredMenu.loadedMenuArr.length<=featuredMenu.maxDisplayed){
		swapMenuImage(featuredMenu.topArrow,"images/hp/scroll_up_gray.jpg")
		featuredMenu.topArrow.style.cursor = "default";
		swapMenuImage(featuredMenu.bottomArrow,"images/hp/scroll_down_gray.jpg")
		featuredMenu.bottomArrow.style.cursor = "default";
		return;
		}
	
	// If menu is scrolled up disable top arrow
	if(featuredMenu.currentStartIndex==0){
		
		swapMenuImage(featuredMenu.topArrow,"images/hp/scroll_up_gray.jpg")
		featuredMenu.topArrow.style.cursor = "default"
		
	}else{
	// otherwise set top arrow rollover, rollout and click behavior	
		swapMenuImage(featuredMenu.topArrow,"images/hp/scroll_up.jpg")
		featuredMenu.topArrow.style.cursor = "pointer"
		featuredMenu.topArrow.style.cursor = "hand"
		featuredMenu.topArrow.onmouseover = function(){
		swapMenuImage(this,"images/hp/scroll_up_over.jpg")
	}
		featuredMenu.topArrow.onmouseout = function(){
		swapMenuImage(this,"images/hp/scroll_up.jpg")
	}	
		featuredMenu.topArrow.onclick = featuredMenu.scrollUp
	}
	
	// If menu is scorolled down, diable bottom arrow
	if(featuredMenu.currentStartIndex==featuredMenu.loadedMenuArr.length-featuredMenu.maxDisplayed){
		
		swapMenuImage(featuredMenu.bottomArrow,"images/hp/scroll_down_gray.jpg")
		featuredMenu.bottomArrow.style.cursor = "default"
	
	}else{
		// otherwise set bottom arrow rollover, rollout and click behavior	
		swapMenuImage(featuredMenu.bottomArrow,"images/hp/scroll_down.jpg")
		featuredMenu.bottomArrow.style.cursor = "pointer"
		featuredMenu.bottomArrow.style.cursor = "hand"
		featuredMenu.bottomArrow.onmouseover = function(){
			swapMenuImage(this,"images/hp/scroll_down_over.jpg")
		}
		featuredMenu.bottomArrow.onmouseout = function(){
			swapMenuImage(this,"images/hp/scroll_down.jpg")
		}	
		featuredMenu.bottomArrow.onclick = featuredMenu.scrollDown
	}
}

// General functions

// Swap image source:
function swapMenuImage(img,newSrc){
   // alert("old src = "+img.src+" new src = "+newSrc)
   
	if(img.src!=newSrc){
		img.src = newSrc;
	
	}
}

// Preload images.
// Parameter: an array of urls to images.
// The code loops through the array and creates a timeout for each item to activate the preload action.
// This is done to give the action enough time to execute

function preloadMenuImages(imgArr){
	
	
	var tempArr = []
	
	for(var i=0;i<imgArr.length;i++){
		var time = i*200;
		var timeout = setTimeout("createNewImg('"+imgArr[i]+"')",time);
	}
	
}

// Preload image by creating a Image object and setting its source.
function createNewImg(src){
	
    var img = new Image()
	img.src = src;
}


// *************************************************

// Custom functions that can be called from the menu

function openNewWindow(url,width,height,scrollbars){
   
    var newWindowName = "win"+Math.round(Math.random()*1000);
    var features = "width="+width+", height="+height+","+"scrollbars="+scrollbars;
   
    window.open(url,newWindowName,features)

}






// Strip Whitespace code ********************************


function is_ws(nod)
{
	return !(/[^\t\n\r ]/.test(nod.data));
}

function findWhiteSpace(node, nodeNo)
{
	for (i=0; i<node.childNodes.length; i++)
	{
		if (node.childNodes[i].nodeType == 3 && is_ws(node.childNodes[i]))
		{
			nodesToDelete[nodesToDelete.length] = node.childNodes[i];
		}
		if (node.childNodes[i].hasChildNodes())
		{
			findWhiteSpace(node.childNodes[i],i);
		}
	}
	node = node.parentNode;
	i = nodeNo;
}

function stripWhiteSpace(node)
{
	nodesToDelete = Array();
	findWhiteSpace(node,0);
	for (i=nodesToDelete.length-1; i>=0; i--)
	{
		nodeRef = nodesToDelete[i];
		nodeRef.parentNode.removeChild(nodeRef);
	}
	return node;
}