//This script requires user to declare and initialize the variable storeId
//these functions are used to do an AJAX callback to the server
var req;
var siteURL;
function userCountryLookUp() {  
  
   var url = "UserCountryLookUpCmd?storeId=12052&langId=-1&pageView=0" ;
   //+ encodeURIComponent(storeId);   
   if(!initializeHttpObject()){
    return false;
    //=============>
   } 
   req.open("GET", url, true);
   req.onreadystatechange = callback;
   req.send(null);  
}
window.onresize = setLayerPosition;

function initializeHttpObject() {
  try  {  // Firefox, Opera 8.0+, Safari  
     req = new XMLHttpRequest(); 
  }
  catch (e) {  // Internet Explorer 
    try {
      req=new ActiveXObject("Msxml2.XMLHTTP");    
    }
    catch (e)
    {
      try {
        req=new ActiveXObject("Microsoft.XMLHTTP");      
      }
      catch (e) { 
        //alert("Your browser does not support AJAX!");      
        return false;      
      }    
    }  
  }
  return true;
}


function callback() {
    if (req.readyState == 4) {
        if (req.status == 200) {
           parseMessage();
        }
    }
}

function parseMessage() {
try {

   	var message = req.responseXML.getElementsByTagName("ignore")[0];
   	if (message.childNodes[0].nodeValue == 'false') {
           siteURL = req.responseXML.getElementsByTagName("url")[0].childNodes[0].nodeValue;
           var countryCode = req.responseXML.getElementsByTagName("countryCode")[0];
           setMessage(countryCode.childNodes[0].nodeValue);
        }
  }
  catch(err)
  {
    //something bad happened 
    
  }
}

//these functions are used to mask the page contents

function getBrowserHeight() {
    var intH = 0;
    var intW = 0;

    if(typeof window.innerWidth  == 'number' ) {
       intH = window.innerHeight;
       intW = window.innerWidth;
    }
    else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        intH = document.documentElement.clientHeight;
        intW = document.documentElement.clientWidth;
    }
    else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
        intH = document.body.clientHeight;
        intW = document.body.clientWidth;
    }

    return { width: parseInt(intW), height: parseInt(intH) };
}

function setLayerPosition() {
    var shadow = document.getElementById("shadow");
    var question = document.getElementById("question");
	if(shadow && question)
	{
    	var bws = getBrowserHeight();
    	shadow.style.width = bws.width + "px";
    	shadow.style.height = bws.height + "px";
    	question.style.left = parseInt((bws.width - 410) / 2)+'px';
    	question.style.top = parseInt((bws.height - 200) / 2)+'px';
	}
    shadow = null;
    question = null;
}

function showLayer() {
    setLayerPosition();

var shadow = document.getElementById("shadow");
    var question = document.getElementById("question");

    shadow.style.display = "block";
    question.style.display = "block";

    shadow = null;
    question = null;
}

function hideLayer() {
    var shadow = document.getElementById("shadow");
    var question = document.getElementById("question");

    shadow.style.display = "none";
    question.style.display = "none";

    shadow = null;
    question = null;
}

function setMessage(countryCode) {
    var newDiv = document.createElement("div");
    newDiv.id='gtmMessage';
    var bodyRef = document.getElementsByTagName("body").item(0);
    bodyRef.appendChild(newDiv);
    
    var a  = '<div id="shadow" style="display:none;position:absolute;top:0px;left:0px;opacity:0.6;filter:alpha(opacity=60);background-color: #000000;z-Index:1000;"> </div>';
    a += '<div id="question" style="position:absolute;top:0px;left:0px;width:410px;height:200px;display:none;z-Index:1001;border:2px solid black;background-color:#FFFFFF;text-align:left;vertical-align:middle;padding:10px;">';
    a += '<div class="global_redirect_popup" id="' + countryCode + '_popup">';
	a += '<div id="redirect_button_container">';
	a += '<a href="javascript:checkRememberMe(0);"><img src="/wcsstore/Fossil/images/en_US/popups/redirects/' + countryCode + '_button.gif" class="redirect_button" border="0" id="' + countryCode + '_button"/></a>';
	a += '<a href="javascript:checkRememberMe(1);"><img src="/wcsstore/Fossil/images/en_US/popups/redirects/fossil_button.gif" class="redirect_button" border="0" id="usa_button"/></a>';
    a += '</div>';
	a += '</div>';
	a += '</div>';
	
    document.getElementById("gtmMessage").innerHTML = a;

    showLayer();
}
function navigate()
{
  window.location.href = siteURL;
}
/*
target value =1 corresponds to fossil.com  or current site 
target value =0 corresponds to other site 
*/
function checkRememberMe(target)
{
	var rememberMe = document.getElementById('fossilRememberMe');
	if(rememberMe && rememberMe.checked) {	
		if (testPersistentCookie()) {
           	if(target == 1) {
		 	 writePersistentCookie('fossilPermanent','fossil','years',1);
			}
			else {
		 	 writePersistentCookie('fossilPermanent',siteURL,'years',1);
			}
        }
        else {
           alert ("Persistent Cookies are not enabled your decision may not be remembered");
        }
	}
	if(target == 1) {
		hideLayer();
	}
	else {
		navigate();
	}
}

function checkCookie()
{
	if (!getCookieValue("fossilSession")) {
	      if (getCookieValue("fossilPermanent"))  {
             siteURL = getCookieValue("fossilPermanent");
             if(siteURL != 'fossil')
             navigate();
          
          } else {
          	 //write session cookie
			writeSessionCookie("fossilSession","fossilSession");
          	 //call the function to look up users
		     userCountryLookUp();
          }          
	}	
}
/*==============================================================================

    Cookie Routines by courtesy of John Gardner - 2003 - 2005
================================================================================

*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years": 
     var year = expireDate.getYear();     
     // Note some browsers give only the years since 1900, and some since 0.
     if (year < 1000) year = year + 1900;     
     expireDate.setYear(year + offset);
     break;
    case "months":
      expireDate.setMonth(expireDate.getMonth() + offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate() + offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours() + offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes() + offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  
checkCookie();
