var thisLoc = location.toString();

// SH - July 20008 - managing [Outside + TON] links for Dealer view, we want a new broswer for dealer view only, the rest will open in the same page.
function openLink(url){
	var dealerStyleIdCoockie="";
	try { dealerStyleIdCoockie=getCookie("dealerStyleId");}
	catch (e) { location.href=url; }
	if(dealerStyleIdCoockie="" || dealerStyleIdCoockie == null) {
		location.href=url;
	} else { //we're now in dealer-view
		var theDomain = 'http://' + thisLoc.split('/')[2];	
		if (url.indexOf('/gm/') != -1 && url.indexOf('http://') == -1) { //manage internal links
			var myserver;
			if (thisLoc.indexOf('preprod-pnt.') != -1){
				myserver = 'http://preprod-pnt.gm.ca';
			}	
			else if (thisLoc.indexOf('dit.tech.') != -1){
				myserver = 'http://dit.tech.mminteractive.com';
			}
			else if (thisLoc.indexOf('www-wrn.') != -1){
				myserver = 'http://www-wrn.gm.ca';
			}
			else if (thisLoc.indexOf('preprod.preview.') != -1){
				myserver = 'http://preprod.preview.tech.mminteractive.com';
			}
			else if (thisLoc.indexOf('itl.') != -1) { // we are on ITL
				myserver = 'http://itl.gm.ca';
			} else if (thisLoc.indexOf('preprod.') != -1) { // we are on PREPROD
				myserver = 'http://preprod.gm.ca';
			} else if (thisLoc.indexOf('localhost') != -1) { // we are on localhost
				myserver = 'http://localhost';
			} else { // default to LIVE
				myserver = 'http://www.gm.ca';
			}
			//alert("server is: "+myserver + "  url is: " +url);
			openBrowserWin(myserver+url);
		}else{
			openBrowserWin(url);
		}
	}
}

//Khalid - Open a new browser Window - could be used for badges - Jan 17/2008 (Malibu contest example)
function openBrowserWin(url) {

            var w = screen.width;
            var h = screen.height;
            if (!ie5 && !ns && isMac) { h += 18; }
            win= window.open(url,'newbrowserwin', 'width=' + w + ',height=' + h +',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');

            if (win.opener == null) win.opener = self;
            win.focus();
            moveToTop();
}
function moveToTop() {
            window.screenX = 0;
            window.screenY = 0;
            alwaysLowered = false;
}
//Sirine Apr 2007 - When you go from https//: like an SRD back to static content, the https:// stays and thus you get alerts in IE7.
function unsecureLink(url) {
	var thisLoc = location.toString();
	var theDomain = 'http://' + thisLoc.split('/')[2];
	
	var server;
		if (thisLoc.indexOf('pnt.') != -1 || 
			thisLoc.indexOf('itl001.') != -1){
			server = theDomain;
			PEDomain = 'http://paymentestimator.autodata.preprod.gm.ca';		
		}		
		else if (thisLoc.indexOf('itl.preview.') != -1){
			server = 'http://itl.preview.tech.mminteractive.com';
			PEDomain = 'http://paymentestimator.autodata.preprod.gm.ca';	
		}
		else if (thisLoc.indexOf('preprod.preview.') != -1){
			server = 'http://preprod.preview.tech.mminteractive.com';
			PEDomain = 'http://paymentestimator.autodata.preprod.gm.ca';	
		}	
		else if (thisLoc.indexOf('itl.') != -1) { // we are on ITL
			server = 'http://itl.gm.ca';
			PEDomain = 'http://paymentestimator.autodata.preprod.gm.ca';	
		} else if (thisLoc.indexOf('preprod.') != -1) { // we are on PREPROD
			server = 'http://preprod.gm.ca';
			PEDomain = 'http://paymentestimator.autodata.preprod.gm.ca';	
		} else if (thisLoc.indexOf('localhost') != -1) { // we are on localhost
			server = 'http://localhost';
			PEDomain = 'http://paymentestimator.autodata.preprod.gm.ca';	
		}else if (thisLoc.indexOf('www-wrn.') != -1) {
			server = 'http://www-wrn.gm.ca';
			PEDomain = 'http://paymentestimator.autodata.gm.ca';
		}else { // default to LIVE
			server = 'http://gm.ca';
			PEDomain = 'http://paymentestimator.autodata.gm.ca';	
		}
	document.location=server+url;
}


//Sirine July 18/06 - Payment Estimator link, goes to Autodata carrying a list of parameters
function estimator(){
	var returnToURL = escape(document.location.href); //current location
	var returnToName = escape(sectionDisplayTitle); //New node in all corporate content files
	
	//Finding the language in Live or preview mode
	var lang="";
	var thisURL = location.toString();
	
	if ((thisURL.indexOf('/english') != -1) || (thisURL.indexOf('en_CA') != -1)) { 
		lang = "en";
	}
	else if ((thisURL.indexOf('/french') != -1)|| (thisURL.indexOf('fr_CA') != -1)) {
		lang = "fr";
	}
	else {
		lang = "en";
	}
	
	unsecureLink(thisURL);
	
	//Constracting the new path
	var estimatorLink = PEDomain+"/GMCanadaPaymentEstimator/paymentEstimatorContainer.html?lang="+lang+"&model=&package=&brand=&year=&returnToName="+returnToName +"&returnToURL="+returnToURL;
	
	//redirecting to the estimator link
	document.location=estimatorLink;
}




function switchLang () {
	engDelimiter = 'english';
	freDelimiter = 'french';
	newURL = switchLangSearch(engDelimiter, freDelimiter);
	if (newURL != 'null') {
		self.location = newURL;
		return;
	}
	engDelimiter = "lang=en";
	freDelimeter = "lang=fr";
	newURL = switchLangSearch(engDelimiter, freDelimeter);
	if (newURL != 'null') {
		self.location = newURL;
		return;
	}
	engDelimiter = "_code=en";
	freDelimeter = "_code=fr";
	newURL = switchLangSearch(engDelimiter, freDelimeter);
	if (newURL != 'null') {
		self.location = newURL;
		return;
	}
}



function switchLangSearch (engDelim, freDelim) {
	docURL = document.URL;
	newURL = 'null';
	engPosition = 0;
	frePosition = 0;
	charStart = 0;
	charEnd = docURL.length + 1;
	engDelimiter = engDelim;
	freDelimiter = freDelim;
	do {
		var test = docURL.substr(charStart, engDelimiter.length);
		if (test == engDelimiter) { engPosition = charStart;}
		charStart++;
	}
	while (charStart < charEnd - engDelimiter.length);
	if (engPosition > 0) {
		// english detected - switch to french
		newURL = docURL.substr(0,engPosition) + freDelimiter + docURL.substr((engPosition + engDelimiter.length),docURL.length);
		// set cookie (kn Oct 2004)
		deleteCookie("weblanguage", "/");
		setCookie("weblanguage","fr", "", "/");
	} else {
		charStart = 0;
		do {
			var test = docURL.substr(charStart, freDelimiter.length)
			if (test == freDelimiter) { frePosition = charStart;}
			charStart++;
		}
		while (charStart < charEnd - freDelimiter.length);
		if (frePosition > 0) {
			// french detected - switch to english
			newURL = docURL.substr(0,frePosition) + engDelimiter + docURL.substr((frePosition + freDelimiter.length),docURL.length);
			// set cookie (kn Oct 2004)
			deleteCookie("weblanguage", "/");
			setCookie("weblanguage","en", "", "/");
		}
	}
	return newURL;
}

//*** Universal Reference ***//
function getRef(id) {
		return (document.getElementById ? document.getElementById(id) : document.all[id]);
}


//*** COOOKIE STUFF *****//

// Write a cookie value
function setCookie(name, value, expires, path, domain, secure) {
	domain = location.toString();
	if (domain.indexOf('.gm.ca') != -1){
		if(navigator.appName.indexOf('Microsoft') != -1){
			domain = "";
		}
		else{
			domain = ".gm.ca";
		}
	}
	else if(domain.indexOf('.mminteractive.com') != -1){
		if(navigator.appName.indexOf('Microsoft') != -1)
			domain = "";
		else{
			domain = ".mminteractive.com";
		}
	}
	else{
		domain ="";
	}
	var curCookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
	document.cookie = curCookie;
}

// Retrieve a named cookie value
function getCookie(name) {
	// There is something very flakey with this function. Probably explains why at some unknown time some unknown person created the function get_cookie to be found later in this file.  Why they didn't document this decision makes baby Jesus cry. It cost me a couple of hours of work but that is besides the point.  I'm not trashing this function because I think it does work in certain contexts and is probably being used, but it doesn't seem to function predictably. I wouldn't use it if I were you. <3 JRB
	// I think I have fixed this flakeyness, seems fine now - PJ
	
	var dc = document.cookie;

	// find beginning of cookie value in document.cookie
	var prefix = name + "=";
	
	var begin = dc.indexOf("; " + prefix);
	//alert(begin);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else begin += 2;

	// find end of cookie value
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;

	// return cookie value
	return unescape(dc.substring(begin + prefix.length, end));
}

// Delete a named cookie value
function deleteCookie(name, path, domain) {
	var value = getCookie(name);
	if (value != null) document.cookie = name + '=' + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
	return value;
}

// Test for cookie support
function supportsCookies(rootPath) {
   setCookie('checking_for_cookie_support', 'testing123', '', (rootPath != null ? rootPath : ''));
   if (getCookie('checking_for_cookie_support')) return true;
   else return false;
}
//*** end COOOKIE STUFF *****//


// Pop-up

	var ie5 = (document.all && document.getElementbyID) ? false : true;
	var isMac = (navigator.appVersion.indexOf("Mac") == -1) ? false : true;
	var win, win2;

	function openWin(url, popWidth, popHeight, popScroll, popStatus, popWin) {
		var winName =  "popup";
		// popWin is a new optional parameter; for backwards compatibility popStatus MUST be
		// specified if popWin is to be used - ppoles 12/24/02
		if (popWin != null)
		{
			winName = popWin;
		}
		// popStatus is a new parameter; it is optional so that old calls will not cause an error
		var statusBar = popScroll;

		if (popStatus != null) {
			statusBar  = popStatus;
			// 'fix' for Mac IE's problem when including a status bar in the pop up window
			// - the browser chops off the bottom 18 pixels of the window to accomodate for the
			//   the status bar, and so we add 18 pixels to the height
			if (!ie5 && !ns && isMac) { popHeight += 18; }
		}

//	    if(win) {
//			if(!win.closed) {
//				if(win.name == "popup") winName = "popup2";
//			  	win.close();
//			}
//			win = null;
//		}

		win=window.open(url, winName, 'width=' + popWidth + ',height=' + popHeight + ',screenX=25,screenY=150,left=25,top=150,scrollbars=' + popScroll + ',resize=no,status=' + statusBar + '');

		if (win.opener == null) win.opener = self;
		win.focus();
	}

// end of pop-up

// function for email page icon, uses escape method to trap multiple instances of ?
var divCode = '';

function pageTAF() {
	var url = escape(document.location.href);
	var dotdo = url.indexOf(".do")
	if (dotdo >= 0 && (document.referrer&&document.referrer!="")) {
		// TAF location must be based on referrer 
		if (document.referrer.indexOf(".do") >= 0)
		{
			url = get_cookie("dotdoref");
			document.location = "/gm/taf.do?div=" + divCode;
		}
		else {
			setCookie('dotdoref', document.referrer, '', '/');
			document.location = "/gm/taf.do?div=" + divCode;
		}
	}
	else {
		deleteCookie("dotdoref");
		document.location = "/gm/taf.do?div=" + divCode;
	}
}



function ParseQueryString(searchStr) {
	var tempStr = window.location.search;
    var startOfString = tempStr.indexOf(searchStr);
    var result = "";
    if (startOfString != -1) {
    	var endOfString = tempStr.indexOf("&",startOfString+searchStr.length+1);
       	if (endOfString != -1) {
           	result = tempStr.substring(startOfString+searchStr.length+1, endOfString);
    	}
    	else {
    		result = tempStr.substring(startOfString+searchStr.length+1, tempStr.length);
    	}
    }
	return result;
}


// generic show/hide methods (from 2004)
var prefix, suffix, layerName, xPos; 			// globals for bookmark layer methods, timer
var bm_showing = false;
var bm_count = 0;

if (document.getElementById) {					// constructor for DOM
	prefix = "document.getElementById('";
	suffix = "').style";
} else if (document.layers) {
	prefix = 'document.layers[\"';
	suffix = '\"]';
	left = '.left';
} else {
	prefix = 'document.all[\"';
	suffix = '\"].style';
	left = '.pixelLeft';
}

function gen_show (myLayer) {
	eval(prefix + myLayer + suffix + '.visibility = "visible"');
}

function gen_hide (myLayer) {
	eval(prefix + myLayer + suffix + '.visibility = "hidden"');
}
function get_cookie(Name) {
		var search = Name + "="
  		var returnvalue = "";
  		if (document.cookie.length > 0) {
		    offset = document.cookie.indexOf(search)
		    // if cookie exists
		    if (offset != -1) { 
		      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 appendPostal(id) {
	var postal="";
	var cookieString=get_cookie('pc');
	postal=cookieString;
	//we pass a different name value pair for the dealer
	if(id=='dealer'){
		document.getElementById(id).href=document.getElementById(id).href+"&inputPostalCode="+postal;
	}
	else{
		document.getElementById(id).href=document.getElementById(id).href+"&POSTLCD="+postal;
	}
}



/* Golbal Sound On/Off Toggle code - Keep this code next to "Eolas Patent Workaround" (below) for congruity - PJ */
// vars
var soundState;
// global function to toggle flash sound off/on
// is only remembered for current session
function toggleGmSound()
{
	if (supportsCookies() == true)
	{
		if (getCookie('gmSoundOn') == 'true')
		{
			setCookie('gmSoundOn', 'false', '', '/', '', '');
		} else {
			setCookie('gmSoundOn', 'true', '', '/', '', '');
		}
	}
}
// code to determine what value to give to the Flash to set the sound to prior to loading the Flash - see code below
if (supportsCookies() == true)
{
	if (getCookie('gmSoundOn'))
	{
		if (getCookie('gmSoundOn') == 'false') soundState = 'true';
		else if (getCookie('gmSoundOn') == 'true') soundState = 'false';
	}
}


/* Eolas Patent Workaround */
 // changes were made to this script to tie it into the Global Sound on/off toggle - October 19, 2007 - see above script - PJ
function CreateControl (divID, objID, url, w, h , wmode, vers, qual, bg, noFlashStr) {
	wmode = (wmode=='') ? '':'<param name="wmode" value="' + wmode + '" />';
	vers = (vers=='') ? '':'<param name="version" value="' + vers + '" />';
	qual = (qual=='') ? '':'<param name="quality" value="' + qual + '" />';
	bg = (bg=='') ? '':'<param name="bgcolor" value="' + bg + '" />';
	allowScriptAccess = '<param name="allowScriptAccess" value="always" />';
	allowFullScreen = '<param name="allowFullScreen" value="true" />';
	
	re = new RegExp('swf\?');
	gmSoundPrefix = '&';
	if (!re.test(url)) gmSoundPrefix = '?'; // determine if there are params in the swf path and if not, put a ? instead of an & in front of the 'gmSound' param

	soundToggle = 'true';
	if (soundState == 'false') soundToggle = 'false'; // var 'soundState' taken from Sound Toggle code above
	
  var d = document.getElementById(divID);
  var als = 'allowScriptAccess = "always"'
  d.innerHTML = 
    '<object id="'+objID+'" type="application/x-shockwave-flash"  data="'+url+gmSoundPrefix+'gmSound='+soundToggle+'" width="'+w+'" height="'+ h + ' allowScriptAccess = "always" + allowFullScreen "true" >' +
		'<param name="movie" value="'+url+gmSoundPrefix+'&gmSound='+soundToggle+'" />' +
		wmode + vers + qual + bg + allowScriptAccess + allowFullScreen +
		noFlashStr + '</object>'; // modified to support the global Sound toggle
}

function emailDialog(lang) {	
	// Language variables
	var dialogTitle = (lang == "english") ? "Email a Friend" : "Dites-le &#xE0; un ami";
	var errorEmailMsg = (lang == "english") ? "Invalid email address" : "Addresse courriel invalide";
	var errorReqMsg = (lang == "english") ? "This field is required" : "Champ obligatoire";
	//Captcha Input
	var captchaMessageInput = "<input type=\"text\" id=\"captcha-response\" name=\"j_captcha_response\">";
	$("body").append("<div id=\"dialog\" title=\"" + dialogTitle + "\"></div>");
	$.ui.dialog.defaults.bgiframe = true;
	$(function() {
		$.ajax({
			url: "email-form",
			cache: false,
			success: function(html){
				
				$("#dialog").append(html);
				$('#emailReturnMsgSuccess').hide();
				$('#emailReturnMsgFail').hide();
				//Force Reload JCaptcha Image
				d = new Date();
			    $("#captcha").attr("src", "/gm/jcaptcha?"+d.getTime());
				$("#dialog").dialog({ 
					buttons: {
						"Send": function() { $("#EmailForm").submit(); },
						"Cancel": function() { $(this).dialog("close"); }
					},
					close: function(event, ui) {
						$("#dialog").remove(); // remove dom elements upon closing the dialog
					},
					modal:true, 
					width:700,
					zIndex:9999
				});
				if(lang == "french") { // 
					$('#dialog').dialog('option', 'buttons', { 
						"Envoyer": function() { $("#EmailForm").submit(); },
						"Annuler": function() { $(this).dialog("close"); }
					});	
				}
				$("#EmailForm").validate({
					messages: {
						from_name: { required: errorReqMsg },
						to_email_1: { email: errorEmailMsg, required: errorReqMsg },
						to_email_2: { email: errorEmailMsg },
						to_email_3: { email: errorEmailMsg },
						to_email_4: { email: errorEmailMsg }
					},
					submitHandler: function(html) {
						$.ajax({
							type: "GET",
							data: "from_name=" + $("#from_name").val() + "&j_captcha_response=" + $("#captcha-response").val() + "&to_email_1=" + $("#to_email_1").val() + "&to_email_2=" + $("#to_email_2").val() + "&to_email_3=" + $("#to_email_3").val() + "&to_email_4=" + $("#to_email_4").val() + "&url=" + location.href,
							url: "/gm/"+lang+"/sendemail",
							dataType: "html",
							success: function(data, textStatus) {
							//it could be other way to check return value
							if(data.length>10&&data.length<50)
							{
								//Force Reload JCaptcha Image
							   d = new Date();
							   $("#captcha").attr("src", "/gm/jcaptcha?"+d.getTime());
                               //Empty input value and other error message							   
							   $("#captchaMessage").html(captchaMessageInput);
							   //Add new error message
							   $("#captchaMessage").append(data).css("color", "red");
							}
								
							else{	
								$("#EmailForm").hide();
								$("#dialog").dialog('destroy');
								$('#emailReturnMsgSuccess').show();
								$("#dialog").dialog({
									buttons: {
										"OK": function() { $(this).dialog("close"); }
									},
									close: function(event, ui) {
										$("#dialog").remove(); // remove dom elements upon closing the dialog
									},
									modal:true,
									zIndex:1500000
								});}
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								$("#EmailForm").hide();
								$("#dialog").dialog('destroy');
								$('#emailReturnMsgFail').hide();
								$("#dialog").dialog({
									buttons: {
										"OK": function() { $(this).dialog("close"); }
									},
									close: function(event, ui) {
										$("#dialog").remove(); // remove dom elements upon closing the dialog
									},
									modal:true,
									zIndex:1500000
								});
							}
						});
					}
				});
			}
		}); 
	});
}

function ChangeFlashcontent () {
	document.getElementById("flashcontent").innerHTML='<object id="flashObj" width="320" height="240" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,47,0"><param name="movie" value="http://c.brightcove.com/services/viewer/federated_f9?isVid=1&isUI=1" /><param name="bgcolor" value="#FFFFFF" /><param name="flashVars" value="videoId=1107842657001&playerID=61626370001&playerKey=AQ~~,AAAAAF4Psd4~,gwfEf1kv0CYvSVFaJAwrn9QDKzDrJZMY&domain=embed&dynamicStreaming=true" /><param name="base" value="http://admin.brightcove.com" /><param name="seamlesstabbing" value="false" /><param name="allowFullScreen" value="true" /><param name="swLiveConnect" value="true" /><param name="allowScriptAccess" value="always" /><embed src="http://c.brightcove.com/services/viewer/federated_f9?isVid=1&isUI=1" bgcolor="#FFFFFF" flashVars="videoId=1107842657001&playerID=61626370001&playerKey=AQ~~,AAAAAF4Psd4~,gwfEf1kv0CYvSVFaJAwrn9QDKzDrJZMY&domain=embed&dynamicStreaming=true" base="http://admin.brightcove.com" name="flashObj" width="320" height="240" seamlesstabbing="false" type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" swLiveConnect="true" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed></object>';
}






