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
		
		if (url.indexOf('/gm/') != -1 && url.indexOf('http://') == -1) { //manage internal links
			var myserver;
			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 server;
		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 { // 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";
	}
	
	//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) {
	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 = "/servlet/pageTAF?page=" + url + '&div=' + divCode;
		}
		else {
			setCookie('dotdoref', document.referrer, '', '/');
			document.location = "/servlet/pageTAF?page=" + document.referrer + '&div=' + divCode;
		}
	}
	else {
		deleteCookie("dotdoref");
		document.location = "/servlet/pageTAF?page=" + url + '&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
}

