//v1.41 mtsai@extractable.com
function sendToRouter() {
    var argv = sendToRouter.arguments;
    var argc = sendToRouter.arguments.length;
	var countryName = (argc > 0) ? argv[0] : '';
	var args = getArgs();
	var retURL = URLEncode(args.retURL);
	if (isEmpty(retURL)){ retURL = (argc > 1) ? argv[1] : '';	}
	var retcountry = URLEncode(args.retcountry);
	if (isEmpty(retcountry) || parseInt(retcountry)!=0){
			retcountry = 1;
		}else{ 
			retcountry = parseInt(retcountry);
	}
	var pricookie = getCookie(COUNTRY_COOKIE_NAME);
	var tmpcookie = getCookie(COUNTRY_COOKIE_NAME_TMP);
	var oldperm = parseCookieValue(pricookie);
	var oldtemp = parseCookieValue(tmpcookie);
	//if (!isEmpty(pricookie)) {
	//	if (countryName==oldperm) {	// if selected country is same as cookie...
	//		var trackingURL = getTrackerURL(oldperm, oldperm, countryName, countryName);
        //	if (debug){alert(trackingURL);}
        //	var trackerimg = new Image();
        //	trackerimg.src = trackingURL;
	//		sendToDestination(retURL, retcountry, self, countryName);
	//	}
	//	else {
	//		var cwinURL = './gg_popup.html?country=' + countryName;
	//		cwinURL += '&retcountry=' + retcountry;
	//		if (!isEmpty(retURL)) cwinURL += '&retURL=' + retURL;
	//		if(document.theForm.rememberCountry.checked){
	//			userDecision(1,countryName);
	//		}else{
	//			userDecision(0,countryName);
	//		}
	//	}
	//}
	//else {
		//***country tracking url****
		var trackingURL = getTrackerURL('', '', countryName, '');
        if (debug) alert(trackingURL);
        var trackerimg = new Image();
        trackerimg.src =  trackingURL;

		// set up primary country cookie
		//if(document.theForm.rememberCountry.checked){
		//	setPrimaryCookie(countryName);
		//}
		//setTmpCookie(countryName);
		sendToDestination(retURL, retcountry);
	//}
}

function sendToDestination() {
    var argv = sendToDestination.arguments;
    var argc = sendToDestination.arguments.length;

    var retURL = (argc > 0) ? argv[0] : null;
    var retcountry = (argc > 1) ? argv[1] : 0;
    var targetWin = (argc > 2) ? argv[2] : self;
    var selectedCountry = (argc > 3) ? argv[3] : '';

    var url = getDestinationURL(retURL, retcountry, selectedCountry);
    if (debug) alert('send user to ' + url);
	if (self != top) {
	    if (document.images) top.location.replace(url);
	    else top.location.href = url;
	}		
	else {
		targetWin = self; /*aarf*/
		if (targetWin.location.href.indexOf(SELECTCOUNTY_STATIC)>-1) {
			targetWin.location.href=url;
		}
		else {
			targetWin.location.href=url;
		}
	}
}

// get destination url according to return URL and cookie settings
function getDestinationURL() {
    var url = '';
    
    var argv = getDestinationURL.arguments;
    var argc = getDestinationURL.arguments.length;
    
    var retURL = (argc > 0) ? argv[0] : null;    
    var retcountry = (argc > 1) ? argv[1] : null;
    var selectedCountry = (argc > 2) ? argv[2] : '';
    var debug = (argc > 3) ? argv[3] : false;

	var country = '';
	
	if (!isEmpty(selectedCountry)) {
	    country = selectedCountry;
	}
	else {
	    var priCountry = getCookie(COUNTRY_COOKIE_NAME);
	    var tmpCountry = getCookie(COUNTRY_COOKIE_NAME_TMP);
	    //use tmpcountry if it presents
	    if ( !isEmpty(tmpCountry) ) {
		    country = parseCookieValue(tmpCountry);
		    if (debug) alert('getDestinationURL: temporary cookie presents, value is: ' + country);
	    }
	    else if ( !isEmpty(priCountry) ) {			
		    country = parseCookieValue(priCountry);
		    if (debug) alert('getDestinationURL: primary cookie presents, value is: ' + country);
	    }
	}
	
	var ep = checkHistroy(country);
	
	var url = '';
    if (!isEmpty(retURL)) {
		if (!isEmpty(retcountry)) {
			if (retURL.substring(retURL.length-1)!='/') retURL = retURL + '/';
			
			if (retURL.indexOf('?')!=-1) url = retURL + '&country=' + country;
			else url = retURL + '?country=' + country;
			
			url += '&ep=' + ep;	//append new|return user param
		}
		else {	
			url = retURL;
		}
    }
	else {
		//if return path is not specified, read country setting and send user
		//to appreciate destination
		if (country!='') {
			var countryObj = getCountryDataObject(country);
			url = countryObj.regionalSiteURL;
			url += '?country=' + country + '&ep=' + ep;
		}
		else {
			//send user to home page
			url = DEFAULT_HOMEPAGE;
		}
	}
		
	// if valid url cannot be found, use default home page
	if ( isEmpty(url) ) url = DEFAULT_HOMEPAGE;	
	return url;
}


function sendToGateway() {
	var args = getArgs();
		
	var retURL = URLEncode(args.retURL);
	if (isEmpty(retURL)) retURL = '';	

	var retcountry = URLEncode(args.retcountry);
	if (isEmpty(retcountry)) retcountry = 1;
	else {
		retcountry = parseInt(retcountry);
		if (parseInt(retcountry)!=0) retcountry = 1;
	}
	
	var url = DEFAULT_GATEWAY_PAGE + '?retcountry=' + retcountry;
	if (!isEmpty(retURL)) url += '&retURL=' + retURL;
	window.location.replace(url);
}

function getTrackerURL() {
    var argv = getTrackerURL.arguments;
    var argc = getTrackerURL.arguments.length;
    var oldperm = (argc > 0) ? argv[0] : '';
    var oldtemp = (argc > 1) ? argv[1] : '';
    var newperm = (argc > 2) ? argv[2] : '';
    var newtemp = (argc > 3) ? argv[3] : '';
    
    var url = DEFAULT_HOMEPAGE + '/';
    if (!isEmpty(newperm)) url += newperm + '/';
    if (!isEmpty(oldperm)) url += oldperm + '/';
    if (!isEmpty(newtemp)) url += newtemp + '/';
    if (!isEmpty(oldtemp)) url += oldtemp + '/';

	url += 'tracking_GG.trk?oldperm=' + oldperm + 
		'&oldtemp=' + oldtemp +
		'&newperm=' + newperm + 
		'&newtemp=' + newtemp;
	
    var uid = getCookie(GG_IDENTITY);
    if (!isEmpty(uid)) url += '&uid=' + uid;
    	
	return url;
	alert(url);
}

//create the history if it doesn't exists.
//if exists, check the value. if new, append and return v_gg_new;
//otherwise, return v_gg_return
function checkHistroy(isocode) {
	var h = getCookie(HISTORY_COOKIE_NAME);
	if (isEmpty(h)) {
		setHistoryCookie(isocode);
		
		return 'v_gg_new';
	}
	else {
		if (h.indexOf(isocode)!=-1) {	//the country is already in history
			return 'v_gg_return';
		}
		else {	//append the value			
			var value = h + ',' + isocode;
			setHistoryCookie(value);
			return 'v_gg_new';
		}
	}
}

function parseCookieValue(cookieValue) {
	cookieValue=cookieValue+'';		
	var index = cookieValue.indexOf("_");
	result = cookieValue.substring(0,index);
	return result;
}

// decode cookie value and use it to get country object; finally get the regional site url
function getDestination(cookieValue) {
	var isocode = parseCookieValue(cookieValue);
	var countryObj = getCountryDataObject(isocode);
	
	var result = countryObj.regionalSiteURL;
	
	return result;
}

function getCountryObject(id) {
	var countryObj = new Object();
	countryObj.id = -1;
	countryObj.name = "";
	countryObj.regionalSiteURL = "";
	countryObj.countryCode = -1;
	countryObj.countryISOCode = "";
	
	if (isEmpty(id) || isNaN(id)) return countryObj;
	
	var index=0;
	for (var i=0;i<countryData.length;i++) {
		var getdata = false;
		
		if (i<=1) {
			index = 1; getdata = true; i=i+5;
		}
		else {
			index = i; getdata = true; i=i+4; 
		}		
		if (getdata) {
			var test = countryData[index];
			if (id==test) {
				countryObj.id = countryData[index];
				countryObj.name = countryData[index+1];
				countryObj.regionalSiteURL = countryData[index+2];
				countryObj.countryCode = countryData[index+3];
				countryObj.countryISOCode = countryData[index+4];
				
				break;
			}
		}
	}
	return countryObj;
}

//get country object by its ISO code
function getCountryDataObject(isoCode) {
	
	var countryObj = new Object();
	countryObj.id = -1;
	countryObj.name = "";
	countryObj.regionalSiteURL = "";
	countryObj.countryCode = -1;
	countryObj.countryISOCode = "";
	
	isoCode=isoCode+'';	
	if (isEmpty(isoCode)) return countryObj;
	
	var index=0;
	for (var i=0;i<countryData.length;i++) {
		var getdata = false;
		if (i<=1) {
			index = 1; getdata = true; i=i+5;
		}
		else {
			index = i; getdata = true; i=i+4; 
		}		
		
		if (getdata) {
			var test = countryData[index+4];
			if (isoCode==test) {
				countryObj.id = countryData[index];
				countryObj.name = countryData[index+1];
				countryObj.regionalSiteURL = countryData[index+2];
				countryObj.countryCode = countryData[index+3];
				countryObj.countryISOCode = countryData[index+4];
				
				break;
			}
		}
	}
	return countryObj;
}

function getRegionDataObject(regionName) {		
	var regionObj = new Object();
	regionObj.id = -1;
	regionObj.name = "";
	regionObj.visaRegionName = "";
	
	regionName=regionName+'';	
	if (isEmpty(regionName)) return regionObj;
	
	var getdata = false;
	var index=0;
	for (var i=0;i<regionData.length;i++) {
		if (i<=0) {
			index=0; getdata = true; i=i+2;
		}
		else {
			index=i; getdata = true; i=i+2;			
		}
		
		if (getdata) {
			var test = regionData[index+1];
			if (regionName==test) {
				regionObj.id = regionData[index];
				regionObj.name = regionData[index+1];
				regionObj.visaRegionName = regionData[index+2];
				break;
			}	
		}
	}
	return regionObj;	
}

//return array of country IDs belong to the region
function getRegionCountries(regionObj) {
	var countryArray = new Array();
	if (isNaN(regionObj.id)) return countryArray;
	
	var getdata = false;
	var index=0;	
	//var str = '';
	for (var i=0;i<countryRegionData.length;i++) {
		if (i<=0) {
			index=0;getdata = true; i=i+1;
		}
		else {
			index=i; getdata = true; i=i+1;			
		}
		if (getdata) {
			var test = countryRegionData[index];
			if (regionObj.id==test) {
				countryArray[countryArray.length] = countryRegionData[index+1];
			}
		}	
	}	
	return countryArray;
}


function getCookieValue(countryObj) {
	var value = '';
	var test = countryObj.countryISOCode;
	if (!isEmpty(test)) value += test;
	
	var timestamp = new Date().getTime();
	value += '_' + timestamp;
	
	return value;
}

function setPrimaryCookie(isoCode) {
	var countryObj = getCountryDataObject(isoCode);
	var cookieValue = getCookieValue(countryObj);
				
	var expires = new Date(); 
	expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000 * 360));					
				
	setCookie(COUNTRY_COOKIE_NAME, cookieValue, null, expires);
}

function setTmpCookie(isoCode) {
	//alert("in set temp cookie. ISO code is: " + isoCode);
	var countryObj = getCountryDataObject(isoCode);
	var cookieValue = getCookieValue(countryObj);
	
	setCookie(COUNTRY_COOKIE_NAME_TMP, cookieValue);
}

function setHistoryCookie(value) {
	var expires = new Date(); 
	expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000 * 360));					
				
	setCookie(HISTORY_COOKIE_NAME, value, null, expires);
}

function fixCookieDate (date) {
	var base = new Date(0);
	var skew = base.getTime(); // dawn of (Unix) time - should be 0
	
	// Except on the Mac - ahead of its time
	if (skew > 0) date.setTime (date.getTime() - skew);
}

function getCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		
		if (i == 0) break; 
	}	
	
	return null;
}

function deleteCookie(name) {
	if (getCookie(name)) {
        setCookie (name, "null");
	}
}

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function setCookie (name, value) {
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    
    var path = (argc > 2) ? argv[2] : null;
    if (path==null) path = '/';    // if path isn't specified, path='/'
    
    var expires = (argc > 3) ? argv[3] : null;    
        
    var domain = (argc > 4) ? argv[4] : null;    
    if (domain==null) {
		var domain = document.domain+'';
		
		var astr = domain.split('.');
		if (astr.length>=2) {	//parse domain to root domain
			domain = '';
			for (var i=astr.length-2;i<astr.length;i++) {
				domain += astr[i] + '.';
			}			
		}
		if (domain.length!=0) domain=domain.substring(0,domain.length-1);
		if (domain=='103.190') domain='172.16.103.190';  // needed to ensure this works on the IP address of the betaserver
		{
		}
    }

    var secure = (argc > 5) ? argv[5] : null;
    
    var str = name + "=" + escape (value);
    if (expires!=null) {
		fixCookieDate(expires);
		str += '; expires=' + expires.toGMTString();
	}
	
    if (path!=null) str += '; path=' + path;
    if (domain!=null) {
		if (!isMSIE() && ( isBrowserVersion(3) || isBrowserVersion(4) ) ) {
		}
		else {
			str += '; domain=' + domain;    
		}
	}
    if (secure!=null && secure==true) str += '; secure';
//var debug = true;
//if (debug) alert("set cookie: " + str);    
    document.cookie = str;
}


function getRandomString() {
	var Uppers = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
	var Lowers= new String("abcdefghijklmnopqrstuvwxyz");
	var Numbers = new String("0123456789");
		
	var passlen = new Array(6,7,8); // Generated password length
	var i = 0;
	
	var useCharacters = new String(Uppers + Lowers + Numbers);	
	var str = "";
	
	i = parseInt(Math.random() * 100);		
	i = i%3;	
	for (var j=0; j< passlen[i]; j++) {
		var tmp = parseInt(Math.random() * useCharacters.length);		
		str = str + useCharacters.substring(tmp, tmp+1);
	}
		
	return str;
}


function openNewWindow(url, winName, width, height)	{
	// adds 18 pixels to Netscape new window height
	// so the two browsers view the quiz the same
	var browser = navigator.appName;
	if (browser.indexOf("Net") != -1){
		height += 18;
	}
	// done checking browser
	//alert(window.screenTop + ' ' + window.screenLeft);
	var feature = 'toolbar=no,titlebar=no,location=no,directories=no,status=no,' + 
				  'menubar=no,resizable=no,copyhistory=no,fullscreen=no,scrollbars=no,' +
				  'width=' + width + ',height=' + height;				  					  
				  
	if (isMSIE()) {
		if(isMacintosh()){	
			// must assign static content because screenLeft and screenTop
			// do not work for MacIE 5
			feature += ',left=100,top=100';
		}else{
			feature += ',left=' + (window.screenLeft+50) + ',top=' + (window.screenTop+30);
		}
	}
	else {
		feature += ',screenX=' + (screenX+(outerWidth/2)-20) + ',screenY=' + (screenY+(outerHeight/2));
	}
	
	var Win = window.open(url, winName, feature);		
	if (Win.opener == null) Win.opener = this;
	
	return Win;
}

// start of displayAlert include
function isWebTV() {
	if ( (navigator.appName.indexOf ( "WebTV" ) != -1 ) ) { // WebTV
		return true;
	} 
	else {
		return false;
	}
}
function isMSIE() {
	if ( (navigator.appVersion.indexOf ("MSIE") != -1) ) {
		return true;
	} 
	else {
		return false;
	}
}
function isMacintosh() {
	if ( (navigator.appVersion.indexOf ("Macintosh") != -1) ) {
		return true;
	} 
	else {
		return false;
	}
}
function isBrowserVersion(versionString) {      // versionString = 3.01
	return ( navigator.userAgent.indexOf (versionString) != -1);
}

function getArgs(str) {
	if (str=='' || str==null) str = location;
    var args = new Object();
    var query = str.search.substring(1);
    var pairs = query.split("&");       
    for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;        
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);      
    }
    
    return args;
}

function isEmpty(str)	{
	var b = false;
		
	strTemp = new String(str);	
	if (strTemp == null)
		b = true;
	else
		if (strTemp == 'undefined' || strTemp=='null'|| strTemp.length == 0) b = true;
	
	return b;
}


function URLEncode(str) {
	str = str+'';
	str = str.replace(/\s/g, '%20');
		
	return str;
}

function URLUnEncode(str) {
	str = str+'';
	str = str.replace(/\+/g, ' ');
	
	return str;
}

// force myself to get out of frameset
function backtoTopFrame() {
	if (self != top) {
	    if (document.images)
	        top.location.replace(window.location.href);
	    else
	        top.location.href = window.location.href;
	}
}
/// merged from core.js
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
	document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function goIndex(myIndex){
	location.href = this.myForm.countryList[myIndex].value;
}

function go(formName,myIndex){
	location.href = eval("this." + formName + ".countryList[myIndex].value");
}

function changeMap(region){
	if (region == 'off') {
		document.images['myMapImage'].src = mapImgs[lastClicked].src;
	} else {
		document.images['myMapImage'].src = mapImgs[region].src;
	}
}

var regionsArr = ['russia','mideast','europe','asia','africa','southamerica','northamerica','centralamerica','australia'];

function showCountriesLayer(region){
	for(i=0;i<regionsArr.length;i++){
		if(regionsArr[i] == region){
			eval("document.all." + regionsArr[i] + ".style.visibility = 'visible'");
		}else{
			eval("document.all." + regionsArr[i] + ".style.visibility = 'hidden'");
		}
	}
}

var off = new Image();
off.src = "images/map_default.gif";
var russia = new Image();
russia.src = "images/map_russia.gif";
var mideast = new Image();
mideast.src = "images/map_middle_east.gif";
var europe = new Image();
europe.src = "images/map_europe.gif";
var asia = new Image();
asia.src = "images/map_asia.gif";
var africa = new Image();
africa.src = "images/map_africa.gif";
var southamerica = new Image();
southamerica.src = "images/map_south_america.gif";
var northamerica = new Image();
northamerica.src = "images/map_north_america.gif";
var centralamerica = new Image();
centralamerica.src = "images/map_central_america.gif";
var australia = new Image();
australia.src = "images/map_australia.gif";
var chooseARegion = new Image(157, 24);
chooseARegion.src = './images/chooseARegion.gif';
var map = new Image(472, 161);
map.src = './images/map.gif';
var chooseacountry = new Image(224, 24);
chooseacountry.src = './images/chooseacountry.gif';
var org_arrow = new Image(13, 13);
org_arrow.src = './images/arrow_orange_sq_rd1.gif';
var smalllogo = new Image(123, 14);
smalllogo.src = './images/corpinfo.gif';
var topimg = new Image(761, 207);
topimg.src = './images/top.jpg';

function countrySite() {
  var countryObj = getCountryDataObject(document.theForm.country[document.theForm.country.selectedIndex].value);

  //document.write("id: " + countryObj.id + "<br \>");
  //document.write("name: " + countryObj.name + "<br \>");
  //document.write("url: " + countryObj.regionalSiteURL + "<br \>");
  //document.write("ccode: " + countryObj.countryCode + "<br \>");
  //document.write("isocode: " + countryObj.countryISOCode + "<br \>");

  //window.location=countryObj.regionalSiteURL + "?lang=" + countryObj.countryISOCode;
  window.location=countryObj.regionalSiteURL;

//				countryObj.name = countryData[index+1];
//				countryObj.regionalSiteURL = countryData[index+2];
//				countryObj.countryCode = countryData[index+3];
//				countryObj.countryISOCode =
 // document.write("this is a test");


}

function doSelection() {
	//if(window.location.href.indexOf('/gg_selectcountry.html')!=-1){
		// if they select the first item in the pulldown item '0' give them the error.
//		var myComparison = eval(document.theForm.country.selectedIndex<=0);
//		var errorMessage = "Please select a country/region";
//	}else{
		// if dont select anything in the countries list give them the error.
//		var myComparison = eval(document.theForm.country.selectedIndex<0);
//		var errorMessage = "Please select a country/territory";
//	}
//	if (myComparison) {
//		alert(errorMessage);
//	}
//	else {
		var selectedValue = document.theForm.country[document.theForm.country.selectedIndex].value;
		if (!isEmpty(selectedValue)) sendToRouter(selectedValue);
//	}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}