/*****************************************************************************
* global variables
*****************************************************************************/
var curTab = 0;
var numTabs = 0;
var tabName = "";
var promoNum = 0;
var promoPage = "";
var headline = "";
var headlines = "";
var links = "";

/*****************************************************************************
* showTab - function for switching between tabs (i.e. on the product pages)
*****************************************************************************/
function showTab( tabNum )
{
    curTab = tabNum;
    for( i=0; i<numTabs; i++ ){
        page = document.getElementById( 'tabPage' + i );
        tab = document.getElementById( tabName + '_tab' + i );
        tabOn = document.getElementById( tabName + '_tab' + i + '_on' );
        tabOver = document.getElementById( tabName + '_tab' + i + '_over' );
        if( i == tabNum ){
	        page.className = tabName + '_tabPageTable';
	        tab.className = 'hidden';
	        tabOver.className = 'hidden';
	        tabOn.className = 'tab';
        }
        else{
	        page.className = 'hidden';
	        tab.className = 'tab';
	        tabOn.className = 'hidden';
        }
    }
}

/*****************************************************************************
* highlightTab - function for highlighting tabs (i.e. on the product pages)
*****************************************************************************/
function highlightTab( tabNum, bHighlight )
{
    if( tabNum != curTab ){
        tab = document.getElementById( tabName + '_tab' + tabNum );
        tabOver = document.getElementById( tabName + '_tab' + tabNum + '_over' );
        if( bHighlight ){
            tab.className = 'hidden';
            tabOver.className = 'tab';
        }
        else{
            tab.className = 'tab';
            tabOver.className = 'hidden';
        }
    }
}

/*****************************************************************************
* promoRollover - function for showing promo rollovers (i.e. on the home page)
*****************************************************************************/
function promoRollover( promoNum, bShow )
{
    promo = document.getElementById( promoPage + 'Promo' + promoNum );
    promoOver = document.getElementById( promoPage + 'Promo' + promoNum + '_over' );
    if( bShow ){
        promo.className = 'hidden';
        promoOver.className = promoPage + 'Promo_over';
    }
    else{
        promo.className = promoPage + 'Promo';
        promoOver.className = 'hidden';
    }
}

/*****************************************************************************
* showHeadline - function for rotating news headlines on the home page)
*****************************************************************************/
function showHeadline()
{
    headline = document.getElementById( 'a1NewsLink' );
    headline.innerHTML = headlines[ curHeadline ];
    headline.href = links[ curHeadline ];

    curHeadline++;
    if( curHeadline >= headlines.length ) curHeadline = 0;
}

/*****************************************************************************
* imageRollover - function for showing image button rollovers
*****************************************************************************/
	Rollimage = new Array()

	Rollimage[0]= new Image(121,153)
	Rollimage[0].src = "images/BTN_Dealer_OFF.gif"

	Rollimage[1] = new Image(121,153)
	Rollimage[1].src = "images/BTN_Dealer_ON.gif"

	function SwapOut() {
	document.imageRollover.src = Rollimage[1].src;
	return true;
	}

	function SwapBack() {
	document.imageRollover.src = Rollimage[0].src;
	return true;
	}

/*****************************************************************************
* Gallery popup - function for showing popup window in the gallery
*****************************************************************************/

	function popitup(url, pathImg) {
	url = url + "?pathImg=" + pathImg;
	//newwindow=window.open(url,'name','height=575, width=780, scrollbars=YES');
	newwindow=window.open(url,'name','height=690,width=670,status=no,scrollbars=no,resizable=no');
	if (window.focus) {newwindow.focus()}
	return false;
}

/*****************************************************************************
* Simple Make Element - Ratchet
*****************************************************************************/

function makeElement(name, attr, txt, cmt, data)
{
    var el = document.createElement(name);

    var u = "undefined";
    if(typeof attr != u && attr != null)
    {
        //Add attributes
        for(prop in attr)
        {
            if(prop.toString() == "cn")
            {
                el.className = attr[prop];
            }
            else if(prop.toString() == "style") 
            {
                for(style in attr[prop])
                {
                    if(style.toString() == "float")
                    {
                        if(typeof el.style.styleFloat != "undefined")
                            el.style.styleFloat = attr[prop][style];
                        else
                            el.style.cssFloat = attr[prop][style];
                    }
                    else
                    {
                        el.style[style.toString()] = attr[prop][style];
                    }
                }
            }
            else if (prop.toString() == "frameborder")
            {
                el.frameBorder = attr[prop];
            }
            else
            {
                el.setAttribute(prop.toString(), attr[prop]);
            }
        }
    }

    if(typeof txt != u && txt != null)
        el.appendChild(document.createTextNode(txt));
    
    if(typeof cmt != u && cmt != null)
        el.appendChild(document.createComment(cmt));

    if(typeof data != u && data != null)
		el.innerHTML = data;

    return el;
}

/*****************************************************************************
* AJAX Request Object Encaspulator - Ratchet
*****************************************************************************/
function getQueryVariable(name) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == name)
			return pair[1];
	}
	
	return null;
}

function getData(nodes) //Use this method when getting data in a CDATA area of an xml file
{
	for(var i = 0; i < nodes.length; i++)
		if(nodes[i].data.length > 0)
			return nodes[i].data;
}


function ajaxObj(url, request_params) {
	var ajax = this;
	this.request_timeout = 15000;
	this.maxRetry = 3;
	this.trys = 0;
	this.timeout = null;
	this.request_onTimeout = function()
	{ 	                            
		if(this.http_request != null && this.http_request.readyState < 4)
		{
			this.http_request.abort();
			clearTimeout(this.timeout);
			if(getQueryVariable("debug") != null)
			{
				if(confirm("A server timeout has occured, would you like to retry?"));
					this.init();
			}
			else
			{
				if(this.maxRetry > this.trys)
					this.init();
				else
					alert("A timeout error has occured, please check your internet connection.");
			}
			
		}
	};

	this.handler_params = new Array();
	this.handler_method = function() { return null; };
	
	this.http_request = null;
	this.xmlDoc = null;
	this.text = null;

	this.init = function()
	{
		this.trys += 1;
		
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			this.http_request = new XMLHttpRequest();

			if(typeof this.http_request.async != "undefined")
				this.http_request.async = true;            

		} else if (window.ActiveXObject) { // IE
		
			try
			{
				this.http_request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
			}
			catch (e)
			{
				try
				{
					this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e)
				{
				}
			}
		}
		else
		{
			alert("Your browser does not support AJAX");
		}
		
		if(this.http_request != null) {
			this.http_request.onreadystatechange = function() // 
			{
				if (ajax.http_request.readyState == 4) {
					clearTimeout(ajax.timeout);
					if (ajax.http_request.status == 200) {
						//alert(ajax.http_request.getResponseHeader("Content-Type"));
						//if((ajax.http_request.responseXML != null && ajax.http_request.responseXML.contentType == "text/xml" || ajax.http_request.getResponseHeader("Content-Type") == "application/xml") && ajax.http_request.responseXML.documentElement != null && ajax.http_request.responseXML.documentElement.nodeName != "parsererror")
							ajax.xmlDoc = ajax.http_request.responseXML;
						//else
							ajax.text = ajax.http_request.responseText;
							
						ajax.handler_method();
						ajax.http_request = null;						
					} else if (ajax.http_request.status != 0) {
						/* alerts with exception on bad request */
						if(getQueryVariable("debug") != null)
						{
							if(confirm("A server '" + ajax.http_request.status + ": " + ajax.http_request.statusText + "' error has occured, would you like see the details?"));
								document.body.innerHTML = "Page: " + document.location + "<br />AJAX Request: " + url + "?" + request_params + "<br /><br />" + ajax.http_request.responseText;
						}
						else
						{
							alert("Server Error '" + ajax.http_request.status + ": " + ajax.http_request.statusText + "'\n\nPlease nofity the developer with the following information:\n\nPage: " + document.location + "\nAJAX Request: " + url + "?" + request_params);
						}
						ajax.http_request.abort();
					}
				} else {
					if (ajax.http_request.readyState == 1) { // Set up timeout function
						ajax.timeout = setTimeout(ajax.request_onTimeout, ajax.request_timeout);
					}
				}
			};
			
			if (request_params == null) {
				this.http_request.open('GET', url, true);
				this.http_request.send(null);
			} else {
				this.http_request.open('POST', url, true);
				this.http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.http_request.setRequestHeader("Content-length", request_params.length);
				this.http_request.setRequestHeader("Connection", "close");
				this.http_request.send(request_params);
			}
		}			
		
		
	};
};

// IE Compatibility
var isIE = (typeof document.all != "undefined");
var isIE6 = false;

function setIE6()
{
    isIE6 = isIE && (typeof document.body.style.maxHeight == "undefined");
}



/*****************************************************************************
* Events
*****************************************************************************/


function addEvent(elm, evType, fn, useCapture) {
    
    if(typeof useCapture == "undefined") useCapture = false; // defaults to event bubbling
    
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
		
	}
	else {
		elm['on' + evType] = fn;
	}
}

function removeEvent(elm, evType, fn, useCapture) {

    if(typeof useCapture == "undefined") useCapture = false; // defaults to event bubbling

	if (elm.removeEventListener)
	{
		elm.removeEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.detachEvent) {
	    var r = elm.detachEvent('on' + evType, fn);
	    return r;
	}
	else {
	    elm['on' + evType] = null;
	}
}


/*****************************************************************************
* Expandable Term List Generator
*****************************************************************************/
	var termsIdArray = new Array();
	function showHideTerm(id, show)
	{
		
		for(var t = 0; t < termsIdArray.length; t++) // Close all other terms first
		{
			if(termsIdArray[t] != id)
			{
	            document.getElementById(termsIdArray[t]).className = "termHide";
				document.getElementById("i_" + termsIdArray[t]).src = "/images/plus.gif";	
			}
		}
		
		img = document.getElementById("i_" + id);
		element = document.getElementById(id);
		
	    if(element != null)
	    {
	        if(element.className.indexOf('termHide') != -1 || typeof show != "undefined")
			{
	            element.className = "";
				img.src = "/images/minus.gif";
				document.getElementById("a_" + id).focus();
			}
	        else
			{
	            element.className = "termHide";
				img.src = "/images/plus.gif";
			}
	    }
	}
	
	function getTerms(xmlURL, div, useDropDown)
	{
		if(typeof useDropDown == "undefined")
			useDropDown = false;
			
		var termRequest = new ajaxObj(xmlURL);
		termRequest.handler_params = new Array(div, useDropDown);
		termRequest.handler_method = function()
		{
			var is_ie = (document.all);
			
			var container = document.getElementById(this.handler_params[0]);
			var terms = this.xmlDoc.documentElement.getElementsByTagName("term");
			
			
			if(this.handler_params[1])
			{
				var drpDwnWrap = document.createElement("div");
				drpDwnWrap.style.textAlign = "right";
				
				drpDwn = document.createElement("select");
				drpDwn.id = "selectTerm";
				drpDwn.onchange = function() { if(this.options[this.selectedIndex].value != "") { showHideTerm(this.options[this.selectedIndex].value, true);window.location.hash = "#a_" + this.options[this.selectedIndex].value;} };
				drpDwn.style.marginBottom = "10px";
				var opt = document.createElement("option");
				opt.text = "- select a term -";
				opt.value = "";			
				
				if(is_ie)
					drpDwn.add(opt);
				else
					drpDwn.add(opt, null);				
				
				var setIndex = 0;
				
				for(var t = 0; t < terms.length; t++)
				{
					var id = terms[t].getAttribute("name").replace(/\s/g, "_").toLowerCase();
					
					opt = document.createElement("option");
					opt.text = terms[t].getAttribute("name");
					opt.value = id;
					
					if(is_ie)
						drpDwn.add(opt);
					else
						drpDwn.add(opt, null);

					if(document.location.hash.toString() == "#a_" + id)
						setIndex = drpDwn.options.length - 1

				}
				
				
				drpDwnWrap.appendChild(drpDwn);
				container.appendChild(drpDwnWrap);
				
				if(setIndex != 0)
					drpDwn.options[setIndex].selected = true;					
			}
			
			for(t = 0; t < terms.length; t++)
			{
				var id = terms[t].getAttribute("name").replace(/\s/g, "_").toLowerCase();
				
				termsIdArray[t] = id;
				
				var term = document.createElement("div");
				term.className = "term";
				
				var anchor = document.createElement("a");
				anchor.href = "javascript:showHideTerm('" + id + "');";
				anchor.setAttribute("id", "a_" + id);
				
				var img = document.createElement("img");
				img.setAttribute("id", "i_" + id);
				img.src = "/images/plus.gif";
				img.align = "left";
				img.border = "0";
				img.width = "9";
				img.height = "16";
				
				anchor.appendChild(img);
				anchor.appendChild(document.createTextNode(terms[t].getAttribute("name")));
				
				term.appendChild(anchor);				
				container.appendChild(term);
				
				var definition = document.createElement("div");
				definition.setAttribute("id", id);
				definition.className = "termHide";
				definition.innerHTML = getData(terms[t].childNodes);
				
				container.appendChild(definition);
			}
			
			if(document.location.hash.toString() != "")
				showHideTerm(document.location.hash.toString().replace(/\#a_/, ""));

		}
		termRequest.init();
		
	}
	
/*************************************************************
*      Media Pop Up Window
*************************************************************/
var mediaWin;
var mediaContainer;
function showMedia(attr)
{
	if(mediaWin != null)
		mediaWin.close();
		
	
	mediaWin = window.open("media.html?" + attr, "", "scrollbars=no,width=740,height=475,left="+ ((window.screen.availWidth - 740) / 2) + ",top=" + ((window.screen.availHeight - 475) / 2) + ",resizable=yes");
	mediaWin.focus();
}

var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

getOffsetTop = function(node){var t=0;while(node){if(typeof node.offsetTop!="undefined"){t+=node.offsetTop;}node=(typeof node.offsetParent!="undefined")?node.offsetParent:null;}return parseInt(t);};
getOffsetLeft = function(node){var l=0;while(node){if(typeof node.offsetLeft!="undefined"){l+=node.offsetLeft;}node=(typeof node.offsetParent!="undefined")?node.offsetParent:null;}return parseInt(l);};
getWinHeight = function(){ return (typeof window.innerHeight=="number")?parseInt(window.innerHeight):(document.documentElement && document.documentElement.clientHeight)?parseInt(document.documentElement.clientHeight):parseInt(document.body.clientHeight);};
getWinWidth = function(){ return (typeof window.innerWidth=="number")?parseInt(window.innerWidth):(document.documentElement && document.documentElement.clientWidth)?parseInt(document.documentElement.clientWidth):parseInt(document.body.clientWidth);};
getScrollTop = function(){ return (typeof window.pageYOffset=="number")?parseInt(window.pageYOffset):(document.body && document.body.scrollTop)?parseInt(document.body.scrollTop):parseInt(document.documentElement.scrollTop);};
getNextSiblingOf = function(siblingOf, tagName)
{
	if(typeof siblingOf.nextSibling.tagName != "undefined" && siblingOf.nextSibling.tagName.toLowerCase() == "div")
		return siblingOf.nextSibling;
	else
		return getNextSiblingOf(siblingOf.nextSibling, tagName);
}


function clearTree(node)
{
    if(node != null)
    {
        if(node.childNodes != null && node.childNodes.length > 0)
        {
            for(var x = node.childNodes.length - 1; x > -1; x--)
            {
                if(!isIE && node.childNodes[x].childNodes != null && node.childNodes[x].childNodes.length > 0)
                {
                    this.clearTree(node.childNodes[x]);
                }
                
                node.removeChild(node.childNodes[x]);
            }
        }
    }
}

function getData(nodes) //Use this method when getting data in a CDATA area of an xml file
{
	for(var i = 0; i < nodes.length; i++)
		if(nodes[i].data.length > 0)
			return nodes[i].data;
}

var zIndexMgr = new function zIndexMgrObj()
{   
    var _this = this;
    this.zIndex = 100;
    this.setzIndexOf = function(element)
    {
        if(element.style.zIndex < _this.zIndex || element.style.zIndex > 9000)
        {
            _this.zIndex++;
            element.style.zIndex = _this.zIndex;
        }
    };
}
/*** ENewsletter Begin ***/
	
function growSubmitBox()
{
	$(".enewsEmailSubmitBox").animate({height: 610}, 1000);
}

function showThankyou()
{
	$('html,body').animate({scrollTop: 0}, 1000);
	$(".enewsEmailSubmitBox").animate({height:60}, 1000);
}

var emailSubmitBox = new function emailSubmitBoxClass()
{
	var _this = this;
	this.openPrePopulated = function()
	{
		if($("#txtNombre").val().length == 0 || $("#txtApellido").val().length == 0 || $("#txtEmail").val().length == 0)
		{
			alert("Especificar todos los campos marcados con *");
		}
		else
		{
			var query = "?first=" + $("#txtNombre").val() + "&last=" + $("#txtApellido").val() + "&email=" + $("#txtEmail").val() + "&optin=" + $("#chkOptIn")[0].checked;
			_this.open(query);
		}
	};
	this.open = function(query)
	{
		if(typeof query == "undefined")
			query = "";
			
		var url = "enewsletter.html" + query;
		$('html,body').animate({scrollTop: 0}, 1000);
		$("body").append('<div class="washout" style="height:' + document.getElementById("all").offsetHeight + 'px">&nbsp;</div>');		
		$("body").append('<div class="enewsEmailSubmitBox"><iframe src="' + url + '" scrolling="no" frameborder="0" name="specFrame" id="specFrame"></iframe></div>');
	};
	this.close = function()
	{
		$(".enewsEmailSubmitBox").remove();
		$(".washout").remove();		
	};
}
/*** ENewsletter End ***/

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName]
	}
	else {
		return document[movieName]
	}
}