// Methods used across the site.

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

// This contains all the general functions for the active JS.

/********** User info functions **********/
function identifyBrowser() {
   var agent = navigator.userAgent.toLowerCase();

   if(typeof navigator.vendor != "undefined" && navigator.vendor == "KDE" && typeof window.sidebar != "undefined") {
      return "kde";
   }else if(typeof window.opera != "undefined") {
      var version = parseFloat(agent.replace(/.*opera[\/ ]([^ $]+).*/, "$1"));
      if(version >= 7) {
         return "opera7";
      }else if (version >= 5) {
         return "opera 5";
      }
      return false;
   }else if (typeof document.all != "undefined") {
      if(typeof document.getElementById != "undefined") {
         var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, "$1").replace(/ /, "");
         if(typeof document.uniqueID != "undefined") {
            if(browser.indexOf("5.5") != -1) {
               return browser.replace(/(.*5\.5).*/, "$1");
            }else {
               return browser.replace(/(.*)\..*/, "$1");
            }
         }else {
            return "ie5mac";
         }
      }
      return false;
   }else if(typeof document.getElementById != "undefined") {
      if(navigator.vendor.indexOf("Apple Computer, Inc.") != -1) {
         if(typeof window.XMLHttpRequest != "undefined") {
            return "safari1.2";
         }
         return "safari1";
      }else if(agent.indexOf("gecko") != -1) {
         return "mozilla";
      }
   }
   return false;
}

function getScrollPosition() {
   var position = [0, 0];

   if(typeof window.pageYOffset != 'undefined') {
      position = [
      window.pageXOffset,
      window.pageYOffset,
      ];
   }else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0) {
      position = [
      document.documentElement.scrollLeft,
      document.documentElement.scrollTop,
      ];
   }else if(typeof document.body.scrollTop != 'undefined') {
      position = [
      document.body.scrollLeft,
      document.body.scrollTop,
      ];
   }
   return position;
}

function getBrowserSize() {
   var size = [0, 0];

   if(typeof window.innerWidth != 'undefined') {
      size = [
      window.innerWidth,
      window.innerHeight
      ];
   }else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
      size = [
      document.documentElement.clientWidth,
      document.documentElement.clientHeight
      ];
   }else {
      size = [
      document.getElementsByTagName('body')[0].clientWidth,
      document.getElementsByTagName('body')[0].clientHeight,
      ];
   }
   return size;
}
/********** User info functions end **********/

/********** Functions for getting elements **********/
function getById(id)
{
	return document.getElementById(id);
}

function getByClass(classname, node) 
{
	if(!node)
	{
		node = document.getElementsByTagName("body")[0];
	}
	
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	
	for(var i = 0, j = els.length; i < j; i++)
	{
		if(re.test(els[i].className))
		{
			a.push(els[i]);
		}
	}
	
	return a;
}

function elementAttributes(e, ns)
{
	if (!this.__namespaceRegexps)
	{
		this.__namespaceRegexps = {};
	}
	
	var regexp = this.__namespaceRegexps[ns];
	
	if (!regexp)
	{
		this.__namespaceRegexps[ns] = regexp = 
		ns ? eval("/^" + ns + ":(.+)/") : /^([^:]*)$/;
	}
	
	var result = {};
	var atts = e.attributes;
	var l = atts.length;
	
	for (var i = 0; i < l; i++)
	{
		var m = atts[i].name.match(regexp);
		if (m)
		{
			result[m[1]] = atts[i].value;
		}
	}
	
	return result;
}

function getEventTarget(event)
{
   var targetElement = null;

   if (typeof event.target != "undefined")
   {
      targetElement = event.target;
   }
   else
   {
      targetElement = event.srcElement;
   }

   while (targetElement.nodeType == 3 &&
   targetElement.parentNode != null)
   {
      targetElement = targetElement.parentNode;
   }

   return targetElement;
}


function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	
	arrayPageSizeWithScroll = yWithScroll;
	//arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}
/********** Functions for getting elements end **********/

/********** Debugging Functions **********/
function dumpAlert(arr,level)
{
	var dumped_text = "";
	
	if(!level)
	{
		level = 0;
	}
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	
	for(var j = 0; j < level + 1; j++)
	{
		level_padding += "    ";
	}
	
	if(typeof(arr) == 'object') //Array/Hashes/Objects 
	{ 
		for(var item in arr)
		{
			var value = arr[item];
			
			if(typeof(value) == 'object') //If it is an array,
			{
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			}
			else
			{
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	}
	else //Stings/Chars/Numbers etc.
	{ 
		dumped_text = arr+": (" + typeof(arr) + ")";
	}
	
	alert(dumped_text);
}
/********** Debugging Functions End **********/

/********** Cookie Functions **********/
function setCookie(cookieName, cookieValue, nDays, secure)
{
	var theCookie = cookieName + "=" + cookieValue;

	// Cookie expiry date
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*nDays);
	theCookie += ";expires=" + expire.toGMTString();
	
	// Cookie path
	theCookie += ";path=/";
	
	// Secure cookie (https)
	if(secure)
	{
		theCookie += ";secure";
	}
	
	document.cookie = theCookie;
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	
	return "";
}
	
function deleteCookie(name, path, domain){
    if(getCookie(name))
	{
        setCookie(name, '', -30, path, domain);
    }
} 

/********** Cookie Functions End **********/

/********** Global Popup Functions **********/
function globalPopup(target, width, height, lightbox, lightboxColor, draggable, closeBtn, popupBodyColor, iframescrolling)
{	
	// Installation variables.
	var divAfter  = "wrapper";
	var divBefore = "header";
	
	if(!getById("popupBody"))
	{
		var additionSize = 42;
		
		// Set all the default values for the popup.
		if(!width)
		{
			width = 600;
		}
		
		if(!height)
		{
			height = 400;
		}
		
		if(!popupBodyColor)
		{
			popupBodyColor = "#FFFFFF";
		}
		
		if(!lightbox)
		{
			lightbox = false;
		}
		
		if(!lightboxColor)
		{
			lightboxColor = '#333333';
		}
		
		if(!draggable)
		{
			draggable = true;
		}
		
		if(!closeBtn)
		{
			closeBtn = true;
		}
		
		if(!iframescrolling)
		{
			iframescrolling = 'auto';
		}
		
		// If no lightbox set bg as white because of the shadow images.
		if(!lightbox)
		{
			popupBodyColor = "#FFFFFF";
		}
		
		// Get the href from the link and work out if it is a link or an element id
		var domain = 'http://' + window.location.hostname + '/';
		var targetElement = target.replace(domain, '');
		var targetObject = getById(targetElement);
		var isUrl = true;
		var popupContent = '';
		
		// Add the first half of the drop shadow.
		if(!lightbox)
		{
			popupContent += '<div id="popupBodyWrapper">';
			
			if(closeBtn)
			{
				popupContent += '<a id="popupCloseBtn" title="Close this popup" href="javascript:closePopup(0);"><img src="/templates/1/images/popup/close.png" alt="Close this popup" /></a>';
			}
			
			popupContent += '<div id="top_left"></div>';
			popupContent += '<div id="top_row"></div>';
			popupContent += '<div id="top_right"></div>';
			popupContent += '<div id="mid_left"></div>';
			popupContent += '<div id="popup_stage">';
		}
		
		if(targetObject)
		{
			// Is an element on the page so build the popup content.
			var attributes = elementAttributes(getById(targetElement));
			var attributeStr = '';
			
			for(key in attributes)
			{
				attributeStr += ' ' + key + '="' + attributes[key] + '"';
			}
			
			popupContent += '<div'+ attributeStr +'>' + getById(targetElement).innerHTML + '</div>';
			isUrl = false;
		}
		else
		{
			// Is an external link.
			popupContent += '<iframe src="' + target + '" scrolling="' + iframescrolling + '" frameborder="0" id="url_iframe" height="' + height + '" width="' + width + '"></iframe>';
		}
		
		// Add the second half of the drop shadow.
		if(!lightbox)
		{
			popupContent += '</div>';
			popupContent += '<div id="mid_right"></div>';
			popupContent += '<div id="btm_left"></div>';
			popupContent += '<div id="btm_row"></div>';
			popupContent += '<div id="btm_right"></div>';
			popupContent += '</div>';
		}
	
		// Firstly generate the translucent background for the popup if lightbox is set.
		if(lightbox)
		{
			var popupBack = document.createElement('div');
			popupBack.setAttribute('id', 'popupBackground');
			popupBack.setAttribute('onclick', 'closePopup();');
			
			var browserHeight = getBrowserSize();
			var siteHeight = getPageSizeWithScroll();
			var totalHeight;
			
			if(siteHeight <= browserHeight[1])
			{
				totalHeight = browserHeight[1];
			}
			else
			{
				totalHeight = siteHeight;
			}
			
			popupBack.style.height = totalHeight + 'px';
			popupBack.style.backgroundColor = lightboxColor;
		}
		
		// Then generate the popup body.
		var scrollPos = getScrollPosition();
		var dimentions = getBrowserSize();
	
		var positionx = (dimentions[0] - width)/2;
		var positiony = ((dimentions[1] - height)/2) + scrollPos[1];
		
		if(lightbox)
		{
			var lightboxClose = document.createElement('div');
			lightboxClose.setAttribute('id', 'lightboxclosebtn');
			lightboxClose.innerHTML = '<a id="popupCloseBtn" title="Close this popup" href="javascript:closePopup(0);"><img src="/templates/1/images/popup/close.png" alt="Close this popup" /></a>';
		}
		
		var popupBody = document.createElement('div');
		
		popupBody.setAttribute('id', 'popupBody');
		
		// Set the width and height plus shadow if no lightbox.
		if(!lightbox)
		{
			width += additionSize;
			height += additionSize;
		}
		
		popupBody.style.width   = width + 'px';
		popupBody.style.height  = height + 'px';
		popupBody.style.top     = positiony + 'px';
		popupBody.style.left    = positionx + 'px';
		popupBody.innerHTML     = popupContent;
	
		// If a lightbox is wanted then show this first then show the popup body.
		if(lightbox)
		{
			popupBody.style.backgroundColor = popupBodyColor;
			popupBody.style.display = 'none';
			popupBack.style.display = 'none';
			lightboxClose.style.display = 'none';
			
			// Add the background div to the page.
			getById(divAfter).insertBefore(popupBack, getById(divBefore));
			getById(divAfter).insertBefore(popupBody, getById(divBefore));
			getById(divAfter).insertBefore(lightboxClose, getById(divBefore));
			
			$('#popupBackground').slideToggle(
											"slow",
											function()
											{	
												$('#popupBody').fadeIn("normal");
												$('#lightboxclosebtn').slideToggle("normal");
											});
		}
		else
		{
			getById(divAfter).insertBefore(popupBody, getById(divBefore));
			popupBody.style.display = 'none';
			$('#popupBody').fadeIn("fast");
		}
		
		// Style the drop shadow.
		if(!lightbox)
		{
			var popup_stage = getById("popup_stage");
			var top_row     = getById("top_row");
			var mid_left    = getById("mid_left");
			var mid_right   = getById("mid_right");
			var btm_row     = getById("btm_row");
			
			// set the stage width.
			popup_stage.style.width = (width - additionSize) + 'px';
			popup_stage.style.height = (height - additionSize) + 'px';
			
			// Set the top row width;
			top_row.style.width = (width - additionSize) + 'px';
			
			// Set the mid left side height.
			mid_left.style.height = (height - additionSize) + 'px';
			
			// Set the mid right height.
			mid_right.style.height = (height - additionSize) + 'px';
			
			// Set the btm row width;
			btm_row.style.width = (width - additionSize) + 'px';
		}
		
		if(draggable)
		{
			$("#popupBody").Draggable();
		}
	}
}
	
function closePopup(lightbox) {
	// Installation variables.
	var divAfter  = "wrapper";
	
	// If there is a lightbox remove that before the popup body.
	if(!lightbox)
	{
	$('#popupBody').fadeOut(
							"fast",
							function()
							{
								var d = getById(divAfter);
								var background = getById('popupBody');
								d.removeChild(background);
								
								$('#lightboxclosebtn').slideUp(
									"normal",
									function()
									{
										var d = getById(divAfter);
										var background = getById('lightboxclosebtn');
										d.removeChild(background);
									});
								
								$('#popupBackground').slideUp(
									"normal",
									function()
									{
										var d = getById(divAfter);
										var background = getById('popupBackground');
										d.removeChild(background);
									});
							});
	}
	else
	{
		var d = getById(divAfter);
		var background = getById('popupBody');
		d.removeChild(background);
		
		$('#popupBody').slideUp(
								"normal",
								function()
								{
									var d = getById(divAfter);
									var background = getById('popupBody');
									d.removeChild(background);
								});
	}
}
/********** Global Popup Functions End **********/

function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}