// JavaScript Document

// AJAX Request Object //////////////////////
function createRequestObject()
	{ 
	var req;
	if( window.XMLHttpRequest )
		{
		// Firefox, Safari, Opera...
		req = new XMLHttpRequest();
        }
	else if( window.ActiveXObject )
		{
		// Internet Explorer 5+
		req = new ActiveXObject("Microsoft.XMLHTTP");
		}
	else
		{
		// There is an error creating the object,
		// just as an old browser is being used.
		alert('There was a problem creating the XMLHttpRequest object');
        }
	return req;
	}
// Make the XMLHttpRequest object
http = createRequestObject();
///////////////////////////////////////////////



// JAVASCRIPT VISITOR DATA
function sendReferer(thisrefererid,time,referer,userid)
	{ 
	// GET THE SCREEN PIXEL WIDTH AND HEIGHT
	var screensize = screen.width + " x " + screen.height;
	
	// GET THE BROWSERS VIEWPORT PIXEL WIDTH AND HEIGHT
	var screenview = getviewport();
	
	// GET THE BROWSER USER AGENT
	var useragent = navigator.userAgent;
	
	// GET THE BROWSERS DEFAULT LANGUAGE
	if (navigator.appName == 'Netscape')
		{ var language = navigator.language; }
	else
		{ var language = navigator.browserLanguage;	}
		
	//alert( thisrefererid + " " + time + " " + referer + " " + userid );
	// BUILD VISITOR DATA STRING
	var refererString = 'thisrefererid=' + thisrefererid + '&referer=' + referer + '&screensize=' + screensize + '&screenview=' + screenview + '&userid=' + userid + '&useragent=' + useragent + '&language=' + language;
	
	// SEND VISITOR DATA TO DATABASE
	http.open('GET', 'referer.php?' + refererString);
	http.onreadystatechange = refererResponse; 
	http.send(null);     
    }
	
// AJAX handle Response //////////////////////////////////////
function refererResponse()
	{
	if(http.readyState == 4 && http.status == 200)
		{
		// Text returned FROM PHP script 
		var response = http.responseText; 
		//alert( " AJAX Success Status code : " + http.status );
		if( response )
			{
			// UPDATE ajaxTest content 
			//alert( response );
			}
        }    
    }
///////////////////////////////////////////////



// JAVASCRIPT VISITOR DATA
function sendVisitDuration(time,userid)
	{ 
	//alert( time + " " + userid );
	// BUILD VISITOR DATA STRING
	var visitDurationString = 'time=' + time + '&userid=' + userid;
	
	// UPDATE TIME EVERY SECOND
	visitDurationTimer = setTimeout('sendVisitDuration(time,userid)', 10000);

	// SEND VISITOR DATA TO DATABASE
	http.open('GET', 'visitduration.php?' + visitDurationString);
	http.onreadystatechange = visitDurationResponse; 
	http.send(null);     
    }
	
// AJAX handle Response //////////////////////////////////////

function visitDurationResponse()
	{
	if(http.readyState == 4 && http.status == 200)
		{
		// Text returned FROM PHP script 
		var response = http.responseText; 
		//alert( " AJAX Success Status code : " + http.status );
		if( response )
			{
			// UPDATE ajaxTest content 
			//alert( response );
			}
        }    
    }

	

// NAVIGATION MENU //////////////////////////////////////
	
// MainMenu Alignment
var leftAlignMainMenuPosition = 'left'; // of parent left, center, right or empty for default
var leftAlignMainMenuOffset = -3;//no. of pixels can be negative // - moves left
var centerAlignMainMenuOffset = 0;
var rightAlignMainMenuOffset = 5;

var topAlignMainMenuPosition = 'top';// top, middle, bottom
var topAlignMainMenuOffset = -34;//no. of pixels can be negative // - moves up
var middleAlignMainMenuOffset = 0;
var bottomAlignMainMenuOffset = 0;

// SubMenu Alignment
var leftAlignSubMenuPosition = 'right';// of parent left, center, right
var leftAlignSubMenuOffset = -7;//no. of pixels can be negative // - moves left
var centerAlignSubMenuOffset = 0;
var rightAlignSubMenuOffset = 7;

var topAlignSubMenuPosition = 'top';//top, middle, bottom
var topAlignSubMenuOffset = -5;//no. of pixels can be negative // - moves up
var middleAlignSubMenuOffset = 0;
var bottomAlignSubMenuOffset = 0;

// http://www.howtocreate.co.uk/tutorials/javascript/domstructure

// good source for looking up javascript translation of css
//http://www.dhtmlgoodies.com/scripts/css-lookup/css-lookup.html


// On Mouseover Show menu as visible
function showSubMenu()
	{
	var objThis = this;
	for(var i = 0; i  < objThis.childNodes.length; i++)
		{
		var menu = objThis.childNodes.item(i).nodeName;
		if(menu == "DIV" || menu == "div")			
			{
			// display menu or run function to display this menu
			objThis.childNodes.item(i).style.visibility = "visible";
			break;
			}		
		}	
	}

// On Mouseout Show menu as hidden
function hideSubMenu()
	{
	var objThis = this;
	for(var i = 0; i  < objThis.childNodes.length; i++)
		{
		var menu = objThis.childNodes.item(i).nodeName;
		if(menu == "DIV" || menu == "div")
			{
			// hide menu or run function to hide this menu
			objThis.childNodes.item(i).style.visibility = "hidden";
			break;
			}
		}
	}
	
// Test if sub menu appears within viewport
function checkSubMenu()
	{
	//return true;
	//return false;
	}

// Initialise Menu
function initialiseMenu()
	{
	// get the default navigation element ( div container for nav )
	var nav = document.getElementById("navigation");
	
	// get all li elements within navigation div
	var objLICollection = nav.getElementsByTagName("li");
	
	// loop each li element
	for(var i = 0; i < objLICollection.length; i++)
		{
		var objLI = objLICollection[i];
		// loop through elements children if any
		for(var j = 0; j  < objLI.childNodes.length; j++) // if this li has children continue
			{
			// if this li has a div menu sub as child attach mouse functions
			if(objLI.childNodes.item(j).nodeName == "DIV" || objLI.childNodes.item(j).nodeName == "div")
				{
				objLI.onmouseover = showSubMenu;
				objLI.onmouseout = hideSubMenu;
				}
			}
		}
	}


function GetElementPosition(element)
	{
    var result = new Object();
    result.x = 0;
    result.y = 0;
    result.width = 0;
    result.height = 0;
	// Firefox Netscape use offset
    if (element.offsetParent)
		{
		// offsetLeft offsetTop
		// distance of element from the left, in pixels
        result.x = element.offsetLeft;
        result.y = element.offsetTop;
        var parent = element.offsetParent;
        while (parent)
			{
            result.x += parent.offsetLeft;
            result.y += parent.offsetTop;
            var parentTagName = parent.tagName.toLowerCase();
            if (parentTagName != "table" &&
                parentTagName != "body" && 
                parentTagName != "html" && 
                parentTagName != "div" && 
                parent.clientTop && 
                parent.clientLeft)
				{
				// clientLeft clientTop
				// Read-only properties. Get the left and top side of a positioned element
                result.x += parent.clientLeft;
                result.y += parent.clientTop;
				}
			parent = parent.offsetParent;
			}
		}
    else if (element.left && element.top)
		{
        result.x = element.left;
        result.y = element.top;
    	}
    else
		{
        if (element.x)
			{
            result.x = element.x;
        	}
        if (element.y)
			{
            result.y = element.y;
        	}
    	}
    if (element.offsetWidth && element.offsetHeight)
		{
        result.width = element.offsetWidth;
        result.height = element.offsetHeight;
    	}
    else if (element.style && element.style.pixelWidth && element.style.pixelHeight)
		{
        result.width = element.style.pixelWidth;
        result.height = element.style.pixelHeight;
    	}
    return result;
	}
	
function SetElementHeight(element, height)
	{
    if (element && element.style)
		{
        element.style.height = height + "px";
    	}
	}
function SetElementWidth(element, width)
	{
    if (element && element.style)
		{
        element.style.width = width + "px";
    	}
	}
function SetElementX(element, x)
	{
    if (element && element.style)
		{
        element.style.left = x + "px";
    	}
	}
function SetElementY(element, y)
	{
    if (element && element.style)
		{
        element.style.top = y + "px";
    	}
	}
	


function findPosLeft(obj) // horizontal
	{
	//IE and Firefox hack
	var use_parentnode = obj.nodeName=="BODY" && navigator.userAgent.toLowerCase().indexOf("msie")!=-1 && typeof window.opera == 'undefined';
	
	// Opera hack
    var use_children = typeof window.opera != 'undefined';
	
	// if Opera count position from first child element for offsetposition else use standard object offsetposition
    var curleft = use_children && obj.children.length ? obj.children[0].offsetLeft : obj.offsetLeft;
	
	// if IE and Firefox use parentNode
	var parent = use_parentnode ? obj.parentNode : obj.offsetParent;

    while (parent && typeof parent == 'object' && typeof parent.offsetLeft != 'undefined')
		{
       	curleft += parent.offsetLeft;
       	parent = use_parentnode ? parent.parentNode : parent.offsetParent;
    	}
	return curleft;
	}

function findPosTop(obj) // vertical
	{
	// IE hack
    var use_parentnode = obj.nodeName=="BODY" && navigator.userAgent.toLowerCase().indexOf("msie")!=-1 && typeof window.opera == 'undefined';
	
	// Opera hack
    var use_children = typeof window.opera != 'undefined';

    var curtop = use_children && obj.children.length ? obj.children[0].offsetTop : obj.offsetTop;

	var parent = use_parentnode ? obj.parentNode : obj.offsetParent;
	
    while (parent && typeof parent == 'object' && typeof parent.offsetTop != 'undefined')
		{
       	curtop += parent.offsetTop;
       	parent = use_parentnode ? parent.parentNode : parent.offsetParent;
    	}
	return curtop;
	}

function getviewport(direction)
	{
	if (window.innerWidth) // FIREFOX
		{
		screenWidth = window.innerWidth;
		screenHeight = window.innerHeight;
		}
	else if (document.documentElement && document.documentElement.clientWidth) // SAFARI
		{
		screenWidth = document.documentElement.clientWidth;
		screenHeight = document.documentElement.clientHeight;
		}
	else if (document.body) // IE
		{
		screenWidth = document.body.clientWidth;
		screenHeight = document.body.clientHeight;
		}
	if ( direction == "width" )
		{
		return screenWidth;
		}
	if ( direction == "height" )
		{
		return screenHeight;
		}
	return screenWidth + " x " + screenHeight;
	//alert( "Viewport width=" +screenWidth + "px x height=" + screenHeight + "px");
	}
	
	
// reposition all divsacording to visible page area
function alignMenu()
	{
	// Get browser visible workspace
	var viewportWidth = getviewport("width");
	var viewportHeight = getviewport("height");
	//alert( "viewport Width = " + viewportWidth + "px ; viewport Height = " + viewportHeight  + "px");
	
	// loops all div sub menus in navigation list
	var nav = document.getElementById("navigation");
	var navDivs = nav.getElementsByTagName("div");	
	
	var navWidth = nav.offsetWidth; // elements width inc margin & padding
	var navHeight = nav.offsetHeight; // elements height inc margin & padding
	//alert( "Nav Width = " + navWidth + "px ; Nav Height = " + navHeight  + "px");
	
	var navPosLeft = findPosLeft(nav);
	var navPosRight = navPosLeft + navWidth;	
	//alert( "Pos Top Left = " + navPosLeft + "px; Pos Top Right = " + navPosRight + "px");

	// Loop all divs in nav
	for(var i=0;i<navDivs.length;i++) // loop foreach menu
		{
		if ( navDivs[i].style.className != "cleaner" )
			{
			var thisDIV = navDivs[i];
			
			var thisDIVWidth = thisDIV.offsetWidth; // width of this menu
			var thisDIVHeight = thisDIV.offsetHeight; // height of this menu
			var thisDIVPosLeft = findPosLeft(thisDIV); // horizontal position of this menu
			var thisDIVPosTop = findPosTop(thisDIV); // vertical position of this menu		
			
			var parentLI = thisDIV.parentNode; // assign parent LI of this DIV Menu
			//alert(parentLI.tagName); 
			var parentUL = parentLI.parentNode; // assign parent UL of this DIV Menu
			//alert(parentUL.tagName);
			var parentDIV = parentUL.parentNode; // assign parent DIV of this DIV Menu
			//alert(parentDIV.tagName);
			
			var parentLIWidth = parentLI.offsetWidth; // width of parent LI item
			var parentLIHeight = parentLI.offsetHeight; // height of parent LI item
			var parentLIPosLeft = findPosLeft(parentLI); // horizontal position of parent LI item
			var parentLIPosTop = findPosTop(parentLI); // vertical position of parent LI item
			
			var parentULWidth = parentUL.offsetWidth; // width of parent UL item
			var parentULHeight = parentUL.offsetHeight; // height of parent UL item
			var parentULPosLeft = findPosLeft(parentUL); // horizontal position of parent UL item
			var parentULPosTop = findPosTop(parentUL); // vertical position of parent UL item
			
			var parentDIVWidth = parentDIV.offsetWidth; // width of parent DIV item
			var parentDIVHeight = parentDIV.offsetHeight; // height of parent DIV item
			var parentDIVPosLeft = findPosLeft(parentDIV); // horizontal position of parent DIV item
			var parentDIVPosTop = findPosTop(parentDIV); // vertical position of parent DIV item

			//alert("Top " + thisDIVPosTop + " | Left " + thisDIVPosLeft);
			
			var leftMain = 0;
			var topMain = 0;
			var leftSub = 0;
			var topSub = 0;
			
// ALIGN MENUS AND SUB MENUS
///////////////////////////////////////////////////////////////////////////////////////
		
			// CALCULATIONS FOR FIRST LEVEL NAVIGATION MENU
			if ( parentDIV.id == "navigation" ) // this is the first level sub
				{
				
				// horizontal alignment
				switch (leftAlignMainMenuPosition)
					{
					case "left":
					thisDIV.style.left = parseInt(parentLIPosLeft + -thisDIVPosLeft + leftAlignMainMenuOffset) + "px";
					//thisDIV.style.left = leftMain + "px";
					break;
					
					case "center":
					var parentLIPosCenter = parentLIPosLeft + ( parentLIWidth / 2 );
					var thisDIVPosCenter = parentLIPosCenter - ( thisDIVWidth / 2 );
					thisDIV.style.left = parseInt(thisDIVPosCenter + -thisDIVPosLeft + centerAlignMainMenuOffset) + "px";
					break;
					
					case "right":
					var parentLIPosRight = parentLIPosLeft + parentLIWidth;
					var thisDIVPosRight = parentLIPosRight - thisDIVWidth;
					thisDIV.style.left = parseInt(thisDIVPosRight + -thisDIVPosLeft + rightAlignMainMenuOffset) + "px";
					break;
					
					default :
					thisDIV.style.left = parseInt(parentLIPosLeft + -thisDIVPosLeft + leftAlignMainMenuOffset) + "px";
					}

				// vertical alignment
				switch (topAlignMainMenuPosition)
					{
					case "top":
					var thisDIVPosTop = parseInt(parentLIPosTop - thisDIVHeight);
					thisDIV.style.top = parseInt(thisDIVPosTop + topAlignMainMenuOffset) + "px";
					break;
					
					case "middle":
					var parentLIPosMiddle = parseInt(parentLIPosTop + ( parentLIHeight / 2 ));
					var thisDIVPosMiddle = parseInt(parentLIPosMiddle - ( thisDIVHeight / 2 ));
					thisDIV.style.top = parseInt(thisDIVPosMiddle + middleAlignMainMenuOffset) + "px";
					break;
					
					case "bottom":
					var parentLIPosBottom = parseInt(parentLIPosTop + parentLIHeight);
					thisDIV.style.top = parseInt(parentLIPosBottom + bottomAlignMainMenuOffset) + "px";
					break;
					
					default:
					var thisDIVPosTop = parseInt(parentLIPosTop - thisDIVHeight);
					thisDIV.style.top = parseInt(thisDIVPosTop + topAlignMainMenuOffset) + "px";
					}
				}
				else // CALCULATIONS FOR SECOND LEVEL NAVIGATION MENU
				{
				
				// horizontal alignment
				switch (leftAlignSubMenuPosition)
					{
					case "left":
					thisDIV.style.left = parseInt(-parentDIVWidth + rightAlignSubMenuOffset) + "px";
					break;
					
					case "center":
					var parentDIVWidthCenter = parseInt(parentDIVWidth / 2);
					thisDIV.style.left = parseInt(parentDIVWidthCenter + centerAlignSubMenuOffset) + "px";
					break;
					
					case "right":
					thisDIV.style.left = parseInt(parentDIVWidth + leftAlignSubMenuOffset) + "px";
					break;
					
					default :
					thisDIV.style.left = parseInt(-parentDIVWidth + rightAlignSubMenuOffset) + "px";
					}
									
					
				// vertical alignment
				switch (topAlignSubMenuPosition)
					{
					case "top":
					//element.children[0].offsetWidth
					// errors in opera
					//alert( parentLI.offsetTop );
					var thisDIVPosTop = parseInt(parentLIPosTop - parentDIVPosTop);
					thisDIV.style.top = parseInt(thisDIVPosTop + topAlignSubMenuOffset) + "px";
					//var thisDIVPosTop = parseInt(parentLIPosTop - thisDIVHeight);
					//thisDIV.style.top = parseInt(thisDIVPosTop + topAlignSubMenuOffset) + "px";
					break;
					
					case "middle":
					// errors in browser  no li offset height
					//var parentLIPosMiddle = parseInt(parentLIPosTop + ( parentLIHeight / 2 ));
					//var thisDIVPosMiddle = parseInt(parentLIPosMiddle - ( thisDIVHeight / 2 ));
					//thisDIV.style.top = parseInt(thisDIVPosMiddle + middleAlignSubMenuOffset) + "px";
					break;
					
					case "bottom":
					// errors in browser  no li offset height
					//var parentLIPosBottom = parseInt(parentLIPosTop + parentLIHeight);
					//thisDIV.style.top = parseInt(parentLIPosBottom + bottomAlignSubMenuOffset) + "px";
					break;
					
					default:
					var thisDIVPosTop = parseInt(parentLIPosTop - parentDIVPosTop);
					thisDIV.style.top = parseInt(thisDIVPosTop + topAlignSubMenuOffset) + "px";
					}

				}			
			
			
// ALIGN MENUS TO APPEAR WITHIN VIEWPORT
//////////////////////////////////////////////////////////////////////////////////////			
			
			var thisDIVWidth = thisDIV.offsetWidth; // width of this menu
			var thisDIVHeight = thisDIV.offsetHeight; // height of this menu
			var thisDIVPosLeft = findPosLeft(thisDIV); // horizontal position of this menu
			var thisDIVPosRight = thisDIVPosLeft + thisDIVWidth;
			var thisDIVPosTop = findPosTop(thisDIV); // vertical position of this menu
			
			// ReAlign Menus if outside viewport
			// Left Overflow
			if ( thisDIVPosLeft < 0 )
				{
				if ( parentDIV.id == "navigation" ) // Main Menu
					{
					if ( leftAlignMainMenuPosition == "right" || leftAlignMainMenuPosition == "center" )
						{
						// align to left of parent
						thisDIV.style.left = parseInt(parentLIPosLeft + leftAlignMainMenuOffset) + "px";
						}
					}
					else // Sub Menu
					{
					thisDIV.style.left = parseInt(parentDIVWidth + leftAlignSubMenuOffset) + "px"
					}
				}
				
			// Right Overflow
			if ( thisDIVPosRight > viewportWidth )
				{
				if ( parentDIV.id == "navigation" ) // Main Menu
					{
					var parentLIPosRight = parseInt(parentLIPosLeft + parentLIWidth);
					//alert( thisDIVPosLeft + " " + parentLIPosRight );
					var thisDIVnewPosLeft = parseInt((parentLIPosRight - thisDIVWidth) + rightAlignMainMenuOffset) + "px";
					thisDIV.style.left = thisDIVnewPosLeft;
					}
					else // Sub Menu
					{
					thisDIV.style.left = parseInt(-parentDIVWidth + rightAlignSubMenuOffset) + "px";
					}
				}
				
				
			}
		}
	initialiseMenu();
	}
	
	
//////////////////////////////////////////////////////////////////////////////////////
	



// Preload images and any other items
function preload()
	{
	var args = preload.arguments;
	document.imgArray = new Array(args.length);
	for(var i=0; i<args.length; i++)
		{
		document.imgArray[i] = new Image;
		document.imgArray[i].src = args[i];
		}
	}
	
function mouseoverimages()
	{
	preload('images/nav-active-bg.jpg','images/nav-active-left.jpg','images/nav-active-right.jpg','images/nav-hover-bg.jpg','images/nav-hover-left.jpg','images/nav-hover-right.jpg','images/nav-inactive-bg.jpg','images/nav-inactive-left.jpg','images/nav-inactive-right.jpg');
	}
	

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
// use add loadEvent like below
//addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  // more code to run on page load
  sendVisitDuration(time,userid);
  alignMenu();
  //mouseoverimages();
  if ( thisrefererid != '' )
  	{
	//alert(thisrefererid + " " + time + " " + referer + " " + userid);
  	sendReferer(thisrefererid,time,referer,userid);
	}
})

function addUnloadEvent(func) {
  var oldOnunload = window.onunload;
  if (typeof window.onunload != 'function') {
    window.onunload = func;
  } else {
    window.onunload = function() {
      if (oldOnunload) {
        oldOnunload();
      }
      func();
    }
  }
}
// use add loadEvent like below
//addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addUnloadEvent(function() {
  // more code to run on page unload

})
/*
window.onresize= reloadpage;
function reloadpage(){ //or whatver else you have
//alignSubMenu();
setTimeout("window.location.reload()",1);
}
*/
