/****************************************
*for iframe crosstalk
*****************************************/
if(window.location.href.indexOf('icbus.com') != -1)
	document.domain = 'icbus.com';

/*****************************************************************************
* global variables
*****************************************************************************/
var curTab = 0;
var numTabs = 0;
var tabName = "";
var promoNum = 0;
var promoPage = "";
var headline = "";
var headlines = "";
var links = "";

/*****************************************************************************
* Cookie Managment
*****************************************************************************/
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);
}


/*****************************************************************************
* 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';
        }
    }
}

/*********************************************************************
*iframe video pop in, copied from Trucks main.js for use on ICBus
**********************************************************************/
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();

/*****************************************************************************
* highlightTab - function for highlighting tabs (i.e. on the product pages)
*****************************************************************************/
function highlightTab( tabNum, bHighlight )
{
    if( tabNum != curTab ){
        tab = document.getElementById( tabName + '_tab' + tabNum );
        tabOver = document.getElementById( tabName + '_tab' + tabNum + '_over' );
        if( bHighlight ){
            tab.className = 'hidden';
            tabOver.className = 'tab';
        }
        else{
            tab.className = 'tab';
            tabOver.className = 'hidden';
        }
    }
}

/*****************************************************************************
* promoRollover - function for showing promo rollovers (i.e. on the home page)
*****************************************************************************/
function promoRollover( promoNum, bShow )
{
    promo = document.getElementById( promoPage + 'Promo' + promoNum );
    promoOver = document.getElementById( promoPage + 'Promo' + promoNum + '_over' );
    if( bShow ){
        promo.className = 'hidden';
        promoOver.className = promoPage + 'Promo_over';
    }
    else{
        promo.className = promoPage + 'Promo';
        promoOver.className = 'hidden';
    }
}

/*****************************************************************************
* showHeadline - function for rotating news headlines on the home page)
*****************************************************************************/
function showHeadline()
{
    headline = document.getElementById( 'a1NewsLink' );
    headline.innerHTML = headlines[ curHeadline ];
    headline.href = links[ curHeadline ];

    curHeadline++;
    if( curHeadline >= headlines.length ) curHeadline = 0;
}




/*****************************************************************************
* imageRollover - function for showing image button rollovers
*****************************************************************************/
	Rollimage = new Array()

	Rollimage[0]= new Image(121,153)
	Rollimage[0].src = "/images/iccorp/BTN_Dealer_OFF.gif"

	Rollimage[1] = new Image(121,153)
	Rollimage[1].src = "/images/iccorp/BTN_Dealer_ON.gif"

	function SwapOut() {
	document.imageRollover.src = Rollimage[1].src;
	return true;
	}

	function SwapBack() {
	document.imageRollover.src = Rollimage[0].src;
	return true;
	}

/*****************************************************************************
* Gallery popup - function for showing popup window in the gallery
*****************************************************************************/

	function popitup(url, pathImg) {
	url = url + "?pathImg=" + pathImg;
	newwindow=window.open(url,'name','height=575, width=780, scrollbars=YES');
	if (window.focus) {newwindow.focus()}
	return false;
}



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;
	}
}


/**********************************************
* Orange Soda Tracking Code
*******************************************/

var cid = 65141;

var amt = 0.00;

var qty = 0;
/* T gets set to 'c' if user is on the dealer locator page */
var t = (document.location.href.indexOf("menuitem.8c4d576c471e02a92ab89001931010a0/?vgnextoid=fee96ba29ad21110VgnVCM10000085d0eb0aRCRD") != -1) ? 'c' : 'h';

var tid = '';


function loadExternalJavascript(url,element)
{
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName(element)[0].appendChild(e);
}

window.onload = function() {
   loadExternalJavascript("http://otracking.com/js/Tracking.js", "body");
}



/*****************************************************************************
* AJAX Request Object Encaspulator - Ratchet
*****************************************************************************/
function getQueryVariable(name) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == name)
			return pair[1];
	}
	
	return null;
}

function getData(nodes) //Use this method when getting data in a CDATA area of an xml file
{
	for(var i = 0; i < nodes.length; i++)
		if(nodes[i].data.length > 0)
			return nodes[i].data;
}


function ajaxObj(url, request_params) {
	var ajax = this;
	this.request_timeout = 15000;
	this.maxRetry = 3;
	this.trys = 0;
	this.timeout = null;
	this.request_onTimeout = function()
	{ 	                            
		if(this.http_request != null && this.http_request.readyState < 4)
		{
			this.http_request.abort();
			clearTimeout(this.timeout);
			if(getQueryVariable("debug") != null)
			{
				if(confirm("A server timeout has occured, would you like to retry?"));
					this.init();
			}
			else
			{
				if(this.maxRetry > this.trys)
					this.init();
				else
					alert("A timeout error has occured, please check your internet connection.");
			}
			
		}
	};

	this.handler_params = new Array();
	this.handler_method = function() { return null; };
	
	this.http_request = null;
	this.xmlDoc = null;
	this.text = null;

	this.init = function()
	{
		this.trys += 1;
		
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			this.http_request = new XMLHttpRequest();

			if(typeof this.http_request.async != "undefined")
				this.http_request.async = true;            

		} else if (window.ActiveXObject) { // IE
		
			try
			{
				this.http_request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
			}
			catch (e)
			{
				try
				{
					this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e)
				{
				}
			}
		}
		else
		{
			alert("Your browser does not support AJAX");
		}
		
		if(this.http_request != null) {
			this.http_request.onreadystatechange = function() // 
			{
				if (ajax.http_request.readyState == 4) {
					clearTimeout(ajax.timeout);
					if (ajax.http_request.status == 200) {
						
						if((ajax.http_request.getResponseHeader("Content-Type") == "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);
			}
		}			
		
		
	};
};



/*****************************************************************************
* 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 state/province -";
				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 = "";
				
				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";
				
				if(t == 0)
					img.src = "/images/minus.gif";
				
				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";
				
				if(t == 0)
					definition.className = "";
				
				definition.innerHTML = getData(terms[t].childNodes);
				
				container.appendChild(definition);
			}
			
			if(document.location.hash.toString() != "")
				showHideTerm(document.location.hash.toString().replace(/\#a_/, ""));

		}
		termRequest.init();
		
	}

getScrollTop = function(){ return (typeof window.pageYOffset=="number")?parseInt(window.pageYOffset):(document.body && document.body.scrollTop)?parseInt(document.body.scrollTop):parseInt(document.documentElement.scrollTop);};
	
/*** ENewsletter Begin ***/
// function to read url querystring variables
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;
}

// automatically open the registration form if the regtype param is present in the querystring
function initSubmitBox()
{
	if(getQueryVariable("regtype") != null)
	{
		emailSubmitBox.open("?" + window.location.href.split("?")[1],"/iccorp/webservices/enewsletter-regtype.jsp");
		$(".enewsEmailSubmitBox").height("580px")
	}
}

function growSubmitBox()
{
	$(".enewsEmailSubmitBox").animate({height: "680px"}, 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,url)
	{
		if(typeof query == "undefined")
			query = "";
		if(typeof url == "undefined")
			url = "/iccorp/webservices/enewsletter.jsp";
		
		url = url + query;
		if(_this.box != null)
		{
			_this.box = null;
		}

		_this.washout = makeElement("div", {cn:"emissionsPopFormBg", style:{height:document.getElementById("all").offsetHeight + "px"}});
		$(".enewsEmailSubmitBox").height("430px");
		_this.box = makeElement("div", {cn:"enewsEmailSubmitBox enewsShortStack"});			
		
		_this.box.appendChild(makeElement("iframe", {src:url,frameborder:0,name:"specFrame",id:"specFrame",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(query)
	{
		if(_this.box){
		_this.box.className = "hidden";
		_this.washout.className = "hidden";
		window.frames["specFrame"].location.href = "about:blank";
		$("#sideFirstName").val("");
		$("#sideLastName").val("");
		$("#sideEmail").val("");
		}
		//window.location.reload();
		else{
		//hack
			if(!query){parent.sideEmailSubmitBox.close("true")};
		}
		
		//hack
	};
}
/*** ENewsletter End ***/


/*****************************************************************************
* 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;
}

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;
        }
    };
}

function donothing(){
// do nothing
}


/*************************************************************
*      Media Pop Up Window
*************************************************************/
var mediaWin;
var mediaContainer;
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;

}		

/*** Reskin Homepage Drop Up Menu ***/
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["buses"] = {name:"buses",elem:null,inited:false,items:new Array()};
	this.data["usages"] = {name:"usages",elem:null,inited:false,items:new Array()};
	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="lowMenus2" style="position:absolute;top:' + $(_this.curMenu.elem).offset().top + 'px; left:0px;"></div>');
			$("#lowMenus2").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>');
					});
				}
			});
			$("#" + _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:"205px"});
				$("#" + _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)	
	{

		if(_this.curMenu != null)
			_this.close();

		_this.curMenu = _this.data[menu];
		_this.curMenu.elem = elem;
		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.parseProductData = 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/ICCorp/menuitem.53a9dd425719dfa92ab89001931010a0/?vgnextoid=3aa77bbafac90110VgnVCM10000085d0eb0aRCRD&applicationID=" + $(this).attr("id"),target:"_self"};
		});
		$(data).find("classes>class").each(function() {
			var idx	= 0;
			var nm = $(this).children("name").text();
			
			$(_this.data["buses"].items).each(function(i) { if(this.title == nm) { idx = i; return false; } });
			
			idx = idx == 0 ? _this.data["buses"].items.length : idx;
			
			if(_this.data["buses"].items[idx] == null)
			{
				_this.data["buses"].items[idx] = {classid:$(this).attr("id"),title:$(this).children("name").text(),subItems:new Array(),link:"javascript:void(0)",target:"_self"};
			}
			else
			{
				_this.data["buses"].items[idx].classid = $(this).attr("id");
			}
			
			$(data).find("truck").each(function()
			{
				if($(this).children("class").text() == _this.data["buses"].items[idx].classid)
				{
					_this.data["buses"].items[idx].subItems[_this.data["buses"].items[idx].subItems.length] = {title:$(this).children("name").text(),link:$(this).children("product_link").text(),target:"_self"};
				}
			});				
		});
		_this.dataLoaded[0] = true;
	};	
	this.loadData = function()
	{
		$.ajax({ url: "/iccorp/busesXMLProvider?type=school", dataType: "xml", success: _this.parseProductData });
		$.ajax({ url: "/iccorp/busesXMLProvider?type=commercial", dataType: "xml", success: _this.parseProductData });
		
		$.ajax({ url: "/iccorp/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;			
		}});
	};
}
var topMenuBox = new function topMenuBoxClass()
{
	var _this = this;	
	var fieldValue; 
	this.data = new Array();
	
	this.data["enews"] = {

		func:function() { 
			if($("#topMenuBoxText").val() == '' || $("#topMenuBoxText").val() == 'Enter E-Mail Address')
			{
				fieldValue = '';
			}
			else
			{
				fieldValue = $("#topMenuBoxText").val();
			}
			emailSubmitBox.open("?email=" + fieldValue); 
			}, emptyBoxText:"Enter E-Mail Address"
	};
	
	this.data["search"] = {func:function() { window.location.href="http://www.icbus.com/portal/site/ICCorp/menuitem.deec84539809ada92ab89001931010a0/?vgnextoid=a3f77bbafac90110VgnVCM10000085d0eb0aRCRD&searchterm=" + $("#topMenuBoxText").val(); }, emptyBoxText:"Search"};
	this.currentBox = null;
	this.boxInited = false;
	this.readyBox = function()
	{
		if($("#topMenuBoxText").val() == _this.currentBox.emptyBoxText)
		{
			$("#topMenuBoxText").css("color", "#000000");
			$("#topMenuBoxText").val("");
		}
	};
	this.checkEmpty = function()	
	{
		if($("#topMenuBoxText").val() == "")
		{
			$("#topMenuBoxText").css("color", "#999999");
			$("#topMenuBoxText").val(_this.currentBox.emptyBoxText);
		}
	};
	this.initBox = function()
	{
		if(!_this.boxInited)
		{
			$("body").append('<div id="topMenuBoxDiv"><input type="text" id="topMenuBoxText" /><a href="javascript:topMenuBox.currentBox.func()"><img src="http://67.192.100.230/images/ic_topmenu_submit.gif" alt="Submit" /></a></div>');
			$("#topMenuBoxText").bind("focus", _this.readyBox);
			$("#topMenuBoxText").bind("blur", _this.checkEmpty);
			_this.boxInited = true;
		}
		return true;
	};
	this.toggle = function(link)
	{
		$(link).parent().siblings(":not(.sep)").each(function() { $(this).attr("class", ""); });
		$(link).parent().siblings(":not(.sep)").each(function() { $(this).data("opened", false); });
		if(!$(link).parent().data("opened"))
		{
		//alert('hello');
			$(link).parent().data("opened", true);
			$(link).parent().attr("class", "on");
			_this.currentBox = _this.data[$(link).attr("id").substr(0, $(link).attr("id").length - 3)];
			if(_this.initBox())
			{
				$("#topMenuBoxText").val(_this.currentBox.emptyBoxText);
				if($("#topMenuBoxDiv").css("display") == "none")
					$("#topMenuBoxDiv").fadeIn(250);
			}
		}
		else
		{
			_this.close();
			$(link).parent().data("opened", false);
			$(link).parent().attr("class", "");
			$(link).blur();
		}
		
		return false;
	};
	this.close = function()
	{
		$("#topMenuBoxDiv").fadeOut(250);
	};	
		
}


var sideEmailSignup = new function sideEmailSignupClass()
{
	var _this = this;	
	
	this.initFieldFocus = function()
	{

		$("#sideFirstName, #sideLastName, #sideEmail").bind('focus', function() 
		{
			var fieldVal = $(this).val() ;
			$(this).css("color", "#000000");
			if (fieldVal == "*First Name" || fieldVal == "*Last Name" || fieldVal == "*Email" || fieldVal == "Please enter a valid e-mail" || fieldVal == "Please enter your first name" || fieldVal == "Please enter your last name") 
			{
				$(this).val("");
			}
		});
		
		$("#sideFirstName, #sideLastName, #sideEmail").bind('blur', function() 
		{
			var fieldVal = $(this).val() ;
			var fieldID =  $(this).attr('id'); 
			if (fieldVal === "") 
			{
				switch(fieldID)
				{
					case "sideFirstName":
						$(this).val("*First Name");
						break;
					case "sideLastName":
						$(this).val("*Last Name");
						break;
					case "sideEmail":
						$(this).val("*Email");
						break;
					default:
						$(this).val("");
				}
				$(this).css("color", "#666666");
				
			}
		});
	}
	
	this.validate = function()
	{

		var required = ["sideFirstName", "sideLastName", "sideEmail"];
		var email = $("#sideEmail");
		var first = $("#sideFirstName");
		var last = $("#sideLastName");
		var intrest = $("#sideBusInterests");
		var errornotice = $("#error");
		var emptyfirst = "Please enter your first name";
		var emptylast = "Please enter your last name";
		var emailerror = "Please enter a valid e-mail";



			if ((first.val() == "*First Name") || (first.val() == "") || (first.val() == emptyfirst)) {
				first.addClass("needsfilled");
				first.val(emptyfirst);
				errornotice.fadeIn(750);
			} else {
				first.removeClass("needsfilled");
			}
			
			if ((last.val() == "*Last Name") || (last.val() == "") || (last.val() == emptylast)) {
				last.addClass("needsfilled");
				last.val(emptylast);
				errornotice.fadeIn(750);
			} else {
				last.removeClass("needsfilled");
			}

		// Validate the e-mail.
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
			email.addClass("needsfilled");
			email.css("color", "#666666");
			email.val(emailerror);
			
		}else{

			email.removeClass("needsfilled");
		}

		//if any inputs on the page have the class 'needsfilled' the form will not submit
		if ($(":input").hasClass("needsfilled")) {
			return false;
		} else {
			errornotice.hide();
			//_this.send();
			var queryString = "?email="+email.val()+"&first="+first.val()+"&last="+last.val()+"&intrestType="+intrest.val();
			
			sideEmailSubmitBox.open(queryString);

			return false;
		}
		
		// Clears any fields in the form when the user clicks on them
		$(":input").focus(function(){		
		   if ($(this).hasClass("needsfilled") ) {
				$(this).val("");
				$(this).removeClass("needsfilled");
		   }
		});
	}


	this.send = function()
	{
		var url = "/iccorp/ICBusEnewsletterProvider";
		var regURL = "http://registrations-staging.icbus.com/e-newsletter/enewsregister.asmx/registerNewsletterEntry";
		//var regURL =  ((document.location.href.indexOf("staging") != -1) || (document.location.href.indexOf("navi-") != -1)) ? 'http://registrations-staging.icbus.com/e-newsletter/enewsregister.asmx/registerNewsletterEntry' :'http://registrations.icbus.com/e-newsletter/enewsregister.asmx/registerNewsletterEntry';
		$.get(url, {
			email: $("#sideEmail").val(), 
			first: $("#sideFirstName").val(), 
			last: $("#sideLastName").val(),
			businterests: $("#sideBusInterests").val(),
			url: regURL
		}, function(data){
			if(data.indexOf("success") >= 0)
			{
				//switchtothankyou();
				alert('Thank you for signing up.');
				return false
			}
			else
			{
				alert('There was an error when making your request.  Please wait a few moments and try again.');
				return false
			}
		});
	}
}
var sideEmailSubmitBox = new function sideEmailSubmitBoxClass()
{
	var _this = this;
	this.box = null;
	this.washout = null;
	this.open = function(query)
	{
		if(typeof query == "undefined")
			query = "";			
		
		var url = "/iccorp/webservices/enewsletter2.jsp" + query;
		if(_this.box != null)
		{
			_this.box = null;
		}

		_this.washout = makeElement("div", {cn:"emissionsPopFormBg", style:{height:document.getElementById("all").offsetHeight + "px"}});
		$(".enewsEmailSubmitBox").height("430px");
		_this.box = makeElement("div", {cn:"enewsEmailSubmitBox enewsShortStack"});			
		
		_this.box.appendChild(makeElement("iframe", {src:url,frameborder:0,name:"specFrame",id:"specFrame",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(query)
	{
		if(_this.box){
		_this.box.className = "hidden";
		_this.washout.className = "hidden";
		window.frames["specFrame"].location.href = "about:blank";
		$("#sideFirstName").val("*First Name");
		$("#sideLastName").val("*Last Name");
		$("#sideEmail").val("*Email");
		$('#sideFirstName, #sideLastName, #sideEmail').css('color', '#666');
		//window.location.reload();
		}
		else{
			if(!query){parent.emailSubmitBox.close("true")};
		}
	};
}



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 href="javascript:seeTheDifferencePopIn.close()">Close</a></div>'
						+ '<iframe src="/ICCorp/SeeTheDifference/' + cmpid + '" width="740" height="506" 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:"526px",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();


var viewIframePop = new function viewIframePopObj()
{

	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() - 500) / 2) + $("body").scrollTop(); };
	this.getL = function() { return ((_this.getW() - 720) / 2); };
	
	this.iframeSize = function(height)
	{
		alert('Hello' + height);
		$('#iframe').height(height);
		$("#seeTheDifferencePopIn").css({height:700});
try {
		$("#seeTheDifferencePopIn").css({height:700});
} catch(e) {
    alert(e);
}

		
	}
	this.adjust = function()
	{

		if(!$.support.cssFloat)
			$("#seeTheDifferencePopIn").css({left:_this.getL()});
		else
			$("#seeTheDifferencePopIn").animate({left:_this.getL()}, 100);
	};

	this.open = function(campaignURL, frWidth, frHeight)
	{
	//alert(campaignURL+' '+frWidth+' '+frHeight);
		if(_this.closed)
		{
			_this.closed = false;
			var divHeight = frHeight+22;
			//var cmpid = (typeof campaign != "undefined") ? "?cmpid=" + campaign : "";
			
			$(window).bind("resize", viewIframePop.adjust);
			$("body").append('<div id="seeTheDifferenceWashout">&nbsp;</div>');
			$("body").append('<div id="seeTheDifferencePopIn">'
						+ '<div style="text-align:right;padding:3px;"><a class="calCloseBtn" href="javascript:viewIframePop.close()"></a></div>'
						+ '<iframe src="' + campaignURL + '" width="'+frWidth+'" height="'+frHeight+'" frameborder="0" scrolling="no" id="iframe"></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:"1px solid #ffffff",top:"30px",left:_this.getL()+"px",width:frWidth+"px",height:divHeight+"px",zIndex:"200",textAlign:"center",backgroundColor:"#000",fontFamily:"arial",fontSize:"12px",color:"black"});		
			$("#seeTheDifferenceWashout").fadeTo(500, .6, function() {
				$("#seeTheDifferencePopIn").fadeTo(500, 1);
			});	
			//var newIframeH = $('#iframe').contents().find('.calWrapper').height();
			//$('#iframe').css('height',newIframeH);
			//console.log(newIframeH);
		}
	};
	this.close = function()
	{
		$("#seeTheDifferencePopIn").fadeTo(500, 0, function() {
			$("#seeTheDifferenceWashout").fadeTo(500, 0, function() 
			{ 
				_this.closed = true; 
				$("#seeTheDifferenceWashout").remove(); 
				$("#seeTheDifferencePopIn").remove(); 
				$(window).unbind("resize", viewIframePop.adjust); 
			});
		});	
	};
}

var configPopOver = new function configPopOverObj()
{	
	var styles = {
		washBgColor: '#000',
		washWidth: '970px',
		washHeight: '2000px',
		washZIndex: '100',
		popOverBorder: '1px solid #ffffff',
		popOverTop: '50',
		popOverLeft: '50',
		popOverZIndex: '200',
		popBgColor: '#000'
	}
	var popOverLeft = ($(window).width() / 2)-(790/2);
	var closed = true;
	
	this.adjust = function()
	{
		popOverLeft =  ($(window).width() / 2)-(790/2);
		$('#popOver').css('left',popOverLeft);
	}
	
	this.open = function()
	{
		if(closed)
		{
			this.closed = false;	
			$(window).bind("resize", this.adjust);
			$('body').append('<div id="popOverWash">&nbsp;</div>');
			$("body").append('<div id="popOver"><div></div></div>');
			//CLOSE BTN HTML<a class="calCloseBtn" onClick="configPopOver.close()"></a>
			$('#popOverWash, #popOver').css({'position' : 'absolute', 'opacity' : '0', 'filter' : 'alpha(opacity=0)'});
			$('#popOverWash').css({'background-color' : styles.washBgColor, 'width' : styles.washWidth, 'height' : styles.washHeight, 'zIndex' : styles.washZIndex});
			$('#popOver').css({'border' : styles.popOverBorder, 'top' : getScrollTop()+50, 'left' : popOverLeft , 'z-index' : styles.popOverZIndex, 'background-color' : styles.popBgColor});
		
			$("#popOverWash").fadeTo(500, .6, function() {
				$("#popOver").fadeTo(500, 1);
			});	
			this.adjust();
			this.addFlash();
		}
	}
	this.addFlash = function()
	{
		$('#popOver').append('<div id="configFlash"></div>');
		var so = new SWFObject("/iccorp/includes/ICBusConfigurator.swf", "home", "790", "475", "9");
		so.addParam("allowScriptAccess", "always");
		so.addParam("wmode", "transparent");
		so.write('configFlash');
	}
	this.close = function()
	{
		$("#popOverWash, #popOver").remove(); 
		$(window).unbind("resize", this.adjust); 
		closed = true;
	}
	
}





$(function() { if(getQueryVariable("seethedifference") != null) { seeTheDifferencePopIn.open(getQueryVariable("seethedifference")); } });

$.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();
	});
};

function trackHomePromo(url, p, target)
{
	var pos = new Array();
	// Campaing Code Associations for IC Bus
	pos["p1m"] = "28"; // Home Promotion Position 1 Main Link 
	pos["p2m"] = "29"; // Home Promotion Position 2 Main Link 
	pos["p3m"] = "30"; // Home Promotion Position 3 Main Link 
	pos["p4m"] = "31"; // Home Promotion Position 4 Main Link 
	pos["p1t"] = "32"; // Home Promotion Position 1 Thumb Link
	pos["p2t"] = "33"; // Home Promotion Position 2 Thumb Link
	pos["p3t"] = "34"; // Home Promotion Position 3 Thumb Link
	pos["p4t"] = "35"; // Home Promotion Position 4 Thumb Link
	
	if(url != 'configPopOver.open()'){
		if(target != "_script")
			url = (url.indexOf("?") != -1) ? url + "&cmpid=" + pos[p] : url + "?cmpid=" + pos[p];
		
		switch(target)
		{
			case "_blank":
				window.open(url);
				break;
			case "_none":
				break;
			case "_script":
				eval(url + "(" + pos[p] + ")");
				break;
			default:
				document.location.href = url;
				break;
		}
	}
	else
	{
		configPopOver.open();
	}
	

	


	return false;
}

function hasSeenIntro()
{
	if(readCookie("hasSeenIntro") != null)
		return "true";
		
	createCookie("hasSeenIntro", "true");
	
	return "false";
}

if(getQueryVariable("seethedifference") != null)
{
	hasSeenIntro();
}

$(function() {
	$("a:contains(®), p:contains(®), h4:contains(®)").each(function()
	{
		$(this).html($(this).html().replace(/®/g, '<sup>&reg;</sup>'));
	});
});

/**********************************************
* Add a bookmark link to anypage with this function
*******************************************/

function addBookmark(title,url)
{
	if(typeof url == "undefined")
		url = window.location.href;

	if(typeof title == "undefined")
		title = window.document.title;

	if (window.sidebar) // firefox
	{
		window.sidebar.addPanel(title, url, "");
	}
	else if(window.opera && window.print) // opera
	{
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if(document.all)// ie
	{
		window.external.AddFavorite(url, title);
	}
}



/**********************************************
* 2010 Emissions Updates Form
*******************************************/


var mediaWin;
function showMediaPop(name,w,h,noClose)
{
	if(mediaWin != null)
		mediaWin.close();
		
	
	if(typeof noClose == "undefined")
		h += 40;

	mediaWin = window.open("/trucks/mailer/flash/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();

	return false;
}

function getData(nodes) //Use this method when getting data in a CDATA area of an xml file
{
	for(var i = 0; i < nodes.length; i++)
		if(nodes[i].data.length > 0)
			return nodes[i].data;
}

var requestTimeout = 10000; // All requests made by the ajax object will share this timeout (in milliseconds)

var xmlDocCache = new Array();

function getXMLDocument(xmlSource, cache)
{
    if(typeof cache == "undefined")
        cache = true;
    
    if(typeof xmlDocCache[xmlSource] != "undefined")
        return xmlDocCache[xmlSource];

    if (window.ActiveXObject)
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    else if (document.implementation && document.implementation.createDocument)
        var xmlDoc = document.implementation.createDocument("","",null);

    if (typeof xmlDoc != "undefined")
    {
        xmlDoc.async = false;
        xmlDoc.load(xmlSource);
        ratchet.trace(xmlSource);
		if(cache)
			xmlDocCache[xmlSource] = xmlDoc;
			
		return xmlDoc;        
    }
    else
    {
        return null;
    }
}

function ajaxObjTwo() {
    this.http_request = null;
    this.init_httpreq = function()
    {
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            this.http_request = new XMLHttpRequest();

            if (this.http_request.overrideMimeType)
                this.http_request.overrideMimeType('application/xml');
                
            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)
                {
                }
            }
        }
    };
    this.request_timeout = requestTimeout;
    this.timeout = null;
    this.request_onTimeout = function() { return null; };
    this.handler_method = function() { return null; };
    this.handler_params = new Array();
    this.setParams = function(array) // Use when defining an array of parameters for your custom handler method.
    {
        this.handler_params = array;
    };
    this.handler_divId = null;
    this.message = null;
    this.make_httpreq = function(url, parameters, divId, msg)
    {
        this.handler_divId = divId;
        this.message = (typeof msg != "undefined") ? msg : "loading...";
        this.init_httpreq();
        if(this.http_request != null) {
            var geoJax = this;
            this.http_request.onreadystatechange = function()
            {
                if (geoJax.http_request.readyState == 4 && geoJax.http_request.status != null) {
                    clearTimeout(geoJax.timeout);
                    if (geoJax.http_request.status == 200) {
                        if(geoJax.message != "xml")
                        {
                            var responseDoc = geoJax.http_request.responseXML;
                            var response = responseDoc.documentElement.childNodes[0].nodeValue;//(is_ie) ? responseDoc.documentElement.nodeValue : responseDoc.documentElement.textContent;
                            if (response != null && response.length > 0)
                                getElement(geoJax.handler_divId, true).innerHTML = response;
                        }
                        geoJax.handler_method();
                        geoJax.http_request = null;
                    } else if (geoJax.http_request.status != 0) {
                        /* alerts with exception on bad request */
						alert("Server Error " + geoJax.http_request.status);
                    }
                } else {
                    if(geoJax.message != "xml")
                        getElement(geoJax.handler_divId, true).innerHTML = geoJax.message;
                        
                    if (geoJax.http_request.readyState == 1) {
                        geoJax.request_onTimeout = function()
                        {
                            if(geoJax.http_request != null && geoJax.http_request.readyState < 4)
                            {
                                geoJax.http_request.abort();
                                //getElement(geoJax.handler_divId, true).innerHTML = "request timed out, try again"; 
                                clearTimeout(geoJax.timeout);
                            }
                        };
                        geoJax.timeout = setTimeout(geoJax.request_onTimeout, geoJax.request_timeout);
                    }
                }
            };
            
            if (parameters == 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", parameters.length);
                this.http_request.setRequestHeader("Connection", "close");
                this.http_request.send(parameters);
            }
        }
    };
};


 function checkItem(item, msg, regex) {
        var value = "";
        var type = "r";

        if(typeof item.type != "undefined")
            type = item.type.toLowerCase().substr(0,1);

        switch (type)
        {
            case "r": // Radio Button
                for(var r = 0; r < item.length; r++)
                {
                    if(item[r].checked)
                    {
                        value = item[r].value;
                        break;
                    }
                }
                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 : "";
        }   

        var submitted = false;

        function register()
        {
        if(!submitted)
        {
            var form = document.emissionsReg;
            
            // Do some validation
            var errors = "";

            //errors += checkItem(form.firstname, "First Name");
            //errors += checkItem(form.lastname, "Last Name");
            //errors += checkItem(form.companyname, "Company Name");
            //errors += checkItem(form.address1, "Address 1");
            //errors += checkItem(form.city, "City");
            //errors += checkItem(form.state, "State/Province");
            //errors += checkItem(form.zip, "a valid Postal Code");
            errors += checkItem(form.email, "a valid Email", /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/);
            errors += checkItem(form.businterests, "Company Type");
            
            var params = "";


            
            var elems = form.elements;
            
            for(var e = 0; e < elems.length; e++)
            {
                switch (elems[e].type.toLowerCase().substr(0,1))
                {
                    case "r": // Radio Buttons
                        if(elems[e].checked)
                            params += "&" + elems[e].name + "=" + escape(elems[e].value);
                        break;
                    case "c": // Checkboxes
                        if(elems[e].checked)
                            params += "&" + elems[e].name + "=" + "checked";                            
                        break;
                    case "s": // Select boxes                   
                        if(elems[e].options[elems[e].selectedIndex].value.length > 0)
                            params += "&" + elems[e].name + "=" + escape(elems[e].options[elems[e].selectedIndex].value);                           
                        break;
                    case "t": // Textboxes or Textareas
                        if(elems[e].value.length > 0)
                            params += "&" + elems[e].name + "=" + escape(elems[e].value);
                        break;
                }
            }
            params += (document.location.href.indexOf("www.") != -1) ? '&url=http://registrations.icbus.com/genreg/registerbasic.aspx' : '&url=http://registrations-staging.icbus.com/genreg/registerbasic.aspx';
            //alert(params);
            //alert(params.replace(/&/g, "\n"));
            
            if(errors.length != 0)
            {
                alert("You may not register until the following issues have been resolved:\n" + errors);
            }
            else
            {
                
                
                params = "typeid=2010EmissionsRegistrationIC" + params;

                submitted = true;
                
                document.getElementById("sub").className = "hide";
                
                var ajaxianSubmit = new ajaxObjTwo();
                ajaxianSubmit.handler_method = function() {
                    alert("Thank You");
                    //window.top.location.href = "http://www.icbus.com/2010Emissions";
					emissionsPopOver.closeForm();
                };
                
                ajaxianSubmit.make_httpreq('/iccorp/genericregistrationwrapper/', params, "", "xml");
            }
        }
        }

/**********************************************
* END 2010 Emissions Updates Form
*******************************************/


function initIEFix()
{
if($.browser.msie){

      $(':contains("<!--[if lte IE7]>")').remove();
		$(':contains("<![endif]-->")').remove();
}

}

function initNav() {

	/* setup the width for wider content */
    var widthLiElems = $('#mainHeader .menus li:not(#mainHeader .menus li ul li)');
	var tempWidth;
	var setWidth;

	//var test = '';
    widthLiElems.each(function(i){
		var liElems = $(widthLiElems[i]).children('ul').children('li');
		setWidth = false;
		tempWidth = $(widthLiElems[i]).width();
		var curLiWidth = 0;
		liElems.each(function(x) {
			curLiWidth = $(liElems[x]).children('a').outerWidth() + ($(liElems[x]).outerWidth() - $(liElems[x]).width());
			if ( curLiWidth > tempWidth ) {
				setWidth = true;
				tempWidth = curLiWidth;
			}
		});

		if ( setWidth == true ) {
			$(widthLiElems[i]).children('ul').css('width', tempWidth + 'px');
		}

	});

}

function initBusLanding()
{
	//$('.buses .appTitle').data('width', $(this).width);
	$(window).scroll(function(e) {
		//console.log($(window).scrollTop())
		if ($(window).scrollTop() >= $('.buses .appTitle').offset().top && ($('.buses .appTitle').offset().top >= $('.buses').offset().top) ) {
				//console.log("got here 1");
			//$('.buses .appTitle').css('width', "232px");
			$('.buses .appTitle').addClass('freeze');

							//console.log("got here 1");
		} else {
						//console.log("got here 2");
			//$('.buses .appTitle').css('width', 'inherit');
			$('.buses .appTitle').removeClass('freeze');
		}
	});
}

function initRecommendedModels()
{
	var url = window.location.search;
	//if ( url.match(/vgnextnoice=1/) != null )
	//{
	//	$('.recommendedModels').remove().replaceAll('.recommendedModelsPlaceholder');
	//}
}

function initDropdown()
{
	
	if (window.ActiveXObject)
	{ // IE	
		$(".mainMenu ul li.headlink ").hover(function () {
			$(".menus li.headlink ul").css('display','block');
			}, 
		function () {
			$(".menus li ul").css('display','none');
		});
	}
}

function init(e)
{

	initDropdown();
	initNav();
	initRecommendedModels();
	initBusLanding();
	sideEmailSignup.initFieldFocus();
	initIEFix();
	initSubmitBox();
}



$(init);

/*****************************************************************************
* open configurator on page load
*****************************************************************************/
$(function() {
	if(getQueryVariable("openConfig") != null) { 
		configPopOver.open();
	}
});