/*****************************************************************************
* global variables
*****************************************************************************/
if(document.domain.indexOf("internationaltrucks.com") != -1)
	document.domain = "internationaltrucks.com";

function isReady() {
                return true;
}

var curTab = 0;
var numTabs = 0;
var tabName = "";
var promoNum = 0;
var promoPage = "";
var headline = "";
var headlines = "";
var links = "";


/* //////////////////////////////////////////////////////////////////////////
// Returns url vars
////////////////////////////////////////////////////////////////////////// */
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        //vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
var currentURLVars = getUrlVars();

/*****************************************************************************
* open on page load
*****************************************************************************/
$(function() {
initDemoVideo();
	if(getQueryVariable("openConfig") != null) { 
		configPopOver.open();
	}
});

/* //////////////////////////////////////////////////////////////////////////
//autoplay workstar video
//////////////////////////////////////////////////////////////////////////*/
function initDemoVideo()
{
	var urlVars = getUrlVars();
	if(urlVars["playcngvideo"])
	{
		workstarCNG();
	}
}

/*****************************************************************************
* 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;
}

/*****************************************************************************
* 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)
		{
			if(pair[1].indexOf("#") != -1)
			{
				var nohash = pair[1].split("#");
				return nohash[0];
			}
			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");
}

/*****************************************************************************
* Add hash to current URL - fascilitate deep linking in flash pieces
*****************************************************************************/
function setHash(hash) {
	window.location.hash = hash;
}


/*****************************************************************************
* 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 showPDFThumb(name,pdfLoc,w,h)
{
	//mediaWin = window.open("/StaticFiles/internationalTrucks/Images/" + name, "", "scrollbars=no,width=" + w + ",height=" + h + ",left="+ ((window.screen.availWidth - w) / 2) + ",top=" + ((window.screen.availHeight - h) / 2) + ",resizable=yes");
	mediaWin = window.open("/includes/pdfthumb.html?pdfLoc=" + pdfLoc + "&name=" +name, "", "scrollbars=no,width=" + w + ",height=" + h + ",left="+ ((window.screen.availWidth - w) / 2) + ",top=" + ((window.screen.availHeight - h) / 2) + ",resizable=yes", "location=0, toolbar=0");
	mediaWin.focus();
}

function showMedia(name,w,h,noWin,noClose)
{
	if(mediaWin != null)
		mediaWin.close();		
	
	if(typeof noWin == "undefined" || !noWin)
	{	
		if(typeof noClose == "undefined")
			h += 40;

		mediaWin = window.open("/includes/media.html?name=" + name, "", "scrollbars=no,width=" + w + ",height=" + h + ",left="+ ((window.screen.availWidth - w) / 2) + ",top=" + ((window.screen.availHeight - h) / 2) + ",resizable=yes");
		mediaWin.focus();
	}
	else
	{
		var mediaLoader = new ajaxObj("/includes/media.xml");
		mediaLoader.handler_params = new Array(name);
		
		mediaLoader.handler_method = function() {
			var mediaItems = this.xmlDoc.documentElement.getElementsByTagName("item");
			var item;
			
			for(var i = 0; i < mediaItems.length; i++)
				if(mediaItems[i].getAttribute("name") == this.handler_params[0])
					item = mediaItems[i];
			
			if(item != null)
			{
				var w = item.getAttribute("width");
				var h = item.getAttribute("height");
				var url = item.getAttribute("url");
				
				var winWidth = 0, winHeight = 0;
				if( typeof(window.innerWidth) == 'number' ) {
					//Non-IE
					winWidth = window.innerWidth;
					winHeight = window.innerHeight;
				} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
					//IE 6+ in 'standards compliant mode'
					winWidth = document.documentElement.clientWidth;
					winHeight = document.documentElement.clientHeight;
				} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
					//IE 4 compatible
					winWidth = document.body.clientWidth;
					winHeight = document.body.clientHeight;
				}				
				winWidth = winWidth - 20;
				
				mediaContainer = document.createElement("div");
				mediaContainer.style.position = "absolute";
				mediaContainer.style.top = "0px";
				mediaContainer.style.left = "0px";				
				mediaContainer.style.zIndex = "300";
				mediaContainer.style.width = winWidth + "px";
				mediaContainer.style.height = winHeight + "px";
				
				var calcTop = ((winHeight - h) / 2);
				if(calcTop < 120)
					calcTop = 120;

				var closeButton = makeElement("a", {href:"javascript:void(0)",style:{backgroundColor:"black",display:"block",position:"absolute",top:(calcTop-19)+"px",left:(((winWidth-w)/2)-20)+"px",width:w+"px",textAlign:"center",zIndex:"500",paddingTop:"3px",paddingBottom:"3px"}}, "Click here to close");
				closeButton.onclick = function() { document.body.removeChild(mediaContainer); };
				
				var mediaBox = makeElement("div", {id:"media",style:{zIndex:"600",position:"absolute",top:calcTop+"px",left:(((winWidth-w)/2)-20)+"px",height:h+"px",width:w+"px"}});

				mediaContainer.appendChild(closeButton);
				mediaContainer.appendChild(mediaBox);
				document.body.appendChild(mediaContainer);
				
				switch(item.getAttribute("type"))
				{
					case "video":
						var vid = document.createElement('a');
						vid.className = "xvid {width:" + w + ", height:" + h + "}";
						vid.setAttribute("href", url);

						mediaBox.appendChild(vid);

						$('a.xvid').media();				
						break;
					case "flash":
						var swf = new SWFObject(url,item.getAttribute("name"), w, h, '7', '#000000');
						var attribs = item.getElementsByTagName("attr");
						for(var p = 0; p < attribs.length; p++)
						{
							var attrName = attribs[p].getAttribute("name");
							var attrValue = attribs[p].getAttribute("value");
							if(attribs[p].getAttribute("type") == "v")
								swf.addVariable(attrName, attrValue);
							else
								swf.addParam(attrName, attrValue);
						}
						swf.write("media");	
						break;
					default:
						alert("Unkown media type");
						break;
				}
			}
			else
			{
				alert("Video not found");
			}
		}
		mediaLoader.init();		
	}
	//return false;
}

if(getQueryVariable("showmedia") != null)
{
	var mediaToShow = (getQueryVariable("vidID") != null) ? getQueryVariable("showmedia") + "&vidID=" + getQueryVariable("vidID") : getQueryVariable("showmedia");
	setTimeout('showMedia("' + mediaToShow + '", 740, 475)', 500);
}

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]);
            }
        }
    }
}

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;
        }
    };
}


/**** Truck Finder 2.0 ****/
var TruckFinder = new function TruckFinderClass()
{
	this.truckList = new Object();
	this.gridObj = function(id, ovrImg, specImg, lgImg, detailURL, specURL, copy)
	{
		var _this = this;
		this.lnk = document.getElementById(id);
		this.img = _this.lnk.getElementsByTagName("img")[0];
		this.compare = _this.lnk.getElementsByTagName("input")[0];
		this.compare.checked = false;
		this.compareLbl = _this.lnk.getElementsByTagName("label")[0];
		this.ovrImg = new Image(225,174);
		this.ovrImg.src = ovrImg;
		this.offImg = new Image(225,174);
		this.offImg.src = _this.img.src;
		this.specImg = new Image(240,240);
		this.specImg.src = specImg;
		this.lgImg = new Image(100,100);
		this.lgImg.src = lgImg;
		this.detailURL = detailURL;
		this.specURL = specURL;
		this.copy = copy;
		this.hovering = false;
		this.popOutTimeout = null;
		this.showPopOut = function()
		{
			clearTimeout(_this.popOutTimeout);
			if(_this.hovering)
			{
				zIndexMgr.setzIndexOf(_this.lnk);
				TruckFinder.popOutManager.show(_this);
			}
		};
		this.lnk.onmouseover = function()
		{
			_this.hovering = true;
			_this.img.src = _this.ovrImg.src;
			_this.popOutTimeout = setTimeout(_this.showPopOut, 200);
		};
		this.lnk.onmouseout = function()
		{
			_this.hovering = false;
			_this.img.src = _this.offImg.src;
			setTimeout(TruckFinder.popOutManager.remove, 10);
		};
		this.compare.onclick = function()
		{
			TruckFinder.compareQueue.comparisonBox = _this.compare;
			TruckFinder.compareQueue.timeout = setTimeout(TruckFinder.compareQueue.toggleCompare, 10);
			return false;
		};
		this.compareLbl.onclick = function()
		{
			_this.compare.click();
			return false;
		};
	};	
	this.listItemObj = function(id, ovrImg)
	{
		var _this = this;
		this.listItem = document.getElementById(id);
		this.img = _this.listItem.getElementsByTagName("img")[0];
		this.compare = _this.listItem.getElementsByTagName("input")[0];
		this.ovrImg = new Image(225,174);
		this.ovrImg.src = ovrImg;
		this.offImg = new Image(225,174);
		this.offImg.src = _this.img.src;
		this.listItem.onmouseover = function()
		{
			_this.img.src = _this.ovrImg.src;
		};
		this.listItem.onmouseout = function()
		{
			_this.img.src = _this.offImg.src;
		};
		this.compare.onclick = function()
		{
			TruckFinder.compareQueue.toggleCompare(_this.compare);
		};
	};
	this.popOutManagerObj = function()
	{
		var _this = this;
		this.showing = false;
		this.popOut = null;
		this.lnk = null;
		this.gridObj = null;
		this.detailImg = new Image(80,20);
		this.detailImg.src = "/StaticFiles/internationalTrucks/Site Assets/Products/truck_detail_link.gif";
		this.specImg = new Image(80,20);
		this.specImg.src = "/StaticFiles/internationalTrucks/Site Assets/Products/full_spec_link.gif";
		this.ieLinks = null;
		this.show = function(gridObj)
		{
			if(!_this.showing)
			{
				var t = "-250px";
				var onLeft = ((getOffsetLeft(gridObj.lnk) + 50) < 480);
				var l =  onLeft ? "50px" : "-450px";
				var cn = onLeft ? "atAGlancePopOut left" : "atAGlancePopOut right";
				_this.gridObj = gridObj;
				_this.popOut = makeElement("div", {cn:cn,style:{top:t,left:l}});
				
				_this.popOut.appendChild(makeElement("div", {cn:"info"}));
				_this.popOut.childNodes[0].appendChild(makeElement("img", {src:_this.gridObj.specImg.src}));
				_this.popOut.childNodes[0].appendChild(makeElement("div", {cn:"copy"}, null, null, _this.gridObj.copy));
				_this.popOut.childNodes[0].appendChild(makeElement("div", {cn:"links"}));
				if(!isIE)
				{
					_this.popOut.childNodes[0].childNodes[2].appendChild(makeElement("a", {href:_this.gridObj.detailURL,cn:"detail"}));
					_this.popOut.childNodes[0].childNodes[2].childNodes[0].appendChild(makeElement("img",{src:_this.detailImg.src}));
					_this.popOut.childNodes[0].childNodes[2].appendChild(makeElement("a", {href:_this.gridObj.specURL}));
					_this.popOut.childNodes[0].childNodes[2].childNodes[1].appendChild(makeElement("img",{src:_this.specImg.src}));
				}
				
				_this.popOut.appendChild(makeElement("img", {cn:"lgImg",src:_this.gridObj.lgImg.src}));
				_this.popOut.appendChild(makeElement("div", {cn:"clr"}, null, "clr"));
				_this.gridObj.lnk.appendChild(_this.popOut);	

				if(isIE)
				{
					l =  onLeft ? "100px" : "-400px";
					_this.ieLinks = makeElement("div", {style:{position:"absolute",top:"5px",left:l,zIndex:"1000",width:"300px"}});
					_this.ieLinks.appendChild(makeElement("a", {href:_this.gridObj.detailURL,cn:"detail"}));
					_this.ieLinks.childNodes[0].appendChild(makeElement("img",{src:_this.detailImg.src}));
					_this.ieLinks.appendChild(makeElement("a", {href:_this.gridObj.specURL,style:{marginLeft:"55px"}}));
					_this.ieLinks.childNodes[1].appendChild(makeElement("img",{src:_this.specImg.src}));
					_this.gridObj.lnk.appendChild(_this.ieLinks);
				}
				
				_this.showing = true;
			}
			else
			{
				//_this.hovering = false;
				_this.remove();
			}
		};
		this.remove = function()
		{
			if(_this.gridObj != null && _this.popOut != null && !_this.gridObj.hovering && _this.popOut.parentNode == _this.gridObj.lnk)
			{
				clearTree(_this.popOut);
				_this.gridObj.lnk.removeChild(_this.popOut);
				
				if(isIE)
				{
					clearTree(_this.ieLinks);
					_this.gridObj.lnk.removeChild(_this.ieLinks);
				}
				
				_this.showing = false;
			}
		};
	};
	this.popOutManager = new this.popOutManagerObj();
	
	this.compareQueueObj = function()
	{
		var _this = this;
		this.timeout = null;
		this.compareItems = new Array();
		this.comparisonBox = null;
		this.toggleCompare = function(box)
		{
			if(typeof box != "undefined" && typeof box.tagName != "undefined")
				_this.comparisonBox = box;
			
			if(_this.timeout != null)
				_this.comparisonBox.checked = !_this.comparisonBox.checked;
			
			if(_this.comparisonBox.checked)
				_this.addCompareItem(_this.comparisonBox);
			else
				_this.removeCompareItem(_this.comparisonBox);
		};
			
		this.addCompareItem = function(chkBox)
		{
			if(_this.compareItems.length < 3)
			{
				_this.compareItems.push(chkBox.value);			
			}
			else
			{
				chkBox.checked = false;
				alert("You may only compare up to three vehicles at a time.");
			}
		};
		this.removeCompareItem = function(box)
		{
			for(var i = 0; i < _this.compareItems.length; i++)
			{
				if(_this.compareItems[i] == box.value)
				{

					_this.compareItems.splice(i,1);
					break;
				}
			}		
		};
		this.clearCompareItems = function(){
			_this.compareItems = new Array();
		}
		this.openComparison = function()
		{
			if(_this.compareItems.length > 1)
			{
				specBox.open(_this.compareItems.toString());
			}
		};
		this.removeColumn = function(col, modelId)
		{
			TruckFinder.truckList[modelId].compare.checked = false;
			_this.removeCompareItem(TruckFinder.truckList[modelId].compare);
			if(_this.compareItems.length > 0)
			{
				var elements = getElementsByClassName(col.className, "div", col.parentNode.parentNode);
				for(var e = 0; e < elements.length; e++)
				{
					clearTree(elements[e]);
					elements[e].parentNode.removeChild(elements[e]);
				}
				specBox.adjustSize();
			}
			else
			{
				specBox.close();
			}
		};
	};
	this.compareQueue = new this.compareQueueObj();
	
	this.currentView = (getQueryVariable("view") != null) ? getQueryVariable("view") : "grid";
	this.currentSort = (getQueryVariable("sort") != null) ? getQueryVariable("sort") : "series";
	
	this.changeView = function(chkbox)
	{
		if(chkbox.value != this.currentView)
		{
			this.currentView = chkbox.value;
			this.refresh();
		}
	};
	this.changeSort = function(selbox)
	{
		if(selbox.options[selbox.selectedIndex].value != this.currentSort)
		{
			this.currentSort = selbox.options[selbox.selectedIndex].value;
			this.refresh();
		}
	};
	this.refresh = function()
	{
		window.location.href = window.location.pathname + "?view=" + this.currentView + "&sort=" + this.currentSort;
	};
	this.swapImage = function(lnk)
	{
		var imgs = lnk.getElementsByTagName("img");
		for(var i = 0; i < imgs.length; i++)
			imgs[i].className = (imgs[i].className.toString() == "") ? "hidden" : "";
		
	}
}

var specBox = new function specBoxClass()
{
	var _this = this;
	this.box = null;
	this.washout = null;
	this.open = function(query)
	{
		var url = "/itrucks/webservices/specsgenerator.jsp?models=" + query;
		if(_this.box == null)
		{
			_this.washout = makeElement("div", {cn:"washout", style:{height:document.getElementById("all").offsetHeight + "px"}});
			_this.box = makeElement("div", {cn:"specBox"});
			_this.box.appendChild(makeElement("iframe", {src:url,frameborder:0,name:"specFrame",id:"specFrame"}));
			document.body.appendChild(_this.washout);			
			document.body.appendChild(_this.box);			
		}
		else
		{
			_this.washout.className = "washout";			
			_this.box.className = "specBox";			
			window.frames["specFrame"].location.href = url;
		}
		
		zIndexMgr.setzIndexOf(_this.washout);
		zIndexMgr.setzIndexOf(_this.box);
		var offset = 40;
		if(getScrollTop() < 60)
			offset = 110 - getScrollTop();
		
		_this.box.style.top = (getScrollTop() + offset) + "px";
	};
	this.close = function()
	{
		_this.box.className = "hidden";
		_this.washout.className = "hidden";
		window.frames["specFrame"].location.href = "about:blank";
	};
	this.toggleSpec = function(lnk)
	{
		var img = lnk.getElementsByTagName("img")[0];
		getNextSiblingOf(lnk.parentNode, "div").className = (img.src.match("opened")) ? "hidden" : "specs";
		img.src = (img.src.match("opened")) ? "/StaticFiles/internationalTrucks/Site Assets/Products/spec_closed.gif" : "/StaticFiles/internationalTrucks/Site Assets/Products/spec_opened.gif";
		_this.adjustSize();
	};
	this.adjustSize = function()
	{
		document.getElementById("specFrame").style.height = (window.frames["specFrame"].document.body.offsetHeight + 10 ) + "px";
		_this.box.style.height = (window.frames["specFrame"].document.body.offsetHeight + 10 ) + "px";
	};
}

function showPropsOf(obj)
{
    var props = "";
    for(prop in obj)
    {
        props += prop + "=" + obj[prop] + "\n";
    }
    alert(props);
}

var DetailPage = new function detailPageClass()
{
	var _this = this;
	var brochureLengthNumberNew = null;
	var brochureFirstLoad = true;
	this.usagesXML = null;
	this.usageMenu = null;
	this.lnk = null;
	this.hovering = false;
	this.usageOvr = new Image(160,22);
	this.usageOvr.src = '/StaticFiles/internationalTrucks/Site Assets/Products/truckusage_ovr.png';
	this.usageOff = new Image(160,22);
	this.usageOff.src = '/StaticFiles/internationalTrucks/Site Assets/Products/truckusage.png';
	this.hideUsageMenu = function()
	{
		if(!_this.hovering && _this.usageMenu.parentNode == _this.lnk)
		{
			_this.usageMenu.style.display = "none";
			_this.lnk.style.backgroundImage = "url('" + _this.usageOff.src + "')";
		}
	};
	this.animTimeout = null;
	this.animLoading = function()
	{		
		clearTimeout(_this.animTimeout);
		if(_this.requestOut)
		{
			el = _this.usageMenu.childNodes[0].childNodes[0].childNodes[0];
			
			var txt = el.childNodes[0].nodeValue;

			if(el.childNodes[0].nodeValue.length  < 15)
				txt += ".";
			else
				txt = "Loading";
			
			el.replaceChild(document.createTextNode(txt), el.childNodes[0]);
			
			_this.animTimeout = setTimeout(_this.animLoading, 200);
		}
	};
	this.initMenu = function()
	{
		//<div class="truckUsageMenu">
		//	<div class="menuBody">
		//		<div class="menuItems">
		//			<a href="#">Stuff</a>
		// 		</div>
		//	</div>
		//  <div class="menuCap">&nbsp;</div>
		//</div>
		_this.usageMenu = makeElement("div", {cn:"truckUsageMenu",style:{top:"22px"}});
		_this.usageMenu.appendChild(makeElement("div", {cn:"menuBody", style:{height:"20px"}}));
		_this.usageMenu.childNodes[0].appendChild(makeElement("div", {cn:"menuItems"}));
		_this.usageMenu.childNodes[0].childNodes[0].appendChild(makeElement("a", {href:'javascript:void(0)'}, "Loading"));		
		_this.usageMenu.appendChild(makeElement("div", {cn:"menuCap"}, null, null, '&nbsp;'));			
		_this.lnk.appendChild(_this.usageMenu);
		zIndexMgr.setzIndexOf(_this.usageMenu);
		_this.animTimeout = setTimeout(_this.animLoading, 200);
		_this.lnk.onmouseout = function() { DetailPage.hovering = false; setTimeout(DetailPage.hideUsageMenu, 50); };
		
	};
	this.requestOut = false;
	this.gatherUsages = function(el, id, isSeries)
	{
		if(!_this.hovering)
		{
			_this.hovering = true;
			_this.lnk = el;
			
			if(_this.usagesXML == null && !_this.requestOut)
			{
				_this.requestOut = true;
				_this.initMenu();
				//var usageRequest = new ajaxObj("usages.xml");
				var params = (isSeries) ? "seriesid=" + id : "modelid=" + id;
				var usageRequest = new ajaxObj("/itrucks/UsagesXMLProvider",params);
				usageRequest.handler_method = function()
				{
					DetailPage.requestOut = false;
					clearTimeout(_this.animTimeout);
					
					clearTree(DetailPage.usageMenu.childNodes[0].childNodes[0]);

					if(this.xmlDoc.documentElement.childNodes.length > 0)
					{					
						DetailPage.usagesXML = this.xmlDoc.documentElement.getElementsByTagName("usage");
						
						for(var u = 0; u < DetailPage.usagesXML.length; u++)
							DetailPage.usageMenu.childNodes[0].childNodes[0].appendChild(makeElement("a", {href:DetailPage.usagesXML[u].getAttribute("link")}, DetailPage.usagesXML[u].getAttribute("text")));

						DetailPage.usageMenu.childNodes[0].style.height = (DetailPage.usagesXML.length * 20) + "px";					
					}
					else
					{
						DetailPage.usagesXML = "none";
						DetailPage.usageMenu.childNodes[0].childNodes[0].appendChild(makeElement("a", {href:"javascript:void(0)"}, "No Usages Defined"));
					}
					
				};
				usageRequest.init();
			}
			else if(_this.usageMenu != null)
			{
				_this.usageMenu.style.display = "block";
			}
			_this.lnk.style.backgroundImage = "url('" + _this.usageOvr.src + "')";
			_this.lnk.style.backgroundColor = "#E5E5E5";
		}
	};
	
	this.clickToView = makeElement("img", {src:"/StaticFiles/internationalTrucks/Site Assets/Products/click_to_view.gif",cn:"clickToView"});
	this.clickHere = function()
	{
		if(_this.clickToView.parentNode == null)
		{
			_this.clickToView.style.top = "165px";
			_this.clickToView.style.left = "0px";
			this.appendChild(_this.clickToView);
			zIndexMgr.setzIndexOf(_this.clickToView);
		}
	};
	
	this.clickHereOff = function()
	{
		if(_this.clickToView.parentNode != null && _this.clickToView.parentNode == this)
		{
			this.removeChild(_this.clickToView);
		}
	};

	
	this.contentBlocks = new Array();
	this.tabs = null;
	this.secondaryNav = null;
	this.secondaryNavItems = new Array();
	this.tabContentItems = 0;

	this.initTabContents = function(items)
	{
		_this.tabContentItems = items;

		var tabContent = document.getElementById("tabContent");
		var divs = tabContent.getElementsByTagName("div");

		for(var d = 0; d < divs.length; d++){
			if(divs[d].parentNode == tabContent){
				_this.contentBlocks[_this.contentBlocks.length] = divs[d];		
			}
		}

		for(var idx = 0; idx < items.length; idx++)
		{
			if(idx === 0) // Brochures
			{
				_this.contentBlocks[idx].style.width = (items[idx].length * 160) + "px";
				brochureLengthNumberNew = items[idx].length;
				
				for(var i = 0; i < items[idx].length; i++)
				{//name, attr, txt, cmt, data
					_this.contentBlocks[idx].appendChild(makeElement("a", {href:items[idx][i].url,target:"_blank",cn:"brochure"}));
					_this.contentBlocks[idx].childNodes[i].appendChild(makeElement("img", {src:items[idx][i].img}));
					if(items[idx][i].title)
						_this.contentBlocks[idx].childNodes[i].appendChild(makeElement("h1", {cn:"brochureName"}, null, null, items[idx][i].title));
					_this.contentBlocks[idx].childNodes[i].onmouseover = _this.clickHere;
					_this.contentBlocks[idx].childNodes[i].onmouseout = _this.clickHereOff;
				}
			}
			else if(idx == 1) // Recommendations
			{
				_this.contentBlocks[idx].style.width = (items[idx].length * 225) + "px";
				
				for(var i = 0; i < items[idx].length; i++)
				{
					_this.contentBlocks[idx].appendChild(makeElement("a", {href:items[idx][i].url,title:" "}));
					_this.contentBlocks[idx].childNodes[i].appendChild(makeElement("img", {src:items[idx][i].img,alt:items[idx][i].ovr}));
					_this.contentBlocks[idx].childNodes[i].childNodes[0].onmouseover = function() { var i = this.src; this.src = this.alt; this.alt = i; };
					_this.contentBlocks[idx].childNodes[i].childNodes[0].onmouseout = function() { var i = this.src; this.src = this.alt; this.alt = i; };
				}
				
			}
			else if(idx == 2) // Wallpapers
			{
				_this.contentBlocks[idx].style.width = (items[idx].length * 175) + "px";
				
				//{thumb:"#",title:"",links:[{url:"#",dimensions:"1280x1025",typesize:"(JPG, 119K)"},{url:"#",dimensions:"1024x768",typesize:"(JPG, 104K)"}]}
				var walDiv = _this.contentBlocks[idx].getElementsByTagName("div")[0];
				for(var w = 0; w < items[idx].length; w++)
				{
					walDiv.appendChild(makeElement("div", {cn:"downloadItem"}));
					walDiv.childNodes[w].appendChild(makeElement("div", {cn:"thumbNail"}));
					walDiv.childNodes[w].childNodes[0].appendChild(makeElement("img", {src:items[idx][w].thumb}));
					walDiv.childNodes[w].appendChild(makeElement("div", {cn:"blackTitle"}, null, null, items[idx][w].title));
					for(var l = 0; l < items[idx][w].links.length; l++)
					{
						walDiv.childNodes[w].appendChild(makeElement("div", {cn:"linkLine"}));
						walDiv.childNodes[w].childNodes[l+2].appendChild(makeElement("div", {cn:"link"}));
						walDiv.childNodes[w].childNodes[l+2].childNodes[0].appendChild(makeElement("a", {href:items[idx][w].links[l].url,target:"_blank"}, items[idx][w].links[l].dimensions));
						walDiv.childNodes[w].childNodes[l+2].appendChild(makeElement("div", {cn:"linkInfo"}, items[idx][w].links[l].typesize));
					}
				}
			}
			
			_this.contentBlocks[idx].appendChild(makeElement("div", {cn:"clr"}, null, "clr"));
		}
		
		_this.swapImage(document.getElementById("lnkBrochureTab"), 0, 1);
		_this.setTab(document.getElementById("lnkBrochureTab"), 0);
	};
	
	
	this.swapImage = function(lnk, from, to)
	{
		if(lnk.className != "selected")
		{
			var imgs = lnk.getElementsByTagName("img");
			imgs[from].className = "hidden";
			imgs[to].className = "";
		}
	};
	this.ringtonesSelected = false;
	this.setSecondary = function(name)
	{
	
		// Currently only functional for downloads
		var divs = _this.contentBlocks[2].getElementsByTagName("div");
		var dlDivs = new Array();
		for(var d = 0; d < divs.length; d++)
			if(divs[d].parentNode == _this.contentBlocks[2])
				dlDivs[dlDivs.length] = divs[d];	
				
		dlDivs[0].className = (name == "wallpaper") ? "downloadContent" : "hidden";
		dlDivs[1].className = (name == "ringtones") ? "downloadContent" : "hidden";
		_this.ringtonesSelected = (name == "ringtones");
		
		_this.contentBlocks[2].style.left = "0px";
		_this.contentBlocks[2].style.width = (!_this.ringtonesSelected) ? (_this.tabContentItems[2].length * 175) + "px" : "640px";
		_this.contentBlocks[2].parentNode.style.marginLeft = (!_this.ringtonesSelected) ? "85px" : "28px";
		_this.contentBlocks[2].parentNode.parentNode.style.height = (!_this.ringtonesSelected) ? "227px" : "525px";
		_this.contentBlocks[2].parentNode.style.height = (!_this.ringtonesSelected) ? "227px" : "525px";
		_this.contentBlocks[2].parentNode.style.width = (!_this.ringtonesSelected) ? "525px" : "640px";
		
		_this.toggleScrollButtons();
	};
	this.setSecondaryNav = function(idx)
	{
		if(_this.secondaryNav == null)
		{
			_this.secondaryNav = document.getElementById("secondaryNav");
			var divs = _this.secondaryNav.getElementsByTagName("div");
			
			for(var d = 0; d < divs.length; d++)
				if(divs[d].parentNode == _this.secondaryNav)
					_this.secondaryNavItems[_this.secondaryNavItems.length] = divs[d];			
			
			// Recommendations
			_this.secondaryNavItems[1].appendChild(makeElement("img",{src:'/StaticFiles/internationalTrucks/Site Assets/Products/tab_you_might_be_bar.jpg'})); 

			// Downloads
			_this.secondaryNavItems[2].appendChild(makeElement("div", {cn:"menu"}));
			if(_this.tabContentItems[2].length > 0) // Wallpapers exist
			{
				_this.secondaryNavItems[2].childNodes[0].appendChild(makeElement("a", {href:"javascript:DetailPage.setSecondary('wallpaper')",cn:"on"}, "For Your Computer"));
				_this.secondaryNavItems[2].childNodes[0].appendChild(makeElement("span", null, "|"));
				_this.secondaryNavItems[2].childNodes[0].appendChild(makeElement("a", {href:"javascript:DetailPage.setSecondary('ringtones')"}, "For Your Phone"));
				$("#secondaryNav .menu a").click(function()
				{
					$(this).siblings("a").removeClass('on');
					$(this).removeClass('on');
					$(this).addClass('on');				
				});
			}
			else
			{
				_this.secondaryNavItems[2].childNodes[0].appendChild(makeElement("a", {href:"javascript:DetailPage.setSecondary('ringtones')",cn:"on"}, "For Your Phone"));
				_this.setSecondary("ringtones");
			}
			
		}
		
		for(var s = 0; s < _this.secondaryNavItems.length; s++)
			_this.secondaryNavItems[s].className = (s == idx) ? "" : "hidden";
		
		_this.contentBlocks[2].parentNode.parentNode.style.height = (idx != 2 || (idx == 2 && !_this.ringtonesSelected)) ? "227px" : "525px";
		_this.contentBlocks[2].parentNode.style.height = (idx != 2 || (idx == 2 && !_this.ringtonesSelected)) ? "227px" : "525px";
		_this.contentBlocks[2].parentNode.style.width = (idx == 1) ? "685px" : (idx == 2 && !_this.ringtonesSelected) ? "525px" : "640px";
		_this.contentBlocks[2].parentNode.style.marginLeft = (idx == 1) ? "0" : (idx == 2 && !_this.ringtonesSelected) ? "85px" : "28px";
		_this.contentBlocks[2].parentNode.style.backgroundImage = (idx == 1) ? "url('/StaticFiles/internationalTrucks/Site Assets/Products/search_bkg.jpg')" : "none";
		
	};
	
	this.currentContent = 0;
	
	this.setTab = function(tab, to)
	{
		if(tab.className != "selected")
		{
			if(_this.tabs == null)
				_this.tabs = tab.parentNode.getElementsByTagName("a");
			
			for(var t = 0; t < _this.tabs.length; t++)
			{
				if(_this.tabs[t] != tab)
				{
					_this.tabs[t].className = "";
					_this.swapImage(_this.tabs[t], 2, 0);
				}
			}
			_this.swapImage(tab, 1, 2);
			tab.className = "selected";
			_this.setSecondaryNav(to);			

			
			_this.scrollOffset = (to == 0) ? 640 : (to == 1) ? 675 : 525;

			for(var c = 0; c < _this.contentBlocks.length; c++){
				_this.contentBlocks[c].className = (c == to) ? "content" : "hidden";
			}

			_this.contentBlocks[to].style.left = "0px";
			_this.currentContent = to;

			
			_this.contentBlocks[to].parentNode.style.width = (to == 1) ? "685px" : (to == 2 && !_this.ringtonesSelected) ? "525px" : "640px";
			_this.contentBlocks[to].parentNode.style.marginLeft = (to == 1) ? "0" : (to == 2 && !_this.ringtonesSelected) ? "85px" : "28px";
			_this.contentBlocks[to].parentNode.style.backgroundImage = (to == 1) ? "url('/StaticFiles/internationalTrucks/Site Assets/Products/search_bkg.jpg')" : "none";
			_this.toggleScrollButtons();
			
		}
	};

	// Scroll management
    this.scrollTimeout = null;
    this.scrollOffset = 35;
    this.scrollDirection = null;
	
    this.isFurthestLeft = function() { return !(_this.contentBlocks[_this.currentContent].offsetLeft < 0); };
    this.isFurthestRight = function() { return !(_this.contentBlocks[_this.currentContent].offsetLeft > (-(_this.contentBlocks[_this.currentContent].offsetWidth) + _this.contentBlocks[_this.currentContent].parentNode.offsetWidth)); };
    
    
    this.toggleScrollButtons = function()
    {
        //if(_this.isFurthestRight())
        //    _this.contentBlocks[_this.currentContent].style.left = (-(_this.contentBlocks[_this.currentContent].offsetWidth) + _this.contentBlocks[_this.currentContent].parentNode.offsetWidth) + "px";        
        
        if(_this.isFurthestLeft())
            _this.contentBlocks[_this.currentContent].style.left = "0px";

        document.getElementById("moveLeft").className = _this.isFurthestLeft() ? "hidden" : "scrollLeft";
        document.getElementById("moveRight").className = _this.isFurthestRight() ? "hidden" : "scrollRight";
        // ie7 button fix
        if(brochureFirstLoad && brochureLengthNumberNew > 4){
	        document.getElementById("moveRight").className = "scrollRight";
        }
        brochureFirstLoad = false;
        
		zIndexMgr.setzIndexOf(document.getElementById("moveLeft"));
		zIndexMgr.setzIndexOf(document.getElementById("moveRight"));
    };
    
    this.startScrolling = function(el)
    {
        if(!el.className.match("hidden"))
        {
            _this.scrollDirection = el.className.match("scrollLeft") ? "l" : "r";
            
            if(_this.scrollDirection == "l" && !_this.isFurthestLeft()){
                _this.scrollOffset = Math.abs(_this.scrollOffset);
            }
            else if(_this.scrollDirection == "r" && !_this.isFurthestRight()){
                _this.scrollOffset = -(Math.abs(_this.scrollOffset));
            }

			if((_this.scrollDirection == "l" && !_this.isFurthestLeft()) || (_this.scrollDirection == "r" && !_this.isFurthestRight())){
				_this.contentBlocks[_this.currentContent].style.left = _this.contentBlocks[_this.currentContent].offsetLeft + _this.scrollOffset + "px";
			}
				
			_this.toggleScrollButtons();
		}
    
    };
}    

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName]
	}
	else {
		return document[movieName]
	}
}


/*** ENewsletter Begin ***/
function enewsCheckItem(item, msg, regex) {
		var value = "";
		var itype = "r";
		
		if(typeof item.type != "undefined")
			itype = item.type.toLowerCase().substr(0,1);
		
		switch (itype)
		{
			case "r": // Radio Button
				for(var r = 0; r < item.length; r++)
				{
					if(item[r].checked)
					{
						value = item[r].value;
						break;
					}
				}
				break;
			case "c":
				value = item.checked ? "true" : "";
				break;
			case "s": // Select Box
				value = item.options[item.selectedIndex].value;
				break;
			case "t": // Textbox or Textarea
				value = item.value;
				break;
		}
		
		var fail = (value.length == 0 || ((typeof regex != "undefined") && !regex.test(value)));
		return (fail) ? "\n-Must specifiy " + msg : "";
    }	

$('form#frmEmailSignup input#btnSignup').click(function(){
	validateENewsletter();
});

	function validateENewsletter()
	{
		var form = document.frmEmailSignup;
		
		// Do some validation
		var errors = "";

		errors += enewsCheckItem(form.txtFirstName, "First Name");
		errors += enewsCheckItem(form.txtLastName, "Last Name");
		errors += enewsCheckItem(form.txtEmail, "a valid Email", /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/);
		//errors += enewsCheckItem(form.chkConfirm, "that you agree with the terms and conditions");
		
		if(errors.length != 0)
		{
			alert("You may not register until the following issues have been resolved:\n" + errors);
		}
		else
		{
			function sideBarAjaxCallback(msg){
				if(msg){
					var goodTimes = '<p>Thank you for your submission!</p>';
					$('#frmEmailSignup').replaceWith(goodTimes);
				}
			}
			var sideBarAjax = {
					go: function(type, url, data, returnData, callback) {
						$.ajax({
							type: type,
							url: url,
							data: data,
							success: function(msg){
							if(returnData)
								callback(msg);
							else
								callback();
							},
						error: function(XMLHttpRequest, textStatus, errorThrown){
							alert('There has been an error with your request, please try again.');
						}
					});
				}
			};
			var query = 'email='+$("input#txtEmail").val()+'&first='+$("input#txtFirstName").val()+'&last='+$("input#txtLastName").val();
			//emailSubmitBox.open(query);
			sideBarAjax.go('GET', '/itrucks/eNewsletterProvider', query, false, sideBarAjaxCallback);
			sideBarAjax.go('GET', '/itrucks/ENewsletterListTrak', query + '&fromWhere=itDotComHeader', false, sideBarAjaxCallback);
			/*
			enewsletterSubmitted = true;
			
			var url = "/itrucks/eNewsletterProvider";
			
			//url = "success.txt";
			
			
			var query = "?email=" + $("#txtEmail").val() + "&first=" + $("#txtFirstName").val() + "&last=" + $("#txtLastName").val() + "&additional=" + $("#chkConfirm").attr("checked");
			$.get(url, {email: $("#txtEmail").val(), first: $("#txtFirstName").val(), last: $("#txtLastName").val(), source: "RightRail", additional: $("#chkConfirm").attr("checked")}, function(data){
					if(data.indexOf("success") >= 0)
					{						
						emailSubmitBox.open(query);
					}
					else
					{
						//let them know it didn't work
						alert('There was an error when making your request.  Please wait a few moments and try again.');
					}
				});


				// Do your ajax magic here
				*/
		}
		$("#txtEmail").val("");
		$("#txtFirstName").val("");
		$("#txtLastName").val("");
		return false;
	}
	
function SignupForENewsLetter(emailAddress)
{
	$(".enewsEmailSubmitBox").height("242px");
	emailSubmitBox.open("?email=" + emailAddress + "&origin=flash");
}

function growSubmitBox()
{
	$(".enewsEmailSubmitBox").animate({height: "763px"}, 1500);
}

function showThankyou()
{
	$(".enewsEmailSubmitBox").height("120px");
	$('html,body').animate({scrollTop: $(".enewsEmailSubmitBox").offset().top}, 1000);
}
	
var emailSubmitBox = new function emailSubmitBoxClass()
{
	var _this = this;
	this.box = null;
	this.washout = null;
	this.open = function(query)
	{
		var url = "/itrucks/webservices/enewsletter.jsp" + query;
		if(_this.box != null)
		{
			_this.box = null;
		}
		
		var bodyHeight = $('body').height();
		_this.washout = makeElement( "div", { cn:"washout", style: { height:bodyHeight + 'px' } } );
		if(query.indexOf("origin=flash") >= 0)
			_this.box = makeElement("div", {cn:"enewsEmailSubmitBox enewsShortStack"});			
		else
			_this.box = makeElement("div", {cn:"enewsEmailSubmitBox"});
		

		_this.box.appendChild(makeElement("iframe", {src:url,frameborder:0,name:"specFrame",id:"specFrame",scrolling: "no",allowtransparency: "true"}));
		document.body.appendChild(_this.washout);			
		document.body.appendChild(_this.box);			
		
		
		zIndexMgr.setzIndexOf(_this.washout);
		zIndexMgr.setzIndexOf(_this.box);
		var offset = 40;
		if(getScrollTop() < 60)
			offset = 110 - getScrollTop();
		
		_this.box.style.top = (getScrollTop() + offset) + "px";
		
		var a = $(window).width();
		var b = $('div.enewsEmailSubmitBox').width();
		var c = parseFloat($(window).width(), 10) - parseFloat($('div.enewsEmailSubmitBox').width(), 10);
		var d = c/2;
		
		_this.resize();
		//_this.box.style.left = ( $(window).width() - $('div.enewsEmailSubmitBox').width() ) / 2 ;
		
		$(window).bind('resize', function(){
			_this.resize();
		});
		
	};
	this.resize = function(){
		var a = $(window).width();
		var b = $('div.enewsEmailSubmitBox').width();
		var c = parseFloat($(window).width(), 10) - parseFloat($('div.enewsEmailSubmitBox').width(), 10);
		var d = c/2;
		
		_this.box.style.left = '0';
		_this.box.style.marginLeft = d+'px';
		
	};
	this.close = function()
	{
		_this.box.className = "hidden";
		_this.washout.className = "hidden";
		window.frames["specFrame"].location.href = "about:blank";
		$("#txtEmail").val("");
		$("#txtFirstName").val("");
		$("#txtLastName").val("");
		//window.location.reload();
	};
}

/*** ENewsletter End ***/

/*** Sweepstakes Start ***/
function SignupForSweepstakes()
{
	sweepstakesSubmitBox.open("?origin=flash");
}

function showSweepstakesThankyou()
{
	$(".sweepstakesSubmitBox").height("400px");
	$(".sweepstakesSubmitBox").width("770px");
	$('html,body').animate({scrollTop: $(".sweepstakesSubmitBox").offset().top}, 1000);
}
	
var sweepstakesSubmitBox = new function sweepstakesSubmitBoxClass()
{
	var _this = this;
	this.box = null;
	this.washout = null;
	this.open = function(query)
	{
		var url = "/itrucks/webservices/sweepstakes.jsp" + query;
		if(_this.box != null)
		{
			_this.box = null;
		}
			
		_this.washout = makeElement("div", {cn:"washout", style:{height:document.getElementById("all").offsetHeight + "px"}});
		_this.box = makeElement("div", {cn:"sweepstakesSubmitBox"});
		

		_this.box.appendChild(makeElement("iframe", {src:url,frameborder:0,name:"specFrameSweepstakes",id:"specFrameSweepstakes",scrolling: "no"}));
		document.body.appendChild(_this.washout);			
		document.body.appendChild(_this.box);			
		
		
		zIndexMgr.setzIndexOf(_this.washout);
		zIndexMgr.setzIndexOf(_this.box);
		var offset = 40;
		if(getScrollTop() < 60)
			offset = 110 - getScrollTop();
		
		_this.box.style.top = (getScrollTop() + offset) + "px";
	};
	this.close = function()
	{
		_this.box.className = "hidden";
		_this.washout.className = "hidden";
		window.frames["specFrameSweepstakes"].location.href = "about:blank";
		$("#txtEmailSweepstakes").val("");
		$("#txtFirstNameSweepstakes").val("");
		$("#txtLastNameSweepstakes").val("");
		//window.location.reload();
	};
}

/*** Sweepstakes End ***/


/*** Configurator Begin ***/
var configuratorPopup = new function configuratorPopupObj()
{
	var _this = this;
	this.closed = true;
	this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
 	this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
	this.getT = function() { return (((_this.getH() - 520) / 2) + $("body").scrollTop()) > 110 ? ((_this.getH() - 520) / 2) + $("body").scrollTop() : 110; };
	this.getL = function() { return ((_this.getW() - 780) / 2); };
	this.adjust = function()
	{
		if(!$.support.cssFloat)
			$("#configuratorPopOut").css({top:_this.getT(),left:_this.getL()});
		else
			$("#configuratorPopOut").animate({top:_this.getT(),left:_this.getL()}, 100);
	};
	this.hasLoaded = false;
	this.loaded = function()
	{
		_this.hasLoaded = true;
		$('#configLoading').fadeTo(500, 0, function() { $("#configLoading").remove()});
	};
	this.animTimeout = null;
	this.animLoading = function()
	{		
		clearTimeout(_this.animTimeout);
		if(!_this.hasLoaded)
		{	
			var txt = $('#configLoading').html();

			if(txt.length  < 15)
				txt += ".";
			else
				txt = "Loading";
			
			$('#configLoading').html(txt);
			
			_this.animTimeout = setTimeout(_this.animLoading, 200);
		}
	};	
	this.open = function(campaign)
	{
		//directs to new configurator//
	window.location.href = "/Trucks/Trucks/Series/DuraStar/BuildYourOwn/";
	/*
		if(_this.closed)
		{
			_this.closed = false;
			
			var cmpid = (typeof campaign != "undefined") ? "?cmpid=" + campaign : "";
			
			$(window).bind("resize", configuratorPopup.adjust);
			$("body").append('<div id="configWashout">&nbsp;</div>');
			$("body").append('<div id="configuratorPopOut">'
						+ '<div style="text-align:right;padding:3px;"><a href="javascript:configuratorPopup.close()">Close</a></div>'
						+ '<iframe src="/durastarconfigurator/' + cmpid + '" width="780" height="500" frameborder="0" scrolling="no" onload="configuratorPopup.loaded()"></iframe>'
						+ '</div>');
			$("body").append('<div id="configLoading">Loading</div>');
			$("#configWashout, #configuratorPopOut, #configLoading").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
			$("#configWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
			$("#configuratorPopOut, #configLoading").css({border:"2px solid #ffffff",top:_this.getT()+"px",left:_this.getL()+"px",width:"780px",height:"520px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});		
			$('#configLoading').css({zIndex:"500",textAlign:"left",fontWeight:"bold"});
			$("#configWashout").fadeTo(500, .6, function() {
				$("#configLoading, #configuratorPopOut").fadeTo(500, 1);
				_this.hasLoaded = false;
				_this.animLoading();
			});	
		}
		*/
	};
	this.close = function()
	{
		$("#configuratorPopOut").fadeTo(500, 0, function() {
			$("#configWashout").fadeTo(500, 0, function() { _this.closed = true; $("#configWashout").remove(); $("#configuratorPopOut").remove(); $(window).unbind("resize", configuratorPopup.adjust); });
		});	
	};
}

window.onload = function() { if(getQueryVariable("configurator") != null) { configuratorPopup.open("168"); } };

/*** Configurator End ***/


/*** Reskin Homepage Drop Up Menu ***/
/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
 
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();


var dropUpMenu = new function dropUpMenuObj()
{
	var _this = this;
	this.data = new Array();
	this.data["divisions"] = {name:"divisions",elem:null,inited:false,items:new Array()};
	this.data["trucks"] = {name:"trucks",elem:null,inited:false,items:new Array()};
	this.data["usages"] = {name:"usages",elem:null,inited:false,items:new Array()};
	this.sort = false;
	this.curMenu = null;
	this.dontCloseMeBro = false;
	this.dataLoaded = new Array(false, false);
	this.isIE6 = function() { return !$.support.cssFloat && typeof document.body.style.maxHeight == "undefined"; };	
	this.init = function()
	{
		if(!_this.curMenu.inited)
		{	
			$("body").append('<div id="lowMenus" style="position:absolute;left:0;top:' + $(_this.curMenu.elem).offset().top + 'px"></div>');
			$("#lowMenus").append('<div id="' + _this.curMenu.name + 'Menu" class="dropUpMenu"><ul></ul></div>');
			$("#" + _this.curMenu.name + "Menu").css({bottom:0,left:$(_this.curMenu.elem).offset().left + "px"});
			
			$(_this.curMenu.items).each(function() {
				$("#" + _this.curMenu.name + "Menu>ul").append('<li><a href="' + this.link + '" target="' + this.target + '">' + this.title + '</a></li>');
				if(this.subItems != null)
				{
					$("#" + _this.curMenu.name + "Menu>ul>li:last>a").bind("click", _this.showSubItems);
					$("#" + _this.curMenu.name + "Menu>ul>li:last>a").data("itemCount", this.subItems.length);
					$("#" + _this.curMenu.name + "Menu>ul>li:last").append('<ul class="subItems"></ul>');
					$(this.subItems).each(function() {
						$("#" + _this.curMenu.name + "Menu>ul>li:last>ul").append('<li><a href="' + this.link + '" target="' + this.target + '">' + this.title.replace(/i$/,"<i>i</i>").replace(/ix$/,"<i>ix</i>") + '</a></li>');
					});
				}
			});
			
			if (this.sort) {
				$("#" + _this.curMenu.name + "Menu>ul>li").sortElements(function(a, b){
					return $(a).text() > $(b).text() ? 1 : -1;
				});
			}
			
			$("#" + _this.curMenu.name + "Menu>ul>li:last").attr("class", "lst");
			
			
			
			if(!_this.isIE6())
			{
				$("#" + _this.curMenu.name + "Menu").css({backgroundColor:"transparent",backgroundImage:"url('/images/lowMenuBg.png')",backgroundPosition:"bottom right",backgroundRepeat:"no-repeat",width:"190px"});
				$("#" + _this.curMenu.name + "Menu>ul").css("padding","3px 10px 6px 5px");
			}
			
			
			_this.curMenu.inited = true;
			$("#" + _this.curMenu.name + "Menu").hover(function() {dropUpMenu.dontCloseMeBro = false;}, dropUpMenu.close);
		}
		
		return true;		
	};
	this.close = function()
	{
		if(!_this.dontCloseMeBro && _this.curMenu != null)
		{
			var name = _this.curMenu.name;
			_this.curMenu = null;
			$("#" + name + "Menu").customFadeOut(250);			
		}
	};

	this.open = function(elem,menu,sort)	
	{
		
		if(_this.curMenu != null)
			_this.close();

		_this.curMenu = _this.data[menu];
		_this.curMenu.elem = elem;
		
		if (typeof(sort) != 'undefined') {
			_this.sort = sort;
		}

		if(_this.init())
		{
			$("#" + _this.curMenu.name + "Menu").customFadeIn(250);
		}
			
		return false;
	};
	this.showSubItems = function()
	{
		_this.dontCloseMeBro = true;
		var alreadyOpen = $(this).parent().hasClass("open");
		var offset = (!$.support.cssFloat) ? 20 : 16;
		
		$(this).parent().siblings().andSelf().removeClass("open");
		$(this).parent().siblings().andSelf().css("height", offset + "px");
		$(this).parent().parent().find(".subItems").css("display", "none");
		
		if(!alreadyOpen)
		{
			$(this).parent().addClass("open");
			
			
			var h = ($(this).data("itemCount") * 16);
			
			$(this).parent().animate({height: (h + offset) + "px"}, h * 6, function()
			{	
				$(this).children("ul").customFadeIn(250);
				_this.dontCloseMeBro = false;
			});
		}
		else
		{
			$(this).blur();
		}
		
	};
	this.loadData = function()
	{
		//$.ajax({ url: "productsapps.xml", dataType: "xml", success: function(data, status) {
		var trucksAjax = $.ajax({ url: "/itrucks/trucksXMLProvider", dataType: "xml", success: function(data, status) {
			$(data).find("application").each(function() {
				//_this.data["usages"].items[_this.data["usages"].items.length] = {title:$(this).children("name").text(),link:"/portal/site/ITrucks/menuitem.688e730e2485ac884b8e89106e9c8a0c/?vgnextoid=8e793d9e417dd010VgnVCM1000002101010aRCRD&applicationID=" + $(this).attr("id"),target:"_self"};
				
				_this.data["usages"].items[_this.data["usages"].items.length] = {title:$(this).children("name").text(),link:"/Trucks/Trucks/#refresh=true&u=" + $(this).attr("id").toLowerCase(),target:"_self"};
			});
			$(data).find("class_series>series").each(function() {
				var idx = _this.data["trucks"].items.length;
				_this.data["trucks"].items[idx] = {title:$(this).children("name").text(),subItems:new Array(),link:"javascript:void(0)",target:"_self"};
				$(data).find("truck").each(function()
				{
					if($(this).children("series").text() == _this.data["trucks"].items[idx].title)
					{
						_this.data["trucks"].items[idx].subItems[_this.data["trucks"].items[idx].subItems.length] = {title:$(this).children("name").text(),link:$(this).children("product_link").text(),target:"_self"};
					}
				});				
			});
			_this.dataLoaded[0] = true;
		}});
		
		var navistarAjax = $.ajax({ url: "/itrucks/headerXMLProvider?navistar", dataType: "xml", success: function(data, status) {
			$(data).find("item").each(function() {
				_this.data["divisions"].items[_this.data["divisions"].items.length] = {title:$(this).children("label").text(),link:$(this).children("url").text(),target:"_blank"};
			});
			_this.dataLoaded[1] = true;
		}});
	};
}

//preloads xml for horizontal dropup navigation
//window.onload = this.loadData;
//window.onload=function() {this.loadData();}

function trackHomePromo(url, p, target)
{
	var pos = new Array();
	// Campaing Code Associations for International Trucks
	pos["p1m"] = "170"; // Home Promotion Position 1 Main Link 
	pos["p2m"] = "171"; // Home Promotion Position 2 Main Link 
	pos["p3m"] = "172"; // Home Promotion Position 3 Main Link 
	pos["p4m"] = "173"; // Home Promotion Position 4 Main Link 
	pos["p1t"] = "174"; // Home Promotion Position 1 Thumb Link
	pos["p2t"] = "175"; // Home Promotion Position 2 Thumb Link
	pos["p3t"] = "176"; // Home Promotion Position 3 Thumb Link
	pos["p4t"] = "177"; // Home Promotion Position 4 Thumb Link
	
	if(url == "javascript:iframeVideoPopIn.open('/InternationalTrucks/PageContent/PowerofONE/', 600, 245);"){
		iframeVideoPopIn.open('/InternationalTrucks/PageContent/PowerofONE/', 600, 245);
	}else if(url == "gighome" || url == "gigterrastarhome" || url == "gigterrastarmodel" || url == "gigdurastarhome" || url == "gigdurastarmodel"){
		javascript:vgPopup.open('zimmer','/itrucks/templates/getingear/getingear.jsp?gigid='+url, true);
	
	}else if(url == 'viewMatsVideo.open()'){
		viewMatsVideo.open();
	}else{
		url = (url.indexOf("?") != -1) ? url + "&cmpid=" + pos[p] : url + "?cmpid=" + pos[p];
	
		if(target == "_blank"){
			window.open(url);
		}else{
			document.location.href = url;
		}
	}
	
	return false;
}

var microPollUpdateTimer = null;
function updateMicroPollButton(pollID)
{
	if($("#mp_submit_button_div_" + pollID).length > 0)
	{
		clearTimeout(microPollUpdateTimer);
		var tds = $("#mp_submit_button_div_" + pollID + " td");
		$(tds[0]).children("img")[0].src = "/images/small_blue_left.gif";
		$(tds[1]).css("backgroundImage", "url(/images/small_blue_body.gif)");
		$(tds[2]).children("img")[0].src = "/images/small_blue_right.gif";	
	}
	else
	{
		microPollUpdateTimer = setTimeout(function(){ updateMicroPollButton(pollID); }, 250);
	}
}

if(typeof $ != "undefined")
{
	$.fn.customFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
				if(jQuery.browser.msie)
						$(this).get(0).style.removeAttribute('filter');
				if(callback != undefined)
						callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
				if(jQuery.browser.msie)
						$(this).get(0).style.removeAttribute('filter');
				if(callback != undefined)
						callback();
		});
	};
}

/*********************************************************************
*iframe popup window
**********************************************************************/
var iframePopup = new function iframePopupObj()
	{
		var _this = this;
		this.closed = true;
		this.maxWidth = null;
		this.maxHeight = null;
		this.curHeight = null;
		this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
		this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
		this.getT = function() { return (((_this.getH() - _this.curHeight) / 2) + $("body").scrollTop()) > 110 ? ((_this.getH() - _this.curHeight) / 2) + $("body").scrollTop() : 110; };
		this.getL = function() { return ((_this.getW() - _this.maxWidth) / 2); };
		this.adjust = function()
		{
			var h = _this.curHeight;
			_this.curHeight = ($(window).height() - 140) < _this.maxHeight ? $(window).height() - 140 : _this.maxHeight;
			
			var change = {top:_this.getT(),left:_this.getL()};
			
			
			if(h != _this.curHeight)
				change.height = _this.curHeight;
		
			if(!$.support.cssFloat)
				$("#iframePopup").css(change);
			else
				$("#iframePopup").animate(change, 100);
				
			if(change.height != null)
				$("#iframePopup>iframe").animate({height:_this.curHeight - 20}, 100);
				
		};
		this.open = function(url, maxHeight, maxWidth)
		{
			if(_this.closed)
			{
				_this.closed = false;
				_this.maxHeight = maxHeight;
				_this.maxWidth = (typeof maxWidth != "undefined") ? maxWidth : 850;
				
				
				_this.curHeight = ($(window).height() - 140) < _this.maxHeight ? $(window).height() - 140 : _this.maxHeight;
				
				$(window).bind("resize", iframePopup.adjust);
				$("body").append('<div id="iframeWashout">&nbsp;</div>');
				$("body").append('<div id="iframePopup">'
							+ '<div style="text-align:right;padding:3px;"><a href="javascript:iframePopup.close()">Close</a></div>'
							+ '<iframe src="' + url + '" width="' + _this.maxWidth + '" frameborder="0" scrolling="auto"></iframe>'
							+ '</div>');
				$("#iframeWashout, #iframePopup").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
				$("#iframeWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
				$("#iframePopup").css({border:"2px solid #ffffff",top:_this.getT()+"px",left:_this.getL()+"px",width:_this.maxWidth + "px",height:_this.curHeight + "px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});
				$("#iframePopup>iframe").css("height", _this.curHeight - 20);
				$("#iframeWashout").fadeTo(500, .6, function() {
					$("#iframePopup").fadeTo(500, 1);
				});	
			}
		};
		this.close = function()
		{
			$("#iframePopup").fadeTo(500, 0, function() {
				$("#iframeWashout").fadeTo(500, 0, function() { _this.closed = true; $("#iframeWashout").remove(); $("#iframePopup").remove(); $(window).unbind("resize", iframePopup.adjust); });
			});	
		};
	}

/*********************************************************************
*image popup window
**********************************************************************/
var imagePopup = new function imagePopupObj()
	{
		var _this = this;
		this.closed = true;
		this.maxWidth = null;
		this.maxHeight = null;
		this.curHeight = null;
		this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
		this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
		this.getT = function() { return (((_this.getH() - _this.curHeight) / 2) + $("body").scrollTop()) > 110 ? ((_this.getH() - _this.curHeight) / 2) + $("body").scrollTop() : 110; };
		this.getL = function() { return ((_this.getW() - _this.maxWidth) / 2); };
		this.adjust = function()
		{
			var h = _this.curHeight;
			_this.curHeight = ($(window).height() - 140) < _this.maxHeight ? $(window).height() - 140 : _this.maxHeight;
			
			var change = {top:_this.getT(),left:_this.getL()};
			
			
			if(h != _this.curHeight)
				change.height = _this.curHeight;
		
			if(!$.support.cssFloat)
				$("#imagePopup").css(change);
			else
				$("#imagePopup").animate(change, 100);
				
			if(change.height != null)
				$("#imagePopup>img").animate({height:_this.curHeight - 20}, 100);
				
		};
		this.open = function(url, maxHeight, maxWidth)
		{
			if(_this.closed)
			{
				_this.closed = false;
				_this.maxHeight = maxHeight;
				_this.maxWidth = (typeof maxWidth != "undefined") ? maxWidth : 500;
				
				
				_this.curHeight = ($(window).height() - 140) < _this.maxHeight ? $(window).height() - 140 : _this.maxHeight;
				
				$(window).bind("resize", imagePopup.adjust);
				$("body").append('<div id="imageWashout">&nbsp;</div>');
				$("body").append('<div id="imagePopup">'
							+ '<div style="text-align:right;padding:3px;"><a href="javascript:imagePopup.close()">Close</a></div>'
							+ '<img src="' + url + '" width="' + _this.maxWidth + '" frameborder="0" ></img>'
							+ '</div>');
				$("#imageWashout, #imagePopup").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
				$("#imageWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
				$("#imagePopup").css({border:"2px solid #ffffff",top:_this.getT()+"px",left:_this.getL()+"px",width:_this.maxWidth + "px",height:_this.curHeight + "px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});
				$("#imagePopup>img").css("height", _this.curHeight - 20);
				$("#imageWashout").fadeTo(500, .6, function() {
					$("#imagePopup").fadeTo(500, 1);
				});	
			}
		};
		this.close = function()
		{
			$("#imagePopup").fadeTo(500, 0, function() {
				$("#imageWashout").fadeTo(500, 0, function() { _this.closed = true; $("#imageWashout").remove(); $("#imagePopup").remove(); $(window).unbind("resize", imagePopup.adjust); });
			});	
		};
	}

/*********************************************************************
*iframe video pop in
**********************************************************************/
function terraStarWalkAround(){
	var leftHolder = $('table#all');
	var leftMargin = 494;
	var params = {
		'top':'250px',
		'leftHolder':leftHolder,
		'leftMargin':leftMargin
	};
	vgPopup.open("terraStarWalkAround","/InternationalTrucks/PageContent/TerraStarWalkAroundVideo/",false,true,params);
}
function workstarCNG(){
	var leftHolder = $('table#all');
	var leftMargin = 42;
	var params = {
		'top':'770px',
		'leftHolder':leftHolder,
		'leftMargin':leftMargin
	};
	vgPopup.open("workstarCNG","/InternationalTrucks/PageContent/WorkStarCNG/",false,true,params);
}
function iframeVideoPopInObj()
{
	var _this = this;
	this.closed = true;
	this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
 	this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
	this.getT = function() { return ((_this.getH() - 526) / 2) + $("body").scrollTop(); };
	this.getL = function() { return ((_this.getW() - 740) / 2); };
	this.adjust = function()
	{
		if(!$.support.cssFloat)
			$("#iframeVideoPopInBox").css({top:_this.getT(),left:_this.getL()});
		else
			$("#iframeVideoPopInBox").animate({top:_this.getT(),left:_this.getL()}, 100);
	};	
	this.open = function(url, vidWidth, vidHeight, campaign)
	{
		if(_this.closed)
		{
			_this.closed = false;
			
			var cmpid = (typeof campaign != "undefined") ? "?cmpid=" + campaign : "";
			
			$(window).bind("resize", iframeVideoPopIn.adjust);
			$("body").append('<div id="iframeVideoWashout">&nbsp;</div>');
			$("body").append('<div id="iframeVideoPopInBox">'
						+ '<div style="text-align:right;padding:3px;"><a style="color:#FC6E2A;" href="javascript:iframeVideoPopIn.close()">Close</a></div>'
						+ '<iframe src="' + url + cmpid + '" width="' + (vidWidth + 20) + '" height="' + (vidHeight + 20) + '" frameborder="0" scrolling="no"></iframe>'
						+ '</div>');
			$("#iframeVideoWashout, #iframeVideoPopInBox").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
			$("#iframeVideoWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
			$("#iframeVideoPopInBox").css({border:"2px solid #ffffff",top:_this.getT()+"px",left:_this.getL()+"px",width:(vidWidth + 20) + "px",height: (vidHeight + 40) + "px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});		
			$("#iframeVideoWashout").fadeTo(500, .6, function() {
				$("#iframeVideoPopInBox").fadeTo(500, 1);
			});	
		}
	};
	this.close = function()
	{
		$("#iframeVideoPopInBox").fadeTo(500, 0, function() {
			$("#iframeVideoWashout").fadeTo(500, 0, function() { _this.closed = true; $("#iframeVideoWashout").remove(); $("#iframeVideoPopInBox").remove(); $(window).unbind("resize", iframeVideoPopIn.adjust); });
		});	
	};
}
var iframeVideoPopIn = new iframeVideoPopInObj();

//Added for emergency for terrastar
function seeTheDifferencePopInObj()
{
	var _this = this;
	this.closed = true;
	this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
 	this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
	this.getT = function() { return ((_this.getH() - 526) / 2) + $("body").scrollTop(); };
	this.getL = function() { return ((_this.getW() - 740) / 2); };
	this.adjust = function()
	{
		if(!$.support.cssFloat)
			$("#seeTheDifferencePopIn").css({top:_this.getT(),left:_this.getL()});
		else
			$("#seeTheDifferencePopIn").animate({top:_this.getT(),left:_this.getL()}, 100);
	};	
	this.open = function(campaign)
	{
		if(_this.closed)
		{
			_this.closed = false;
			
			var cmpid = (typeof campaign != "undefined") ? "?cmpid=" + campaign : "";
			
			$(window).bind("resize", seeTheDifferencePopIn.adjust);
			$("body").append('<div id="seeTheDifferenceWashout">&nbsp;</div>');
			$("body").append('<div id="seeTheDifferencePopIn">'
						+ '<div style="text-align:right;padding:3px;"><a style="color:#FC6E2A;" href="javascript:seeTheDifferencePopIn.close()">Close</a></div>'
						+ '<iframe src="/InternationalTrucks/TerraStar/' + cmpid + '" width="740" height="430" frameborder="0" scrolling="no"></iframe>'
						+ '</div>');
			$("#seeTheDifferenceWashout, #seeTheDifferencePopIn").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
			$("#seeTheDifferenceWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
			$("#seeTheDifferencePopIn").css({border:"2px solid #ffffff",top:_this.getT()+"px",left:_this.getL()+"px",width:"740px",height:"450px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});		
			$("#seeTheDifferenceWashout").fadeTo(500, .6, function() {
				$("#seeTheDifferencePopIn").fadeTo(500, 1);
			});	
		}
	};
	this.close = function()
	{
		$("#seeTheDifferencePopIn").fadeTo(500, 0, function() {
			$("#seeTheDifferenceWashout").fadeTo(500, 0, function() { _this.closed = true; $("#seeTheDifferenceWashout").remove(); $("#seeTheDifferencePopIn").remove(); $(window).unbind("resize", seeTheDifferencePopIn.adjust); });
		});	
	};
}
var seeTheDifferencePopIn = new seeTheDifferencePopInObj();

//Added for emergency for terrastar
function viewMatsVideoObj()
{
	var _this = this;
	this.closed = true;
	this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
 	this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
	this.getT = function() { return ((_this.getH() - 526) / 2) + $("body").scrollTop(); };
	this.getL = function() { return ((_this.getW() - 740) / 2); };
	
	this.adjust = function()
	{

		if(!$.support.cssFloat)
			$("#seeTheDifferencePopIn").css({left:_this.getL()});
		else
			$("#seeTheDifferencePopIn").animate({left:_this.getL()}, 100);
	};

	this.open = function(campaign)
	{
		if(_this.closed)
		{
			_this.closed = false;
			
			var cmpid = (typeof campaign != "undefined") ? "?cmpid=" + campaign : "";
			
			$(window).bind("resize", viewMatsVideo.adjust);
			$("body").append('<div id="seeTheDifferenceWashout">&nbsp;</div>');
			$("body").append('<div id="seeTheDifferencePopIn">'
						+ '<div style="text-align:right;padding:3px;"><a style="color:#FC6E2A;" href="javascript:viewMatsVideo.close()">Close</a></div>'
						+ '<iframe src="/InternationalTrucks/PageContent/MatsVideo/' + cmpid + '" width="670" height="610" frameborder="0" scrolling="no"></iframe>'
						+ '</div>');
			$("#seeTheDifferenceWashout, #seeTheDifferencePopIn").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
			$("#seeTheDifferenceWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
			$("#seeTheDifferencePopIn").css({border:"2px solid #ffffff",top:"30px",left:_this.getL()+"px",width:"670px",height:"630px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});		
			$("#seeTheDifferenceWashout").fadeTo(500, .6, function() {
				$("#seeTheDifferencePopIn").fadeTo(500, 1);
			});	
		}
	};
	this.close = function()
	{
		$("#seeTheDifferencePopIn").fadeTo(500, 0, function() {
			$("#seeTheDifferenceWashout").fadeTo(500, 0, function() 
			{ 
				_this.closed = true; 
				$("#seeTheDifferenceWashout").remove(); 
				$("#seeTheDifferencePopIn").remove(); 
				$(window).unbind("resize", viewMatsVideo.adjust); 
			});
		});	
	};
}
var viewMatsVideo = new viewMatsVideoObj();

var viewSyndicatedVideo = new function viewSyndicatedVideoObj()
{

	var _this = this;
	this.closed = true;
	this.getH = function() { if( typeof( window.innerHeight ) == 'number' ) { return window.innerHeight; } else if( document.documentElement && document.documentElement.clientHeight ) { return document.documentElement.clientHeight; } else if( document.body && document.body.clientHeight ) { return document.body.clientHeight; } return 0; };
 	this.getW = function() { if( typeof( window.innerWidth ) == 'number' ) { return window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { return document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { return document.body.clientWidth; } return 0; };
	this.getT = function() { return ((_this.getH() - 526) / 2) + $("body").scrollTop(); };
	this.getL = function() { return ((_this.getW() - 740) / 2); };
	
	this.adjust = function()
	{

		if(!$.support.cssFloat)
			$("#seeTheDifferencePopIn").css({left:_this.getL()});
		else
			$("#seeTheDifferencePopIn").animate({left:_this.getL()}, 100);
	};

	this.open = function(campaignURL)
	{
		if(_this.closed)
		{
			_this.closed = false;
			
			//var cmpid = (typeof campaign != "undefined") ? "?cmpid=" + campaign : "";
			
			$(window).bind("resize", viewSyndicatedVideo.adjust);
			$("body").append('<div id="seeTheDifferenceWashout">&nbsp;</div>');
			$("body").append('<div id="seeTheDifferencePopIn">'
						+ '<div style="text-align:right;padding:3px;"><a style="color:#FC6E2A;" href="javascript:viewSyndicatedVideo.close()">Close</a></div>'
						+ '<iframe src="' + campaignURL + '" width="740" height="430" frameborder="0" scrolling="no"></iframe>'
						+ '</div>');
			$("#seeTheDifferenceWashout, #seeTheDifferencePopIn").css({position:"absolute",top:"0",left:"0",opacity:"0",filter:"alpha(opacity=0)"});
			$("#seeTheDifferenceWashout").css({backgroundColor:"#000000",width:"970px",height:$("#all").height() + "px",zIndex:"100"});
			$("#seeTheDifferencePopIn").css({border:"2px solid #ffffff",top:"30px",left:_this.getL()+"px",width:"740px",height:"450px",zIndex:"200",textAlign:"center",backgroundColor:"white",fontFamily:"arial",fontSize:"12px",color:"black"});		
			$("#seeTheDifferenceWashout").fadeTo(500, .6, function() {
				$("#seeTheDifferencePopIn").fadeTo(500, 1);
			});	
		}
	};
	this.close = function()
	{
		$("#seeTheDifferencePopIn").fadeTo(500, 0, function() {
			$("#seeTheDifferenceWashout").fadeTo(500, 0, function() 
			{ 
				_this.closed = true; 
				$("#seeTheDifferenceWashout").remove(); 
				$("#seeTheDifferencePopIn").remove(); 
				$(window).unbind("resize", viewSyndicatedVideo.adjust); 
			});
		});	
	};
}

/*********************************************************************
*check for vanity url triggers
**********************************************************************/


if(currentURLVars['gigid']){
	$(document).ready(function() {vgPopup.open('zimmer','/itrucks/templates/getingear/getingear.jsp?gigid='+currentURLVars['gigid'], true); return false;});
}
if(currentURLVars['workstarcng']){
	$(document).ready(function(){
		vgPopup.open("workstarCNG","/InternationalTrucks/PageContent/WorkStarCNG/?close=true",true);
		
	});
}
if (window.location == "http://www.internationaltrucks.com/Trucks/?getingear=true") {
	//window.onload=function() {showMedia('terrastar-videos',740,475,false,true);}
	$(document).ready(function() {vgPopup.open('zimmer','/itrucks/templates/getingear/getingear.jsp', true); return false;});
}

// special code for terrastar launch - if on the vanity url, auto play the video
if (window.location.href.toLowerCase().indexOf("/terrastar/video")>0) {
	//window.onload=function() {showMedia('terrastar-videos',740,475,false,true);}
	$(document).ready(function() {seeTheDifferencePopIn.open(); return false;});
}

if (window.location.href.toLowerCase().indexOf("/trucks/matsvideohighlight")>0) {
	$(document).ready(function() {
		setTimeout(function() {
			viewSyndicatedVideo.open('/InternationalTrucks/PageContent/MatsVideo/highlights.html');
		}, 2000); 
		return false;
	});
}

if (window.location.href.toLowerCase().indexOf("/trucks/matsvideo")>0) {
	$(document).ready(function() {
		setTimeout(function() {
			viewSyndicatedVideo.open('/InternationalTrucks/PageContent/MatsVideo/single.html');
		}, 2000); 
		return false;
	});
}

if (window.location.href.toLowerCase().indexOf("/trucks/powerofone")>0) {
	$(document).ready(function() {
		setTimeout(function() {
			viewSyndicatedVideo.open('/InternationalTrucks/PageContent/MatsVideo/powerofonevideo.html');
		}, 2000); 
		return false;
	});
}

//terrastar see the difference
$(function() { if(getQueryVariable("seethedifference") != null) { seeTheDifferencePopIn.open(getQueryVariable("seethedifference")); } });
//experience the power of ONE (check keyword trigger or specific campaign ids) -- 04/28/10 removed campaign id triggers
//$(function() {if(getQueryVariable("experienceone") != null || (parseInt(getQueryVariable("cmpid")) >= 297 &&  parseInt(getQueryVariable("cmpid")) <= 328)) { iframeVideoPopIn.open('/InternationalTrucks/PageContent/PowerofONE/', 600, 245); } });
$(function() {if(getQueryVariable("experienceone") != null) { iframeVideoPopIn.open('/InternationalTrucks/PageContent/PowerofONE/', 600, 245); } });
//jake brake video
$(function() {if(getQueryVariable("jakebrake") != null) { iframeVideoPopIn.open('/InternationalTrucks/PageContent/JakeBrake/', 602, 402); } });
//driver display interactive demo
$(function() { if (window.location.href.toLowerCase().indexOf('/driverdisplaydemo')>0) {  iframeVideoPopIn.open('/InternationalTrucks/PageContent/DriverDisplayDemo/', 800, 600); } });
//pdf viewer test
//$(function() {if(getQueryVariable("video") == "results") { iframeVideoPopIn.open('/includes/pdfthumbviewer.html?pdfLoc=Truck%20Detail/ProStarResults.pdf&name=ProStar+WhitePaper.jpg', 611, 792); } });

//prostar efficiency video
$(function() {if(getQueryVariable("video") == "results") { iframeVideoPopIn.open('/InternationalTrucks/PageContent/ProstarEfficiency/', 640, 360); } });

// clickhandler for members monthly/enewsletter promos
var promoClickTracker = function (promoObj,promoNum) {
	var s = s_gi("navintratchet-testing");
	s.trackExternalLinks=false; //turn off exit link tracking
	s.linkTrackVars="prop3,prop4,prop6";
	try {
		var v = window.location.href.split("?")[0].split("/");
		s.prop3 = v[v.length-1]; // vocation
	} catch(e) {}
	s.prop4=getQueryVariable("newsletter"); // newsletter type
	s.prop6="Position " + promoNum; // promo position
	var promoTitle=$(promoObj).attr("title"); // if no title, pass default string
	s.tl(promoObj,"o",(promoTitle=="") ? "No Title" : promoTitle);
}
// add the clickhandler to the promos on members monthly pages
if ((window.location.href.toLowerCase().indexOf("newsletter=membersmonthly")>=0) || (window.location.href.toLowerCase().indexOf("newsletter=enewsletter")>=0)) {
	$(document).ready(function() {
		$(".mainRightBlockFIRST").each(function(i) {
			$(this).children("a").click(function(e) {
				promoClickTracker(this,i+1);
				/* for debugging:*
				e.preventDefault();
				return false;
				*/
			});
		});
	});
}

/* /Trucks/Services?oncommandSolutions=true */
if(currentURLVars['oncommandSolutions']){
	$(document).ready(function(){
		viewSyndicatedVideo.open('/InternationalTrucks/PageContent/Services/onCommandVideo/');
	});
}

/*********************************************************************
*show hide for model navigation
**********************************************************************/
function toggle() {
	var ele = document.getElementById("showModel");
	var text = document.getElementById("displayText");
	if(ele.style.display == "block") {
		ele.style.display = "none";
	text.innerHTML = "Models";
  	}
  	else {
  	ele.style.display = "block";
  	text.innerHTML = "Models";
	}
} 

/*********************************************************************
*cja for model navigation
**********************************************************************/

$(document).ready(function(){
	$("#nav-one li").hover( 
			function() {
				var numChildren = $(this).children('ul.models').children('li').length;
				if(numChildren > 5)
				{
					$(this).children('ul.models').css('left','-170px');
				}
				$(this).addClass("sfHover");
		},
		function() {
				$(this).removeClass("sfHover");
		}
	);
});

/**********************************************************************
* For facebook like integration
**********************************************************************/

$(document).ready(function() {
	$.getScript("/itrucks/library/js/facebook.js");
	/*
	var windowUrl = window.location.href;
	var isNewsletter = windowUrl.indexOf('newsletter');
	var isaArticle = windowUrl.indexOf('#article');
	if(isNewsletter > -1 || isaArticle > -1){
		$('head').append('<meta property="og:title" content="Article Title" /><meta property="og:site_name" content="International Trucks"/>');
	}
	*/
});

/**********************************************************************
* set sign in sentinel to false on logout
**********************************************************************/
$('.iaulisignout').click(function(){
	iaULI = false;
});

/**********************************************************************
* very generic popup
**********************************************************************/

var vgPopup = {
	open: function(cClass, url, isStatic, customPlacement, params){
		$('.vgPopup').remove();
		$('body').append(
		'<div class="vgPopup '+cClass+'">\
			<div class="vgPopupDim"></div>\
			<div class="vgPopupWrap">\
				<div class="vgPopupHeader"></div>\
				<a href="#" class="vgPopupClose"></a>\
				<iframe id="iframeContent" frameborder="0" src="'+url+'" class="vgPopupFrame"></iframe>\
			</div>\
		</div>'
		);
		$('.'+cClass+' iframe').height($('.vgPopupWrap').height()-$('.vgPopupHeader').height());
		
		if(isStatic){
			vgPopup.bind();
			vgPopup.center($('.vgPopupWrap'));
		}
		if(!isStatic && customPlacement){
			if(params == undefined || params == null){
				params = null;
			}
			vgPopup.bind(customPlacement, params);
			vgPopup.customPlacement($('.vgPopupWrap'), params);
		}
	},
	close: function(){
		$('.vgPopup').remove();
		$(window).unbind('scroll');
		$(window).unbind('resize');
		return false;
	},
	bind: function(custom, params){
		if(!custom){
			$(window).bind('scroll', function() {vgPopup.center($('.vgPopupWrap'))});
			$(window).bind('resize', function() {vgPopup.center($('.vgPopupWrap'))});
			$('a.vgPopupClose').click(vgPopup.close);
		}
		else{
			if(params == undefined || params == null){
				vgPopup.customPlacement($('.vgPopupWrap'), params);
			}
			else{
				$(window).bind('scroll', function() {vgPopup.customPlacement($('.vgPopupWrap'), params)});
				$(window).bind('resize', function() {vgPopup.customPlacement($('.vgPopupWrap'), params)});
			}
			$('a.vgPopupClose').click(vgPopup.close);
		}
	},
	center: function($obj){
		$('.vgPopupDim').css({'top':$(window).scrollTop()+'px','height': $(window).height()+'px', 'width':$(window).width()+'px','display':'block'}); 
		$obj.stop(true);
		$obj.animate({
			left: ( $(window).width() - $obj.width() ) / 2+$(window).scrollLeft() + "px",
			top: ( $(window).height() - $obj.height() ) / 2+$(window).scrollTop() + "px"
		});

	},
	customPlacement: function($obj, params){
		if(params == undefined || params == null){
			params = new Object();
			var leftPos = ( $(window).width() - $obj.width() ) / 2+$(window).scrollLeft() + "px";
			//params.top = ( $(window).height() - $obj.height() ) / 2+$(window).scrollTop() + "px";
			params.top = '50px';
		}
		else{
			var leftPos = (params.leftHolder.offset().left)+params.leftMargin;
		}
		$obj.stop(true);
		$obj.css({
			left: leftPos,
			top: params.top
			//left: ( $(window).width() - $obj.width() ) / 2+$(window).scrollLeft() + "px",
			//top: ( $(window).height() - $obj.height() ) / 2+$(window).scrollTop() + "px"
		});

	}
}

/**********************************************************************
* popup timeout - REMOVED 12-28-2009
**********************************************************************/
/*
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function openGigPopup(){
	var url = 'timePop';
	vgPopup.open('zimmer','/itrucks/templates/getingear/getingearPop.jsp?gigid='+url, true);
	createCookie('timePopCookie','set',1);
}
function checkPopCookie(){
	var x = readCookie('timePopCookie');
	if(!x){
		setTimeout("openGigPopup()", 60000);
	}
}
checkPopCookie();
*/

/* //////////////////////////////////////////////////////////////////////////
//CODE TO DO THE ANNOYING POP-UNDER WHEN LOADING A PAGE
//////////////////////////////////////////////////////////////////////////
//specify page to pop-under
var popunder="http://staging.internationaltrucks.com/itrucks/facebook.html";

//specify popunder window features
//set 1 to enable a particular feature, 0 to disable
var winfeatures="width=450,height=200,scrollbars=0,resizable=0,toolbar=0,location=0,menubar=0,status=0,directories=0";

//Pop-under only once per browser session? (0=no, 1=yes)
//Specifying 0 will cause popunder to load every time page is loaded
var once_per_session=1;

function get_cookie(Name) {
	var search = Name + "=";
	var returnvalue = "";
	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search);
		if (offset != -1) { // if cookie exists
			offset += search.length;
			//set index of beginning of value
			end = document.cookie.indexOf(";", offset);
			//set index of end of cookie value
			if (end == -1)
				end = document.cookie.length;
			returnvalue=unescape(document.cookie.substring(offset, end));
		}
	}
	
	return returnvalue;
}

function loadornot(){
	if (get_cookie('popunder')==''){
		// set date to right now
		var now = new Date();
	
		// from now add one day
		// 1000 ms in a second * 60 seconds in a minute * 60 minutes in an hour * 24 hours in a day
		now.setTime(now.getTime() + (1000 * 60 * 60 * 24 * 7) );

		document.cookie="popunder=yes" + ";expires=" + now;
		
		loadpopunder();
	}
}

function loadpopunder(){
	win2=window.open(popunder,"",winfeatures);
	if(win2){
		win2.blur();
	}
	window.focus();
}

//Calls the function to load the pop-under
if (once_per_session==0)
	loadpopunder();
else
	loadornot();
*/
/* //////////////////////////////////////////////////////////////////////////
//random functions
//////////////////////////////////////////////////////////////////////////*/

function viewLocalOffersTemp(){
	vgPopup.open('zimmer', '/itrucks/templates/ditbyZip/ditby.jsp', true);
	$('#trucksPanel').fadeOut(500);
	$('#truckSearchBackDrop').hide();
}

/* //////////////////////////////////////////////////////////////////////////
//file for redesign-specific js on staging
//////////////////////////////////////////////////////////////////////////*/

function removeUselessVignetteSpacers(){
	var spacerParent = [];
	var deleteParent = false;
	$('img[src="/portal/images/misc/spacer.gif"]').each(function(i){
		spacerParent[i] = $(this).parent().parent();
		if(spacerParent[i].is('tr') == true)
			spacerParent[i].remove();
	});
}
function borderEnhancement(){
	var needsBorder = $('table#all tbody tr:nth-child(2) td:first table:first tbody tr:first td:first table:first tbody:first tr:first td:first table:first');
	needsBorder.css('margin-left','1px');
}

/* //////////////////////////////////////////////////////////////////////////
//generic ajax call
//////////////////////////////////////////////////////////////////////////*/

var genAjaxCall = {
		go: function(type, url, data, returnData, callback, other1, other2) {
			$.ajax({
				type: type,
				url: url,
				data: data,
				success: function(msg){
				if(returnData){
					if(other1 && !other2)
						callback(msg, other1);
					else if(other1 && other2)
						callback(msg, other1, other2);
					else
						callback(msg);
				}
				else
					callback();
				},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				//alert('There has been an error with your request, please try again.');
			}
		});
	}
};

/* //////////////////////////////////////////////////////////////////////////
//header functionality
//////////////////////////////////////////////////////////////////////////*/

var itHeaderFunctions = {
	search: function(){
		var defaultText = 'Search';
		$('#topMenuBoxText').val(defaultText);
		$('#topMenuBoxText').focus(function(){
			var thisGuy = $(this);
			if(thisGuy.val() == defaultText){
				thisGuy.val('');
			}
		});
		$('#topMenuBoxText').blur(function(){
			var thisGuy = $(this);
			if(thisGuy.val() == ''){
				thisGuy.val(defaultText);
			}
		});
		$('.itSearchGo').live('click',function(){
			var searchingFor = $('#topMenuBoxText').val();
			if(searchingFor !== '' && searchingFor !== defaultText){
				window.location.href='/Trucks/Search?q='+searchingFor;
			}
			return false;
		});
	},
	drops: function(){
		$('li.sitesDropDown > a').live('click',function(){
			var thisGuy = $(this).parent();
			$('body').bind('click',function(){
				$('li.sitesDropDown').find('ul.dropDownList').hide();
				$(this).unbind('click');
			});
			$('li.dropDownListHeader > a').bind('click',function(){
				$('li.sitesDropDown').find('ul.dropDownList').hide();
				$(this).unbind('click');
				return false;
			});
			thisGuy.siblings('.sitesDropDown').find('ul.dropDownList').hide();
			thisGuy.children('ul.dropDownList').toggle();
			//thisGuy.toggleClass('headerDropDownOpen');
			return false;
		});
		$('a.sitesDropUp').live('click',function(){
			var thisGuy = $(this);
			$('body').bind('click',function(){
				$('a.sitesDropUp').siblings('.dropUpList').hide();
				$(this).unbind('click');
			});
			thisGuy.siblings('ul.dropUpList').hide();
			thisGuy.siblings('ul.dropUpList').toggle();
			return false;
		});
		$('li.dropUpListHeader > a').live('click',function(){
			var thisPar = $(this).parent().parent();
			thisPar.hide();
			return false;
		});
	},
	trucksClicks: 0,
	onHomePage: false,
	truckClickPromo: 1,
	truckSearchOverlay: function(){
		var _this = this;
		if($('#homePageMainContentBody').length > 0){
			_this.onHomePage = true;
		}
		// click function for clickable things that click
	//	if(jQuery.browser.mobile || (navigator.userAgent.toLowerCase()).match(/(ipad)/)){
			$('.mainMenu a#navMenuTrucks').live('click',function(){
				// set promotator values
				if(_this.onHomePage){
					var prom = $('#homePageMainContentBody').find('.promotatorPromo:visible').attr('id').toString().replace('promotatorPromoID','');
					_this.truckClickPromo = parseFloat(prom);
					var thisObj = $('#markerNum'+_this.truckClickPromo+' a');
				}
				// close any other popups
				$('li.sitesDropDown').find('ul.dropDownList').hide();
				$('footerWrapper .dropUpList').hide();
				itHeaderFunctions.trucksClicks++;
				itHeaderFunctions.searchPanelIsOpen = true;
				$('#trucksPanel').toggleClass('truckPanelIsOpen');
				if($('#trucksPanel').hasClass('truckPanelIsOpen')){ // open panel
					if(_this.onHomePage){
						promotator.forcePromo(_this.truckClickPromo, thisObj); // pause promotator
					}
					genOmn.init("prop29:Close"); // omniture
					//tt_Log('/Trucks'); // test and target call
					var bodyHeight = $('body').height();
					var bodyWidth = $('body').width();
					$('#truckSearchBackDrop').height(bodyHeight).width(bodyWidth).show();
					$('#trucksPanel').fadeIn(500);
					$('#trucksPanel a.closeBtn').show();
				} else{ // close panel
					$('#trucksPanel').fadeOut(500);
					$('#truckSearchBackDrop').hide();
					if(_this.onHomePage){
						promotator.forcePromo(_this.truckClickPromo, thisObj, true); // run promotator
					}
				}
				truckSearchFunctions.ajaxOut(itHeaderFunctions.trucksClicks);
				return false;
			});
			$('#truckSearchBackDrop').live('click',function(){ // click backdrop to close panel
				genOmn.init("prop29:Close");
				$('#trucksPanel').fadeOut(500).die();
				$('#truckSearchBackDrop').hide();
				if($('#trucksPanel').hasClass('truckPanelIsOpen')){
					$('#trucksPanel').removeClass('truckPanelIsOpen');
				}
				if(_this.onHomePage){
					promotator.forcePromo(_this.truckClickPromo, thisObj, true); // run promotator
				}
			});
		/*}
		// hover function for nonclickable things that don't click
		else { // hover functionality
			truckSearchFunctions.ajaxOut(itHeaderFunctions.trucksClicks);
			$('.mainMenu a#navMenuTrucks').live('click',function(){return false;}).live('mouseover',function(){
				genOmn.init("events:event32,prop29:Trucks");
				// set promotator values
				if(_this.onHomePage){
					var prom= $('#homePageMainContentBody').find('.promotatorPromo:visible').attr('id').toString().replace('promotatorPromoID','');
					_this.truckClickPromo = parseFloat(prom);
					var thisObj = $('#markerNum'+_this.truckClickPromo+' a');
				}
				// close any other poups
				$('li.sitesDropDown').find('ul.dropDownList').hide();
				$('footerWrapper .dropUpList').hide();
				if(_this.onHomePage){
					promotator.forcePromo(_this.truckClickPromo, thisObj); // pause promotator
				}
				itHeaderFunctions.trucksClicks++;
				itHeaderFunctions.searchPanelIsOpen = true;
				var bodyHeight = $('body').height();
				var bodyWidth = $('body').width();
				if( window.location.href.indexOf( '/Trucks/portfolio' ) > -1 )
					$('#truckSearchBackDrop').height('100%').width(bodyWidth).show();
				else
					$('#truckSearchBackDrop').height(bodyHeight).width(bodyWidth).show();
				
				$('#trucksPanel').fadeIn(500);
				//truckSearchFunctions.ajaxOut(itHeaderFunctions.trucksClicks);
				$('#trucksPanel').live('mouseleave',function(){
					genOmn.init("prop29:Close");
					$('#trucksPanel').fadeOut(500).die();
					$('#truckSearchBackDrop').hide();
					if($('#trucksPanel').hasClass('truckPanelIsOpen')){
						$('#trucksPanel').removeClass('truckPanelIsOpen');
					}
					//promotator.forcePromo(_this.truckClickPromo, thisObj, true); // run promotator
				});
			});
			
		}*/
	},
	init: function(){
		itHeaderFunctions.search();
		itHeaderFunctions.drops();
		itHeaderFunctions.truckSearchOverlay();
	}
};

/* //////////////////////////////////////////////////////////////////////////
//truck search overlay functionality
//////////////////////////////////////////////////////////////////////////*/

var truckSearchFunctions = {
	search: function(){
		var defaultText = 'Enter Zip Code';
		$('.zipCodeSearch').val(defaultText);
		$('.zipCodeSearch').focus(function(){
			var thisGuy = $(this);
			if(thisGuy.val() == defaultText){
				thisGuy.val('');
			}
		});
		$('.zipCodeSearch').blur(function(){
			var thisGuy = $(this);
			if(thisGuy.val() == ''){
				thisGuy.val(defaultText);
			}
		});
		$('.zipCodeSearchGo').live('click',function(){
			var searchingFor = $('.zipCodeSearch').val();
			if(searchingFor !== '' && searchingFor !== defaultText){
				//window.location.href='/Trucks/Search?q='+searchingFor;
				return false;
			}
			return false;
		});
		$('#panelHead .rightSide .closeBtn').live('click',function(){
			$('#trucksPanel').removeClass('truckPanelIsOpen');
			genOmn.init("prop29:Close");
			$('#trucksPanel').fadeOut(500);
			$('#truckSearchBackDrop').hide();
			return false;
		});
	},
	buildOverlay: function(html){
		// set countdown to fun!
		var timeDelay = 2000;
		function setContent(){
			$("#trucksPanel #panelBody").html(html);
		}
		setTimeout(function(){setContent()},timeDelay);
	},
	ajaxOut: function(count){
		if(count <= 1){
			// ajax that trash!
			genAjaxCall.go('GET', '/itrucks/templates/truck/truckSearchOverlay.jsp', null, true, truckSearchFunctions.buildOverlay);
		}
	},
	init: function(){
		truckSearchFunctions.search();
	}
};

var inventoryAjaxCall = {
	service: '',
	clientIp: null,
	getCookie: function(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 "";
	},
	results: function(num, series, obj){
		var n = num;
		var ns = n.toString().replace(/\s/g,'');
		/*
		if(series == '9000')
			var r = n+' 9900s in your area';
		else
			var r = n+' '+series+'s in your area';
		*/
		var r = 'Inventory ('+ns+') in your area';
		if(ns == 0 || ns == '0')
			r = 'Check Inventory';
		if(obj)
			obj.html(r);
	},
	init: function(series, obj){
		var s = window.location.href.toString().indexOf('staging');
		var t = window.location.href.toString().indexOf('230');
		if(s > -1 || t > -1)
			this.service = 'http://staging.internationaltrucks.com/SOARR/seriesCount.jsp';
		else
			this.service = 'http://www.internationaltrucks.com/SOARR/seriesCount.jsp';
		var zip = this.getCookie('zip');
		this.clientIp = $('input#clientIp').val();
		var data = 'series='+series;
		if(zip != '')
			data += '&zip='+zip;
		else
			data += '&clientIp='+this.clientIp;
		genAjaxCall.go('GET', this.service, data, true, inventoryAjaxCall.results, series, obj);
	}
};

/* //////////////////////////////////////////////////////////////////////////
//right rail enewsletter
//////////////////////////////////////////////////////////////////////////*/

$('.enewsMLeft input#btnSignup').live('click',function(){
	genOmn.init("events:event7, eVar5:Right Rail");
});

/* //////////////////////////////////////////////////////////////////////////
//small business / turn-in-three lease page
//////////////////////////////////////////////////////////////////////////*/

var smallBizForm = {
	checkForVids: function(){
		var _t = this;
		var walkAround = currentURLVars['walkAround'];
		if( walkAround != null && walkAround != '' ) {
			$(document).ready(function() {
				_t.walkAroundVid(walkAround);
			});
		}
	},
	walkAroundVid: function(name){
		if(name.toLowerCase() == 'terrastar')
			vgPopup.open("walkAroundVid","/InternationalTrucks/PageContent/TerraStarWalkAroundVideo/vidLarge.html", true);
		else if(name.toLowerCase() == 'durastar')
			vgPopup.open("walkAroundVid","/InternationalTrucks/PageContent/DuraStarWalkAroundVideo/", true);
	},
	setDefs: function(){
		if( $('#smallBizDataForm #valCode').length > 0 ){
			var mainField = $('#smallBizDataForm #valCode');
			mainField.defaultVal = 'Enter Your Validation Code';
		} else {
			var mainField = $('#smallBizDataForm #zip');
			mainField.defaultVal = 'Enter Your Zip Code';
		}
		var all = {mainField:mainField};
		$.each(all, function(k,v){
			v.val(v.defaultVal);
			v.focus(function(){
				if(v.val() == v.defaultVal)
					v.val('');
			});
			v.blur(function(){
				if(v.val() == '')
					v.val(v.defaultVal);
			});
		});
	},
	verifyMainField: function(){
		var specialPass = true;
		$('#smallBizDataForm .digits').each(function(){
			var digits = $.trim( $(this).val() );
			var isValid = ( isNaN(digits) ) ? false : true;
			if(digits != '' && !isValid){
				specialPass = false;
				$(this).addClass('errorBorder');
				$('<p class="error">Please enter a valid code</p>').insertBefore('#smallBizDataForm .digits');
			}
		});
		return specialPass;
	},
	setReferrerCookie: function(){
		var _t = this;
		this.create = function(name, days, domain) {
			var referrer = document.referrer;
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			if(domain){
				var domain = "; domain="+domain;
			}
			else var expires = "";
			document.cookie = name+"="+referrer + expires + domain + "; path=/";
		};
		this.read = function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		};
		this.erase = function(name) {
			this.create(name,"",-1);
		};
		this.check = function(name){
			var cookieExists = _t.read(name);
			if(cookieExists){
				_t.erase(name);
			}
			_t.create(name, 1, 'internationaltrucks.com');
		};
		_t.check('referCookie');
	},
	init: function(){
		this.setDefs();
		this.checkForVids();
		this.setReferrerCookie();
		$('#smallBizDataForm #submit').click(function(){
			$('#smallBizDataForm p.error').remove();
			var didPass = smallBizForm.verifyMainField();
			return didPass;
		});
	}
};

/* //////////////////////////////////////////////////////////////////////////
//big bore portfolio
//////////////////////////////////////////////////////////////////////////*/

var bigBorePortfolio = {
	onPage: 1, // default page
	setPage: function(n){
		this.onPage = n;
		this.checkPage();
	},
	checkPage: function(){
		$('.portfolioPart').hide();
		$( '#portfolioPart' + this.onPage ).show();
		
		if( this.onPage == 1 || this.onPage == 2 )
			$('body').css('background','url("/itrucks/templates/portfolio/images/portfolioBkg.jpg") no-repeat scroll center 0 #000');
		else
			$('body').css('background','#000');
			
		if( this.onPage == 3 ){
			$('#portfolioPart3 .truckDetail').hide();
			$('#portfolioPart3 #' + this.trucksToDisplay).show();
		}
		
		var footerPage4 = null;
		
		if( this.onPage == 4 ){
			$('#footerWrapper').removeClass('footerPush');
			footerPage4 = true;
		}
		else{
			$('#footerWrapper').addClass('footerPush');
			footerPage4 = false;
		}
	},
	userOptions: {
		lengthOfHaul: "",
		terrain: "",
		load: "",
		styling: ""
	},
	querySet: false,
	checkForUrlQueries: function(){
		var currentUrlVars = getUrlVars();
		
		if( currentUrlVars['stage'] ){
			bigBorePortfolio.onPage = currentUrlVars['stage'];
		}
			
		if( currentURLVars['qloh'] )
			bigBorePortfolio.userOptions.lengthOfHaul = currentURLVars['qloh'];
		if( currentURLVars['qt'] )
			bigBorePortfolio.userOptions.terrain = currentURLVars['qt'];
		if( currentURLVars['ql'] )
			bigBorePortfolio.userOptions.load = currentURLVars['ql'];
		if( currentURLVars['qii'] )
			bigBorePortfolio.userOptions.styling = currentURLVars['qii'];
		
		if( currentURLVars['qloh'] && currentURLVars['qt'] && currentURLVars['ql'] && currentURLVars['qii'] )
			bigBorePortfolio.querySet = true;
	},
	
	// list of truck possiblities
	trucks: [
		{ name: "transtar mxf11",		id: "tm11",		lengthOfHaul: "city",		terrain: "flat",				load: "light",			styling: "less, medium, high" },
		{ name: "transtar mx13",		id: "tm13",		lengthOfHaul: "city",		terrain: "moderate, steep",		load: "moderate, heavy",	styling: "less, medium, high" },
		{ name: "prostar day mxf11",		id: "pdm11",	lengthOfHaul: "regional",	terrain: "flat",				load: "light, moderate",		styling: "less, medium, high" },
		{ name: "prostar day mxf13",		id: "pdm13",	lengthOfHaul: "regional",	terrain: "moderate",			load: "light, moderate",		styling: "less, medium" },
		{ name: "prostar day mx15",		id: "pdm15",	lengthOfHaul: "regional",	terrain: "steep",				load: "heavy",			styling: "less, medium, high" },
		{ name: "lonestar day mxf13",	id: "ldm13",	lengthOfHaul: "regional",	terrain: "moderate, steep",		load: "moderate",		styling: "high" },
		{ name: "lonestar sleeper mxf13",	id: "lsm13",	lengthOfHaul: "long haul",	terrain: "flat, moderate",		load: "light, moderate",		styling: "high" },
		{ name: "prostar sleeper mxf13",	id: "psm13",	lengthOfHaul: "long haul",	terrain: "flat, moderate, steep",	load: "light, moderate",		styling: "less, medium" },
		{ name: "prostar sleeper mxf15",	id: "psm15",	lengthOfHaul: "long haul",	terrain: "steep",				load: "heavy",			styling: "less, medium, high" }
	],

	pArray: [],
	trucksToDisplay: "",
	
	validateFields: function(){
		var allFilled = true;
		$('.truckOptions').each(function(){
			var $defaultTitle = $(this).attr('title');
			var $dropMainText = $(this).find( '.dropMain' ).text();
			
			$(this).removeClass('errorBorder');
			
			if( $dropMainText == $defaultTitle ){
				$(this).addClass('errorBorder');
				allFilled = false;
			}
		});
		return allFilled;
	},
	
	changeTruckBkg: function(ttd){
		$('body').css('background','url("/itrucks/templates/portfolio/images/' + ttd + '_bkg.jpg") no-repeat scroll center 0 #000');
	},
	
	executeSearch: function(){
		$('p.error').remove();
		
		if( !bigBorePortfolio.querySet )
			var checksOut = bigBorePortfolio.validateFields();
		else
			var checksOut = bigBorePortfolio.querySet;
		
		bigBorePortfolio.querySet = false;
		if( checksOut ){
			$.each(bigBorePortfolio.trucks, function(truck, options){
				var ploh = options.lengthOfHaul;
				var pt = options.terrain;
				var pl = options.load;
				var pii = options.styling;
			
				if(
					ploh.indexOf( bigBorePortfolio.userOptions.lengthOfHaul ) > -1 &&
					pt.indexOf( bigBorePortfolio.userOptions.terrain ) > -1 &&
					pl.indexOf( bigBorePortfolio.userOptions.load ) > -1 &&
					pii.indexOf( bigBorePortfolio.userOptions.styling ) > -1
				)
				bigBorePortfolio.pArray.push( options.id );
			});
			
			if( bigBorePortfolio.pArray[0] ){
				bigBorePortfolio.trucksToDisplay = bigBorePortfolio.pArray[0];
				bigBorePortfolio.setPage( 3 );
				bigBorePortfolio.changeTruckBkg( bigBorePortfolio.trucksToDisplay );
			} else {
				$('<p class="error">No trucks matching your search criteria</p>').insertBefore('#portfolioPart2 #portfolioRightContent .truckOptions:first');
			}
			
			bigBorePortfolio.pArray = [];
			bigBorePortfolio.trucksToDisplay = "";
			bigBorePortfolio.omnitureQueue.trackExecuteSearch();
		} else {
			$('<p class="error">Please fill out all fields</p>').insertBefore('#portfolioPart2 #portfolioRightContent .truckOptions:first');
		}
	},
	bindThings: function(){
		var _t = this;
		$('#flipPage').live('click', function(){
			var n = _t.onPage + 1;
			_t.setPage( n );
			return false;
		});
		$('#backPeddle').live('click', function(){
			if( _t.onPage == 2 ) var n = 1;
			else var n = 2;
			_t.setPage( n );
			return false;
		});
		$('#compareQuery').live('click', function(){
			_t.setPage( 4 );
			return false;
		});
		$('.fakeSelect .option').hover(
			function(){
				$(this).addClass('hover');
			}, function(){
				$(this).removeClass('hover');
			}
		);
		$('.fakeSelect .dropMain').live('click', function(){
			var $t = $(this);
			var $fakeSelect = $t.parent();
			var $title = $fakeSelect.attr('title');
			var $backupText = $t.text();
			
			$t.removeClass('filled').text( $title );
			$fakeSelect.addClass('open');
			
			$('#portfolioPart2').bind('click', function(){
				$t.text($backupText);
				if( $backupText != 'length of haul' && $backupText != 'terrain' && $backupText != 'load' && $backupText != 'styling' )
					$t.addClass('filled');
				$t.siblings('.option').css('display','none');
				$fakeSelect.removeClass('open');
				$('#portfolioPart2').unbind('click');
			});
			
			$t.siblings('.option').css('display','block')
				.click(function(){
					var $option = $(this);
					var $newtitle = $option.text();
					
					switch( $title ) {
						case "length of haul":		bigBorePortfolio.userOptions.lengthOfHaul = $newtitle;		break;
						case "terrain":			bigBorePortfolio.userOptions.terrain = $newtitle;			break;
						case "load":			bigBorePortfolio.userOptions.load = $newtitle;			break;
						case "styling":			bigBorePortfolio.userOptions.styling = $newtitle;			break;
						default:				return false;
					}
					
					$t.addClass('filled').text($newtitle);
					$t.siblings('.option').css('display','none');
					$fakeSelect.removeClass('open');
					$('#portfolioPart2').unbind('click');
				});
		});
		$('#submitQuery').live('click', function(){
			bigBorePortfolio.executeSearch();			
			return false;
		});
		$('.truckDetail #mid .calloutPlus').live('click', function(){
			$('.calloutBox').hide();
			
			// set z-index for clicked
			var parentCallout = $(this).parent();
			var parentSiblings = parentCallout.siblings('.callout');
			parentCallout.css('zIndex','1');
			parentSiblings.css('zIndex','0');
			
			parentSiblings.find('.calloutBox').removeClass('isOpen');
			
			var calloutBox = $(this).siblings('.calloutBox');
			if( calloutBox.hasClass('isOpen') )
				calloutBox.hide().removeClass('isOpen');
			else
				calloutBox.show().addClass('isOpen');
		});
		$('.truckDetail #mid #calloutBackdrop').live('click', function(){
			$('.calloutBox').hide().removeClass('isOpen');
		});
	},
	// tracking of 'receive updates' newsletter form is done in enewsletterPopup.js in function thankYouSir();
	omnitureQueue: {
		trackClick: function( linkName ){
			genOmn.init( 'prop39:' + linkName );
			//console.log( 'trackClick | prop39:' + linkName );
		},
		trackExecuteSearch: function(){
			genOmn.init( 'prop39:Submit Search, prop40:' + bigBorePortfolio.userOptions.lengthOfHaul + ' ' + bigBorePortfolio.userOptions.terrain + ' ' + bigBorePortfolio.userOptions.load + ' ' + bigBorePortfolio.userOptions.styling );
			//console.log( 'trackExecuteSearch | prop39:Submit Search, prop40:' + bigBorePortfolio.userOptions.lengthOfHaul + ' ' + bigBorePortfolio.userOptions.terrain + ' ' + bigBorePortfolio.userOptions.load + ' ' + bigBorePortfolio.userOptions.styling );
		}
	},
	omnitureBindings: function(){
		// main start button
		$('#portfolioPart1 #flipPage').live('click', function(){
			bigBorePortfolio.omnitureQueue.trackClick( 'Find Your Truck' );
		});
		
		// out links and receive updates
		$('#portfolioPart3 .truckDetail').each(function(){
			var truckName = $(this).attr('id');
			$(this).find('.outLinks a').each(function(){
				$(this).bind('click', function(){
					bigBorePortfolio.omnitureQueue.trackClick( truckName + ' > ' + $(this).html() );
				});
			});
			$(this).find('#lower a').bind('click', function(){
				bigBorePortfolio.omnitureQueue.trackClick( truckName + ' > Receive Updates' );
			});
		});
		
		// view details button
		$('#portfolioPart4 #compareSection .truckSlice').each(function(){
			var truckName = $(this).attr('title');
			$(this).find('a.viewDetails').bind('click', function(){
				bigBorePortfolio.omnitureQueue.trackClick( truckName + ' > View Details' );
			});
		});
	},
	init: function(){
		this.omnitureBindings();
		this.checkForUrlQueries();
		
		if( this.querySet )
			this.executeSearch();
		else
			this.setPage(this.onPage);
		
		this.bindThings();
		
		// show hidden footer wrapper to avoid jump
		$(document).ready(function(){
			if( this.onPage != 4 )
				$('#footerWrapper').addClass('footerPush');
			else
				$('#footerWrapper').removeClass('footerPush');
				
			$('#footerWrapper').show();
		});
	}
};

/* lightbox || <a class="lightBox" href="#" rel="[name of jsp to ajax]" title="cliffordTheBigRedDog"></a> */
var lightBox = {
	init: function(){
		var _this = this;
		$('.lightBox').live('click', function(){
			// cast 'rel' to panelType
			var panelType = $(this).attr('rel');
			// grab query params
			var url = $(this).attr('href');
			var openTo = lightBox.splitPassedQueryString('openTo', url);
			var openTo2 = lightBox.splitPassedQueryString('openTo2', url);
			var href = lightBox.splitPassedQueryString('href', url);
			lightBox.open(panelType, openTo, href);
			return false;
		});
	},
	open: function(panelType, openTo, openTo2, href){
		var _this = this;
		
		_this.panelType = panelType;
		_this.openTo = openTo;
		_this.openTo2 = openTo2;
		_this.href = href;

		switch( _this.panelType ){
			case 'portfolio':
				_this.panel = $('#genericPanel');
				_this.jsp = '/itrucks/templates/portfolio/portfolio.jsp';
				_this.data = '?valcode=' + _this.openTo;
				break;
			case 'committment':
				_this.panel = $('#genericPanel');
				_this.jsp = '/itrucks/templates/v2.series/committmentVideo.jsp';
				_this.data = '';
				break;
			case 'driversroom':
				_this.panel = $('#genericPanel');
				_this.jsp = '/itrucks/templates/maxxforceVideo.jsp';
				_this.data = 'video=' + _this.openTo;
				break;
			case 'etLightBox':
				_this.panel = $('#genericPanel');
				_this.jsp = '/itrucks/templates/extraordinarytrucks/etLightBox.jsp';
				_this.data = 'xValCode=' + _this.openTo + '&compID=' + _this.openTo2;
				//_this.data = 'compID=' + _this.openTo2;
				break;
			default:
				_this.panel = $('#genericPanel');
		}
		_this.genericBackDrop = $('#genericBackDrop');

		var bodyHeight = $('body').height(); var bodyWidth = $('body').width(); var contentWidth = _this.panel.width();
		var leftPos = (bodyWidth-contentWidth)/2;
		
		_this.genericBackDrop.height(bodyHeight).width(bodyWidth).show();
		_this.panel.fadeIn(500, function(){ $(this).addClass('panelIsOpen'); });
		
		lightBox.bind();
		lightBox.center(true);
		lightBox.ajax();
	},
	bind: function(){
		var _this = this;
		$(window).bind('resize', function(){ lightBox.center(false); }).bind('scroll', function(){ lightBox.center(false); });
		$(window).bind('scroll', function(){ lightBox.center(false); });
		_this.panel.find('.panelHead .rightSide .closeBtn').live('click', function(){ lightBox.close(_this.panel); return false; });
		//_this.genericBackDrop.live('click',function(){ lightBox.close(false); });
	},
	close: function(){
		var _this = this;
		
		_this.panel.removeClass('panelIsOpen');
		var loaderHtml = '<div class="spinnerWrapper"><img src="/itrucks/templates/portfolio/images/loadingSpinner.gif" /><br class="clear" /><h3>Loading...</h3></div>';
		_this.panel.fadeOut('fast').find('.panelBody').html(loaderHtml);
		$('#genericBackDrop').hide().unbind('click');
		
		if( _this.panel.attr('id') == 'genericPanel' )
			_this.panel.find('.panelBody > .leftSide, .panelBody > .rightSide, #leftNavOverlay, #rightNavOverlay').unbind('click');
		else if( _this.panelType == 'vehicleCompare' || _this.panelType == 'engineCompare' )
			omnitureQueue.closeCompareOverlayTrack( _this.panelType + ' > ' + _this.openTo );
		
		$(window).unbind('scroll');
		$(window).unbind('resize');
	},
	center: function(init){
		var _this = this;
		var bodyWidth = $('body').width();
		var bodyHeight = $('body').height();
		var contentWidth = _this.panel.width();
		var scrollLeft = $(window).scrollLeft();
		var scrollTop = $(window).scrollTop();
		
		var leftPos = (bodyWidth-contentWidth)/2;
		var topPos = ($(window).scrollTop())+100;
		if(init)
			_this.panel.css({'left':leftPos+'px', 'top':topPos+'px'});
		else
			_this.panel.animate({'left':leftPos+'px'}, 'fast');
		_this.genericBackDrop.height(bodyHeight).width(bodyWidth).css( { 'left': scrollLeft + 'px', 'top': scrollTop + 'px' } );
	},
	ajax: function(){
		var _this = this;
	//	mainScripts.ajax('get', '/vgn-ext-templating/your-site/jsp/MagicServlet', 'magic=true&unicorns=5000', true, myCallBackFunction);
	//	_this.isGallery;
		genAjaxCall.go('get', _this.jsp, _this.data, true, lightBox.buildOverlay, _this.panel);
	},
	buildOverlay: function(html, panel, jsp){
		// set countdown to fun!
		var timeDelay = 2000;
		function setContent(){
			var panelBody = panel.find('.panelBody');
			
			/*
			// omniture and panel building
			if( panel.hasClass('panelIsOpen') {
				panel.find('.panelBody').html(html);
			} else if( panel.attr('id') == 'vehiclesPanel' || panel.attr('id') == 'enginesPanel' ) {
				panel.find('.panelBody').html(html);
			}
			*/
			
			panel.find('.panelBody').html(html);
			
		}
		setTimeout(function(){setContent()},timeDelay);
	},
	splitPassedQueryString: function(name, url){
		var urlSearch = url.indexOf('?');
		var query = url.substring(urlSearch + 1);
		var vars = query.split("&");
		for (var i=0;i<vars.length;i++){
			var pair = vars[i].split("=");
			if (pair[0] == name){
				if(pair[1].indexOf("#") != -1){
					var nohash = pair[1].split("#");
					return nohash[0];
				}
				return pair[1];
			}
		}
		return null;
	}
};

$(function() { 
	if(getQueryVariable("valcode") != null) {	
		lightBox.open("portfolio", "", ""); 
	} 
});

$(function() { 
	if(getQueryVariable("novalcode") == "1") {	
		lightBox.open("portfolio", "", ""); 
	} 
});
