var MAX_NAV_HEIGHT = "400";
var MIN_NAV_HEIGHT = "115";
var FLASH_NAV_ID = "flashObj_nav";

var model_locate_dealer = "other";
var lastPosition = {x:0,y:0};

function show(id, root, ignoreList) {
	//console.log("show: "+ id);
	var rootNode = document.getElementById(root);
	if (ignoreList == null) ignoreList = "";
	if (rootNode == null) rootNode = document.body;

	//console.log("hide id: "  +id);

	// hide all other flyouts
	var nodeArr = util.getElementsByClassName('flyout', rootNode);
	for (var i = 0; i < nodeArr.length; i++) {
		var thisId = nodeArr[i].id;
		if ((thisId != null) && (thisId.length > 0)) {
			if ((ignoreList.indexOf(thisId)) == -1 ) {
				//console.log("show - hide: " + nodeArr[i].id);
				css.removeClassName(nodeArr[i], "active");
			}
		} else {
			//console.log("show - hide: " + nodeArr[i].id);
			css.removeClassName(nodeArr[i], "active");
		}

	}

	// show this flyout
	css.addClassName(document.getElementById(id), "active");

}

function hide(id, root, ignoreList) {
	var rootNode = document.getElementById(root);

	if (ignoreList == null) ignoreList = "";
	if (rootNode == null) rootNode = document.body;

	//console.log("hide id: "  +id);

	var nodeArr = util.getElementsByClassName('flyout', rootNode);
	for (var i = 0; i < nodeArr.length; i++) {
		var thisId = nodeArr[i].id;
		if ((thisId != null) && (thisId.length > 0)) {
			if ((ignoreList.indexOf(thisId)) == -1 ) {
				//console.log("hide: " + nodeArr[i].id);
				css.removeClassName(nodeArr[i], "active");
			}
		} else {
			//console.log("hide: " + nodeArr[i].id);
			css.removeClassName(nodeArr[i], "active");
		}

	}
}

//alert("global.siteSpeed="+global.siteSpeed);
if(global.siteSpeed!="high"){
	var req = new Request.HTML({method: 'get', url: BASE_CONTEXT + '/tools/util/navigation.do?success=/en/pages/global/includes/navigation_html.jsp',
		onSuccess: function(html) {
			if ($('mdsNavVehicles') != null) {

				//Clear the text currently inside the results div.
				$('mdsNavVehicles').set('text', '');
				//Inject the new DOM elements into the results div.
				$('mdsNavVehicles').adopt(html);
				//console.log('w00t');

				$$('ul#vehicles li').each(function(li) {
					//console.log(li.id);
					
					if(li.className!="separator"){
					li.addEvent('mouseleave', function() {
						css.removeClassName(li, 'active');
					});

					li.addEvent('mouseenter', function() {
						css.addClassName(li, 'active');
					});
					}
					
				});

			}
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			if ($('mdsNavVehicles') != null) {
				$('mdsNavVehicles').set('text', '');
			}
		}
	});

	$(document).addEvent('domready', function() {

		if ($('mdsNavDivisionVehicles') != null) {
		$('mdsNavDivisionVehicles').addEvent('mouseover', function() {
			css.addClassName($('mdsNavVehicles'), 'active');
		});
		}

		if ($('mdsNavVehicles') != null) {
			$('mdsNavVehicles').addEvent('mouseleave', function() {
				css.removeClassName($('mdsNavVehicles'), 'active');
			});

			req.send();
		}
	});
}
	//Following functions are used by buying guides page.
	function showPaymentEstimator(){
		var postalCode = getPostalCode();
		window.open(BASE_CONTEXT+'/pages/mds/pricing/estimatepayment.do');
	}

	function showTradeInAppraisal(url){//URL is passed from jsp, it is set on brand.properties
		console.log(url);
		//window.open(BASE_CONTEXT+'/pages/misc/instersticial/popupToExteriorLink.do?newURL='+url);
		fireInterstitial('/pages/misc/instersticial/popupToExteriorLink.do?newURL='+url+'');
	}

	function showApplyForCredit(){
		window.open('https://www.gmacfinancialtools.com/toolmanager?toolname=XCA&websiteid=USBP&cntrycd=US&langcd=EN&request_type=credapp');
	}

	function showGMACLearnMore(){
		window.open('http://www.gmacfs.com/us/en/personal/automotive/');
	}

/*--------------------MODEL MENU-------------------------*/
function displayHideYears(objId){
	obj =  document.getElementById(objId);
	if(obj.className == "hiddenArea") obj.className = "displayedArea";
	else obj.className = "hiddenArea";
}
/*--------------------END MODEL MENU-------------------------*/

/*
 * showWorldwideSitesDialog(src)
 * Function to show the "Worldwide Sites" pop-up in the navigation bar
 */
function showWorldwideSitesDialog(src){
	var html = '';
	var url = BASE_CONTEXT+"/en/pages/global/nav/worldWideSites/pageData.xml";
	var xml;
	var data;
	if ($('wsDialog') != null) {
		document.body.removeChild($('wsDialog'));
	}
	var toolTipElm = document.createElement('div');
	toolTipElm.setAttribute('id', 'wsDialog');
	toolTipElm.innerHTML += "<div>"+DIVISION+" Worldwide</div>";
	toolTipElm.innerHTML += "<div><a href='#' onclick='closeWorldWideSitesDialog(this);'>Close</a></div>";
	toolTipElm.innerHTML += "<ul>";
	try{
	    xml = new JKL.ParseXML(url);
	    data = xml.parse();
	    for(var link in data.links.link){
	    	if(data.links.link.hasOwnProperty(link)){
	    		toolTipElm.innerHTML += "<li><a href='"+data.links.link[link].href+"' title='"+data.links.link[link].title+"' target='"+data.links.link[link].target+"' class='"+data.links.link[link].css+"' onclick='"+data.links.link[link].onclick+"'>"+data.links.link[link].text+"</a></li>";
	    	}
	    }
	}catch(err){}
	toolTipElm.innerHTML += "</ul>";
	document.body.appendChild(toolTipElm);
	$('wsDialog').style.left = DL_GetElementLeft(src) + "px";
	$('wsDialog').style.top = DL_GetElementTop(src) + "px";
	return false;
}

/*
 * closeWorldWideSitesDialog()
 * Function to hide the "Worldwide Sites" pop-up in the navigation bar
 */
function closeWorldWideSitesDialog() {
	document.body.removeChild($('wsDialog'));
	return false;
}

function doVL(refId,offsetX,offsetY){
	//setPositionLV (551,0);
	if ( typeof refId == 'undefined' ) refId = 'container';
	if ( typeof offsetX == 'undefined' ) offsetX = 0;
	if ( typeof offsetY == 'undefined' ) offsetY = 0;
	if ( typeof refId == 'string' ) refId = $(refId);
	xOffset = offsetX;
	yOffset = offsetY;
	validateCookie(refId,'locateVehicleLanding()','vl',false);
	return false;
}

function doDL(refId,offsetX,offsetY, model){
	if ( typeof refId == 'undefined' ) refId = 'container';
	if ( typeof offsetX == 'undefined' ) offsetX = 0;
	if ( typeof offsetY == 'undefined' ) offsetY = 0;
	if ( typeof model == 'undefined' ) model = "otro"; // Added by fulvio by ticket 337
	if ( typeof refId == 'string' ) refId = $(refId);
	model_locate_dealer = model; // Added by fulvio by ticket 337
	xOffset = offsetX;
	yOffset = offsetY;
	validateCookie(refId,'locateDealer()','dl',false);
	return false;
}

function doDLOffers(refId,offsetX,offsetY){
	if ( typeof refId == 'undefined' ) refId = 'container';
	if ( typeof offsetX == 'undefined' ) offsetX = 0;
	if ( typeof offsetY == 'undefined' ) offsetY = 0;
	if ( typeof refId == 'string' ) refId = $(refId);
	xOffset = offsetX;
	yOffset = offsetY;
	validateCookie(refId,'locateDealer()','dl',false);
	return false;
}

function doBYO(){
	validateCookie(this,'byo()','byo',false);
	return false;
}

function doAffordability(){
	validateCookie(this,'byo()','byo',false);
	return false;
}

function doDLOfferseft(){
	validateCookie(this,"locateDealerTrack('evar24=bu_off_enclave29for60')",'dl',false);
	return false;
}

function locateDealerTrack(value){
	var postalCode = getPostalCode();
	location.href=BASE_CONTEXT+'/tools/dealerlocator/result.do?BRANDID=bu&searchType=ByPostalCode&desiredCount=25&searchByPostalCodePostalCode='+postalCode+'&'+value;
}

function setFlashNavHeight(newHeight){
	var e1 = document.getElementById(FLASH_NAV_ID);
	e1.height=newHeight;
}

function setFlahsNavHeight(){
  var e1 = document.getElementById(FLASH_NAV_ID);
  if (e1.height===MAX_NAV_HEIGHT){
  	e1.height=MIN_NAV_HEIGHT;
  }
  else{
  	e1.height=MAX_NAV_HEIGHT;
  }
}

function pricingOffer(){
	var zipLoc = mrm.cmp.zc.getLocation();
	if(null!=zipLoc){
		window.location.href=BASE_CONTEXT+"/pages/mds/pricing/affordability.do?zipCode="+zipLoc.zipcode+"&regionCode="+zipLoc.region.code+"&countyCode="+zipLoc.county.code;
	}else{
		window.location.href=BASE_CONTEXT+"/pages/mds/pricing/affordability.do";
	}
}

function popUpWindow(url,winName,attributes) {
  if (attributes.indexOf("directories") == -1) { attributes += ",directories=0"; }
  if (attributes.indexOf("location") == -1) {	attributes += ",location=0"; }
  if (attributes.indexOf("menubar") == -1) { attributes += ",menubar=0"; }
  if (attributes.indexOf("resizable") == -1) { attributes += ",resizable=0"; }
  if (attributes.indexOf("scrollbars") == -1) { attributes += ",scrollbars=1"; }
  if (attributes.indexOf("status") == -1) { attributes += ",status=0"; }
  if (attributes.indexOf("toolbar") == -1) { attributes += ",toolbar=0"; }
  if (attributes.indexOf("top") == -1) { attributes += ",top=80";	}
  if (attributes.indexOf("left") == -1) { attributes += ",left=50"; }
  var newWindow = window.open(url,winName,attributes);
  if (window.focus) { newWindow.focus() }

}



function openByo(year, model){

  location.href=BASE_CONTEXT+'/vehicles/'+ year +'/'+ model +'/build.do';

}

function setPositionByo (x, y){

  temp=navigator.appVersion.split('MSIE');

  ieVer=parseInt(temp[1]);

  if(ieVer == 6){

    yPosition = parseInt(y)-180;

  }else{

    yPosition = y;

  }

  xPosition = x;

}



function setPositionLD (x, y){
  temp=navigator.appVersion.split('MSIE');
  ieVer=parseInt(temp[1]);
  if(ieVer == 6){
    yPosition = parseInt(y)+0;
    xPosition = parseInt(x)+147;
  }else{
    if(ieVer == 7){
      yPosition = y;
      xPosition = parseInt(x)+164;
    }else{
      yPosition = y;
      xPosition = x;
    }
  }
}


function setPositionLV (x, y){
  temp=navigator.appVersion.split('MSIE');
  ieVer=parseInt(temp[1]);
  if(ieVer == 6){
    yPosition = parseInt(y)+0;
    xPosition = parseInt(x)+153;
  }else{
    if(ieVer == 7){
      yPosition = y;
      xPosition = parseInt(x)+169;
    }else{
      yPosition = y;
      xPosition = x;
    }
  }
}


function setPositionHelpMeChoose (x, y){

  temp=navigator.appVersion.split('MSIE');

  ieVer=parseInt(temp[1]);

  if(ieVer == 6){

    yPosition = parseInt(y)-180;

  }else{

    yPosition = y;

  }

  xPosition = x;
}

function fireInterstitial(url){
  var newURL="";
  var context = url.split("/")[1]; // search the context of the url
  var context2 = BASE_CONTEXT.split("/")[1]; // context of the brand site
  if(context!=context2){ // if both context are diferents, append the brand's context to the url
     newURL = BASE_CONTEXT+url;
  }
  else{
     newURL = url;
  }
  newURL=newURL.replace(/&/g,'%26');
  if(Browser.Engine.name == 'trident'){ // fix to IE
     centeredWin(newURL, "interstitialWin", "630", "323", true, false, false, false, false, false, false);//located in common.js
  }else{
     centeredWin(newURL, "interstitialWin", "620", "323", true, false, false, false, false, false, false);//located in common.js
  }
}

function changeImageState(img) {
	if(img != null){
		if(img.src.indexOf('_off.')!=-1){
			var newSrc = img.src.replace("_off.","_on.");
			img.src = newSrc;
		}else if(img.src.indexOf('_on.')!=-1){
			var newSrc = img.src.replace("_on.","_off.");
			img.src = newSrc;
		}
	}
}

function changeYear(year,url) {
	if ($type(window.changeYearOverride) == 'function') {
		// used if a page needs to change the normal behavior of the cahnge year function
		changeYearOverride(year);
	}else{
		window.location = url.split('?')[0];
	}
}

if ( typeof getPositionRelative == 'undefined' ) {
	function getPositionRelative(element) {
		var left = 0;
		var top  = 0;
		var isIElte7 = (BrowserDetect.browser == 'Explorer' && BrowserDetect.version <= 7 );
		if (element){
			do {
				left += element.offsetLeft;
				top += element.offsetTop;
			} while ( element = element.offsetParent );
			if ( isIElte7 ) {
				var bwd = (document.documentElement.clientWidth-document.body.clientWidth)/2;
				left -= bwd;
			}
			lastPosition = {x:left, y:top};
			return {x:left, y:top};
		}else{
			return {x:lastPosition.x-1, y:lastPosition.y-10};
		}
	}
}

