/******************************************************************************
/ Begin 8.7 script...
/ Added from devel 8.7 to dynamically append external js files to page head...
******************************************************************************/
var DirLocation = null;
var coreCode = new function() {
	this.relativePath = "";
	this.km_scripts = new Object();
	
	this.init = function() {
		var self = coreCode;
		self.setRelativePath();
		DirLocation = (coreCode.relativePath); // session keep alive is using this...
		self.importJavaScriptFiles();
	};
	
	this.setRelativePath = function(){
		var self = coreCode;
		var path = (location.href.substring(0, location.href.lastIndexOf("/")).toLowerCase());
		path = path.replace("//", "");
		var arrTmp = path.split("/");
		for(var i = 1;i < (arrTmp.length-1);i++){
			self.relativePath = (!self.relativePath)? self.relativePath = "../" : self.relativePath = self.relativePath + "../"
		}
	};
	
	// loads external java script files...
	this.km_myclass_import = function(jsFile){
		var self = coreCode;
		if (self.km_scripts[jsFile] != null) return;
		var scriptElt = document.createElement('script');
		scriptElt.type = 'text/javascript';
		scriptElt.src = jsFile;
		document.getElementsByTagName('head')[0].appendChild(scriptElt);
		self.km_scripts[jsFile] = jsFile;
	};
	
	// load our external java script files...
	this.importJavaScriptFiles = function(){
		var self = coreCode;
		self.km_myclass_import(self.relativePath + 'js/ajax.js');
		/*self.km_myclass_import(self.relativePath + 'js/formdata2querystring.js');
		self.km_myclass_import(self.relativePath + 'js/sms_vsSCLinkHandler.js');
		self.km_myclass_import(self.relativePath + 'js/SetActiveLink.js');
		self.km_myclass_import(self.relativePath + 'js/cookie.js');
		self.km_myclass_import(self.relativePath + 'js/debug.js');
		self.km_myclass_import(self.relativePath + 'js/ie6UpgradeMsg.js');
		self.km_myclass_import(self.relativePath + 'js/sms_SessionKeepAlive.js');
		*/
	};
	
	
};

new coreCode.init;
/******************************************************************************
/ End 8.7 script...
******************************************************************************/

//  Default cookie functions
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1)
      endstr = document.cookie.length;
   return unescape(document.cookie.substring(offset, endstr));
}

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 setCookie (name, value,expires,path,domain,secure) {
   path = path
   document.cookie = name + "=" + escape (value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}

function deleteCookie (name, path, domain) {
   if (getCookie(name))   {
   path = path
   setStr = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-98 00:00:01 GMT";
   document.cookie = setStr
   }
}

function showCookie(name)  {
	var strCookieContents = getCookie(name)
	alert('Cookie '+name+' = ' + strCookieContents)
}

var smsChildVar
function smsChildWin(file)  {
  gotoLocation = "fs"+file
  smsChildVar = window.open(gotoLocation,"","height=450,width=400,locationbar=no,directories=no,scrollbars=no")
}

/* 04-23-2010 - dcw  / begin...
// we are changing the session keep alive script to call sms_KeepSessionSession.asp via AJAX to keep our session alive...
var timerId 
var today
var gotoLocation = window.location.href
var timeDuration = smsCoreCodeTimeLimit * 1000
function startTimer(destination){
   //gotoLocation=destination
   window.setTimeout(((gotoLocation) ? "window.location.href = gotoLocation" : "location.reload()"), timeDuration)
}
*/
// 04-23-2010 - dcw  / end...


function logOut(strLink) {
  // they want their cookie deleted if they accept cookies
  deleteCookie("LOGIN")
  deleteCookie("ZipCookie")
  location.href = "sy173frm.asp?link=" + strLink
}

function Go(){return}
	
// function used to open a new child window
var newWindow = null;
function openWin2(url) {
	var winWidth = (550);
	var winHieght = (300);
	var winl = (screen.width - winWidth) / 2;
	var wint = (screen.height - winHieght) / 2;
    winStats='toolbar=no,location=no,directories=no,menubar=no,'
    winStats+='scrollbars=yes,width='+winWidth+',height='+winHieght
		if (navigator.appName.indexOf("Microsoft")>=0) {
          	winStats+=',left='+winl+',top='+wint
 		}else{
       		winStats+=',screenX='+winl+',screenY='+wint
		}
		
		if (!newWindow || newWindow.closed){
			newWindow = window.open(url,"NewWindow",winStats);
		}else{
			newWindow.focus();
		}  
		 
		if (newWindow.opener == null){
			newWindow.opener = self
		} 
		
    }

function SwapBtnImg(objBtn, imageName){
	objBtn.src = ("images/" + imageName + ".gif");
}

/*****************************************************************/
// css / javascript alert box...
var DisableBG = document.createElement('DIV');
var hoverInfo = document.createElement('DIV');
var hoverInfoContent = document.createElement('DIV');
var titleBarContent = document.createElement('DIV');
var titleBar = document.createElement('DIV');
var closeLink = document.createElement('A');
var reloadFlag = false;
function createMessageDivs(){
	closeLink.innerHTML = "close"
	closeLink.href="javascript:void(0);"
	addEventSimple(closeLink,'click',HideCSSMsgBox);
	DisableBG.id = "DisableBG"
	hoverInfo.id = "hoverInfo"
	hoverInfoContent.id = "hoverInfoContent"
	titleBar.id = "titleBar"
	titleBarContent.appendChild(closeLink)
	titleBar.appendChild(titleBarContent)
	hoverInfo.appendChild(hoverInfoContent)
	hoverInfo.appendChild(titleBar)
	document.body.appendChild(hoverInfo);
	document.body.appendChild(DisableBG);
}

function HideCSSMsgBox(){    
	try{
		hoverInfoContent.innerHTML = "";
		hoverInfo.style.display = "none";
		if (reloadFlag){
			document.location.reload();
		}else{
			DisableBG.style.display = "none";
		}
		reloadFlag = false;
		return true;
	}catch(e){
		return false;
	}
}

// used for expandable windows...
this.overrideWidth = null;
this.overrideHeight = null;
this.expandDiv = function(Msg, divWidth, divHeight){
	// dcw / begin...
	this.divWidth = (!this.overrideWidth)? divWidth : this.overrideWidth;
	this.divHeight = (!this.overrideHeight)? divHeight : this.overrideHeight;
	// dcw / end...
	try{
	    var winl;
		var wint;
		var noPx = document.childNodes ? 'px' : 0;
		var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
	    var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
		var windowScrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
		var windowScrollWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
		winl = (windowWidth - this.divWidth) / 2;
	    wint = 30//(divHeight==0)?(30):((window.screen.height - divHeight) / 2);
		// grey out the background and set the height of the grey area to match that of page scroll.
		DisableBG.style.height = windowScrollHeight + noPx;
		DisableBG.style.display="block";

		// Insert message into our message container...
		hoverInfoContent.innerHTML = "";
		hoverInfoContent.style.height = (this.divHeight) + noPx;
		hoverInfoContent.innerHTML = Msg;
		
		// display and position our message box...
		
		hoverInfo.style.left = winl + noPx;
		hoverInfo.style.top = wint + noPx;
		hoverInfo.style.width = this.divWidth + noPx;
		hoverInfo.style.height = this.divHeight + noPx;
		
		// add check to verify info is not show to prevent having to repaint the screen if it's already visible...
		if ((hoverInfo.style.display=="")||(hoverInfo.style.display=="none")){
			setOpacity(hoverInfo,0);
			hoverInfo.style.display="block";
			var fadeTime = 10;
			for(var a=0;a<100;a++){
				setTimeout('setOpacity(hoverInfo,'+(a+25)+')',fadeTime*a);
			}	
		}
		location.hash = '#';
	}catch (e){}
}

function setOpacity(e,opacity){
	var o=e.style;
	o.opacity=(opacity/100); //Opera
	o.MozOpacity=(opacity/100); //Mozilla+Firefox
	o.KhtmlOpacity=(opacity/100); //Konqueror
	o.filter="alpha(opacity="+opacity+")"; //IE
}


function showMessage(Msg, divWidth, divHeight){
	if(Msg != ""){
		this.expandDiv(Msg, divWidth, divHeight)
		//var objInfoBox = expandDiv(Msg, divWidth, divHeight)
		//return objInfoBox;
	}
}
/*****************************************************************/
	
/** Used to assign and remove events to page elements troughout the site **/
function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
	obj.attachEvent('on'+evt,fn);
}

function removeEventSimple(obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
	obj.detachEvent('on'+evt,fn);
}

/** PUSH AND SHIFT FOR IE5 **/
function Array_push() {
	var A_p = 0
	for (A_p = 0; A_p < arguments.length; A_p++) {
		this[this.length] = arguments[A_p]
	}
	return this.length
}

if (typeof Array.prototype.push == "undefined") {
	Array.prototype.push = Array_push
}

function Array_shift() {
	var A_s = 0
	var response = this[0]
	for (A_s = 0; A_s < this.length-1; A_s++) {
		this[A_s] = this[A_s + 1]
	}
	this.length--
	return response
}

if (typeof Array.prototype.shift == "undefined") {
	Array.prototype.shift = Array_shift
}	

// used on te199frm.js.
function getKey(e){
	if (e == null) e = window.event;
	var unicode=e.keyCode? e.keyCode : e.charCode
	return unicode;
}

function winStatus(msg)  {
	self.status = msg
	return true
}

winStatus('');
var d=document;

// function used to open a new child window
var SelectionWindow = null;
function openWindow(url, width, height) {
	var winWidth = (width);
	var winHieght = (height);
	var winl = (screen.width - winWidth) / 2;
	var wint = (screen.height - winHieght) / 2;
    winStats='toolbar=no,location=no,directories=no,menubar=no,'
    winStats+='scrollbars=yes,width='+winWidth+',height='+winHieght
	if (navigator.appName.indexOf("Microsoft")>=0) {
         	winStats+=',left='+winl+',top='+wint
		}else{
      		winStats+=',screenX='+winl+',screenY='+wint
	}
	
	if (!SelectionWindow || SelectionWindow.closed){
		SelectionWindow = window.open(url,"",winStats);
	}else{
		SelectionWindow.focus();
	}

	if (SelectionWindow.opener == null){
		SelectionWindow.opener = self
	} 
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft + "|" + curtop];
}

// used to fill expandable window...
function ajaxFunction(pageName, ElementName){
	var xmlHttp;
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}catch (e){// Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e){
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}catch (e){
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
    
	xmlHttp.onreadystatechange=function(){		
		switch(xmlHttp.readyState){
		case 1:
		  break;
		case 4:			
		  	document.getElementById(ElementName).innerHTML=xmlHttp.responseText;
		  break;
		default:	 
		}
	}
	xmlHttp.open("GET",pageName,true);
    xmlHttp.send(null);
}

/*
function HideNode(objNode){
	objNode.style.display="none";
}
*/

// debugging function used to assist in debugging javascript...
// if no object exsist use the 
// (i.e var myHistory = document.getElementById("history"))
function writeHistory(object, message){
    if(!object || !object.parentNode || !object.parentNode.getAttribute) return;
    var historyDiv = document.getElementById('history');
    if(historyDiv){
        historyDiv.style.display = "block";
        historyDiv.appendChild(document.createTextNode(object.id+': '+message));
        historyDiv.appendChild(document.createElement('BR'));
        historyDiv.scrollTop += 50;
        }
}

// set functions that need to run after page loads here...

function loadInitScripts(){
	createMessageDivs();	// handles the display of all site alerts returned from the STORIS server...
	var myAlertMsg = "";
	if (SessionMsg != ""){
		myAlertMsg = SessionMsg
	}else if(strMsg != ""){
		myAlertMsg = strMsg	
	}
	if(myAlertMsg != ""){
		showMessage(myAlertMsg, 400, 200)
	}
	//startTimer();
	prepMultiCurrencyMenu();
	//*****debugging*********************************************************************************************************
	//showMessage("Alert window debugging in progress.", 400, 300)
	//*****debugging*********************************************************************************************************
}
 
function switchElementState(){
	var multiCurrencySelections = document.getElementById("multiCurrencySelections")
	multiCurrencySelections.style.display=(multiCurrencySelections.style.display!="block")? "block" : "none"
}

function prepMultiCurrencyMenu(){
	try{
		var multiCurrency = document.getElementById("multiCurrency")
		var multiCurrencySelections = document.getElementById("multiCurrencySelections")
		addEventSimple(multiCurrency,'click',switchElementState);
	}catch(e){}
} 
 
function getZipForm(addQS){
	var windowWidth = 500;
    var windowHeight = 300;
	if(addQS != ""){
		addQS = "&" + addQS;
	}
	var myShipZipURL = "faq/shipZipAlt.asp?BackLink=" + location.href + addQS;
	if (!myZipContainer){
		var myZipContainer = document.createElement('DIV');
	}
	myZipContainer.id = "myZipContainer";
	hoverInfoContent.innerHTML = "";
	
	var preLoaderImg = document.createElement('IMG');
	preLoaderImg.src = "images/ajax-loader.gif";
	preLoaderImg.className = "ajaxLoader"
	myZipContainer.appendChild(preLoaderImg);
  	hoverInfoContent.appendChild(myZipContainer);
	ajaxFunction(myShipZipURL, "myZipContainer");
	showMessage(hoverInfoContent.innerHTML, (windowWidth), (windowHeight));
} 

function submitZip(objForm){
	var myZipCode = objForm.zip.value
	var myHidVal = objForm.HidVal.value
	var myBackLink = objForm.BackLink.value
	reloadFlag = true;
	getZipForm("zip=" + myZipCode + "&HidVal=" + myHidVal)
	return false;
}

function setFormFocus() {
	var W3CDOM = document.createElement && document.getElementsByTagName;
	if (!W3CDOM) return;
	var forms = document.forms;
	var focusSet = false;
	for (var i=0;i<forms.length;i++) {
		for(var j=0;j<forms[i].elements.length;j++){
			if ((forms.length==2)&&(forms[i].elements[j].type=="text")){
				forms[i].elements[j].focus();
				focusSet = true;
				break;
			}else if((i>0)&&(forms[i].elements[j].type=="text")){
				forms[i].elements[j].focus();
				focusSet = true;
				break;
			}
		}
		if(focusSet){
			break;
		}
	}
}


//addEventSimple(document,'keypress',getKey)
addEventSimple(window,'load',loadInitScripts);
//addEventSimple(window,'load',setFormFocus);


var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));


function setGoogleAnalyticsScript(){
	try{
		var pageTracker = _gat._getTracker("UA-12731493-2");
		pageTracker._trackPageview();
	}catch(err) {}
}

addEventSimple(window,'load',setGoogleAnalyticsScript);

/**********************************************************************************************************
Added to keep session active once default time has expired. This script uses AJAX to maintain the users
session. This replaces the timing script which required input from the user when reloading pages that 
had been posted to....
/*********************************************************************************************************/
var kaHttpRequest = false;
var kaOldSessionId = '';
var kaDebug = false;
var kaServerPage = 'sms_KeepSessionSession.asp';
var kaInterval = 1140;
var kaOkMessage = '<span style="color: #41930a;">Session alive</span>';
var kaExpiredMessage = '<span style="color: #b82c06;">Session expired</span>';
var kaErrorMessage = '<span style="color: #b82c06;">Session check error</span>';
var mySessionKeepAliveDiv = document.createElement('DIV')

function initializeKeepAlive(){
	kaAjax('POST', kaServerPage, '', mySessionKeepAliveDiv);
	setInterval("kaAjax('POST', kaServerPage, '', mySessionKeepAliveDiv)", kaInterval * 1000);
}

function kaAjax(httpRequestMethod, url, parameters, target){
	kaHttpRequest = false;
  	target.innerHTML = 'Wait...'
	if (window.XMLHttpRequest){
		// For Mozilla, Safari, Opera, IE7+
	    kaHttpRequest = new XMLHttpRequest();
	    if (kaHttpRequest.overrideMimeType){
    	  	kaHttpRequest.overrideMimeType('text/plain');
			//Change MimeType to match the data type of the server response.
			//Examples: "text/xml", "text/html", "text/plain"
		}
 	}else if (window.ActiveXObject){
		// For IE6
   		try{
			kaHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e){
			try{
				kaHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){}
		}
	}
  	if (!kaHttpRequest){
    	alert('Giving up :( Cannot create an XMLHTTP instance');
	    return false;
  	}
  	kaHttpRequest.onreadystatechange = function() {updateElement(target);};
  	if (httpRequestMethod == 'GET'){
		kaHttpRequest.open('GET', url + '?' + parameters, true);
    	kaHttpRequest.send(null);
		ser = ser + 1;
	}else if (httpRequestMethod == 'POST'){
	    kaHttpRequest.open('POST', url, true);
    	kaHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    	kaHttpRequest.send(parameters);
 	}
  	else{
    	alert('Sorry, unsupported HTTP method');
  	}
}

function updateElement(target){
	if (kaHttpRequest.readyState == 4){
		if (kaDebug == true){
			alert(kaHttpRequest.responseText);
		}
	    if (kaHttpRequest.status == 200){
			if (kaOldSessionId == ''){
		        kaOldSessionId = kaHttpRequest.responseText;
		 	}
		    if (kaHttpRequest.responseText == kaOldSessionId){
				target.innerHTML = kaOkMessage;
		    }else{
    			target.innerHTML = kaExpiredMessage;
		    }
		}else{
			target.innerHTML = kaErrorMessage;
		}
	}
}

// trims spaces from begining and end of string...
String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

addEventSimple(window,'load',initializeKeepAlive);
