/*
	DEFINE GLOBAL VARIABLES
*/
var t; //Timeout variable used for category menus.

try {
var xmlhttp = new XMLHttpRequest();

} 
catch (E){
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

/*
    This function clears and restores input box text based on a default value.
   For an example please see the login box on the index page.
    
    elem = element that triggered the event
    strDefaultValue = Default value for this input.
    intToggle = 1: onmousedown  0: onblur
    
    Brian Smith April 25, 2008
*/

function toggleBoxValue(elem, strDefaultValue, intToggle)
{     
    if(intToggle == 1)
    {
        if(elem.value == strDefaultValue)
        {        
            elem.value = '';
            return true;
        }
    }
    else
    {
        if(elem.value.replace(/[- ' ' ]/g, '') == '')
        {
            elem.value = strDefaultValue;
            return true;
        }        
    }
}


/*
    Attempts to find the position of an elment on the screen.  Seems to be cross browser compatible.
    Script provided by www.quirksmode.com
    Brian Smith Feb. 15, 2008
*/
function findPos(obj) {
    var curleft = curtop = 0;
	if (obj.offsetParent) {
	    curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {			
		    curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/*
    Attempts to find the position of an elment on the screen.  Seems to be cross browser compatible.
    Script provided by www.quirksmode.com
    Brian Smith Feb. 15, 2008
*/
function findScrollOffset(obj) {
    var curleft = curtop = 0;
	if (obj.offsetParent) {
	    curleft = obj.scrollLeft 
		curtop = obj.scrollTop

		while (obj = obj.offsetParent) {
			curleft += obj.scrollLeft 
			curtop += obj.scrollTop
		}
	}
	return [curleft,curtop];
}

/*
    Utility function.  This takes a radio/select and returns which selection was made.
    Please note that this returns an HTML element.
*/

function getSelectedRadioButton(radioButton)
{   
    for(var i=0; i < radioButton.length; i++)
    {
        if(radioButton[i].checked || radioButton[i].selected)
           return radioButton[i];
    }    
}

/*
	This function toggles the category menus.  It uses AJAX to  do this.
	Calls getSubCatagories method.
*/
function toggleCategoryMenu(elem, state)
{
	var menu;
	var positionX;
	var positionY;

	menu = document.getElementById('category_menu');
	positionX = findPos(elem)[1];
	positionY = findPos(elem)[0] + 200;		
	if(state == 1)
	{		
		clearTimeout(t);
		menu.innerHTML = '';
		getSubCatagories(elem.id);
		menu.style.top = positionX + 'px';
		menu.style.left = positionY + 'px';				
		menu.style.display = 'inline';
	}
	else	
		t = setTimeout("document.getElementById('category_menu').style.display = 'none';", 250);
}


/*
	Sent silent request to refresh the catagory menu.
*/
function getSubCatagories(strCategoryPath)
{

	xmlhttp.open("GET", "/getSubCatagories.asp?categoryId=" + strCategoryPath,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			document.getElementById('category_menu').innerHTML = xmlhttp.responseText;
		}
	}
 xmlhttp.send(null)
}

/*
	Return a value from the query string
*/
function getValueFromQueryString(strTarget) {	
	var QS = window.location.search.substring(1, window.location.search.length);
	var qsPairs = QS.split("&");
	
	var key, item, splitIndex;
		
	for(var i = 0; i < qsPairs.length; i++) {
		splitIndex = qsPairs[i].indexOf("=");
		key = qsPairs[i].substring(0, splitIndex);
		item = qsPairs[i].substring(splitIndex + 1, qsPairs[i].length);
	    if(strTarget == key)		
			return item;
	}
	
	return '';
}


/*
    Handles changes the opacity of an element. 
    Cross browser friendly!
*/
function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

/*
    Get's the opacity value for an object.
*/
function getOpacity(obj)
{
    return obj.style.opacity
}

/*
    Displays a div and handles fading the main pages content.
*/
function fadeAndAlert()
{
    var elem = document.getElementById('message');
    
    if(elem.style.display == 'none')
    {
        fadeOutElement('body_content', 100);
        elem.style.display = 'inline';
    }
    else
    {
        fadeInElement('body_content', 25);
        elem.style.display = 'none';
    }
}

/*
    Fades an elem to a given opacity over time.
*/
function fadeInElement(elem, opacity)
{
    element = document.getElementById(elem);
    if(opacity <= 100)
    {
        setOpacity(element, opacity);
        opacity += 10;
        setTimeout("fadeInElement('" + elem + "', " + opacity + ")", 100);    
    }
}

function fadeOutElement(elem, opacity)
{
    element = document.getElementById(elem);
    if(opacity >= 25)
    {
        setOpacity(element, opacity);
        opacity -= 10;
        setTimeout("fadeOutElement('" + elem + "', " + opacity + ")", 100);    
    }
}

/*
	Toggles an Elements background color between a given color and white.
*/
function toggleElementBGColor(elem, strColor)
{
	if(elem.style.backgroundColor == 'White'  || elem.style.backgroundColor == '')			
		elem.style.backgroundColor = strColor; 
	else
		elem.style.backgroundColor = 'White';		
}


// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{	
	bubbling = bubbling || false; 	
	
	// Standard Firefox, Mac broswers.
	if(window.addEventListener)	
	{
		element.addEventListener(type, expression, bubbling);		
		return true;	
	} 
	// IE	
	else if(window.attachEvent) 
	{ 	
		element.attachEvent('on' + type, expression);		
		return true;	
	} 
	// Catch possible problems.
	else 
		return false;
}

function addZoomIcon()
{   
	//document.getElementById('product_list').insertBefore(newImage);
	var elements = getElementsByClassName('addZoom');

	for(var i = 0; i < elements.length; i++)
	{
		if(imageLoaded(elements[i])){
			height = (elements[i].height - 16);
			width = (elements[i].width - 16);
			try{
				newImage = document.createElement('<img src="/images/glass.png" style="position:absolute; top:' + height + 'px; left:'+ width + 'px;" border="0"/>');
			}
			catch(e){
				newImage = document.createElement("img");				
				newImage.setAttribute("src", "/images/glass.png");
				newImage.setAttribute("style", "position:absolute; top:" + height + "px; left:" + width + "px;");
				newImage.setAttribute("border", "0");
			}
			
			var pos = findPos(elements[i]);			
			elements[i].parentNode.parentNode.appendChild(newImage);		
			
		}
	}
}

/*
	Search the DOM for elements with a certain class name.
	Returns an array of elements with that class name.
*/
function getElementsByClassName(strName)
{
	var elem = document.getElementsByTagName('*');
	var returnArray = new Array();
	for(var i = 0; i < elem.length; i++)
	{
		if(elem[i].className == strName)
			returnArray.push(elem[i]);			
	}
	return returnArray;
}

/*
	Test to see if an image loaded correctly.
	Works in FF, IE7, Safari, IE6.
*/

function imageLoaded(elem)
{
    if (!elem.complete) {
        return false;
    }
    if (typeof elem.naturalWidth != "undefined" && elem.naturalWidth == 0) {
        return false;
    }

    return true;
}

/*
	Bookmarks the current page.
*/

function bookmarkPage()
{
	if(window.sidebar)
		window.sidebar.addPanel('Cables To Go', 'http://www.cablestogo.co.uk/index.asp', '');
	if(window.external)
		window.external.AddFavorite('http://www.cablestogo.co.uk/index.asp', 'Cables To Go');	
}


/****************************************
	Pop up an image in a bigger size based on roll over
****************************************/
function enlargedImageRollover(elem)
{
	var product_list = document.getElementById('productList');
	
	if(!document.getElementById('imagePopup'))
	{
		//add controller div
		try{
			divElement = document.createElement("<div id='imagePopup' style='display:none; border:solid 1px black; position:absolute; top:0px; left:0px; z-index:50;'></div>");	
		}	
		catch(e){
			divElement = document.createElement("div");			
			divElement.setAttribute("id", "imagePopup");			
			divElement.setAttribute("style", "display:none; position:absolute; top:0px; left:0px; z-index:50; border:solid 1px black;");			
		}		
		document.body.appendChild(divElement);			
	}
	
	if(!document.getElementById('largerImage'))	{	
		try{			
			imgElement = document.createElement("<img id='largerImage' src='#' />");			
		}	
		catch(e){
			
			imgElement = document.createElement("img");
			imgElement.setAttribute("id", "largerImage");
			imgElement.setAttribute("src", "#");			
		}			
		document.getElementById('imagePopup').appendChild(imgElement);	
	}
	
	if(elem){
		//Set the image Path.        
		var newPath = elem.src;	
		
		/*
		  Find the position of the elem that fired the event on the screen.
		  Split the result into an array for use later.
	   */
		var intPos = findPos(elem);
		var scrollPos = findScrollOffset(elem);
		scrollPos[1] = document.getElementById('productList').scrollTop;
		/*
		 Set up the div and image to be displayed.
	   */

		var div;
		var img;
		div = document.getElementById('imagePopup');
		img = document.getElementById('largerImage');
		img.src = newPath.replace('/thumb', '');
		
		div.style.top = (intPos[1] - scrollPos[1] - (img.height/2) + elem.height)  +  'px';
		div.style.left = (intPos[0] - scrollPos[0] + elem.width + 3) + 'px';


		
		//Toggle the image based if it is displayed or hidden.
		if(div.style.display == "none")
		   div.style.display = "inline";
		
		else
			div.style.display ="none";
	}
}
