﻿// JScript File

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
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 getCartInfo () {
    var cartInfo  = new Array()
    var strCookie = getCookieValue ('SCIFO')
    var arrCookie = strCookie.split("&")
    for (var i =0; i < arrCookie.length; i++){
        var arrCookieVals = arrCookie[i].split("=")
        cartInfo[arrCookieVals[0]]= arrCookieVals[1]
    }
    return cartInfo
}
function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}
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=/";
}  

function FillShipping(container){
 if (document.getElementById(container+"_cbSame").checked){
   document.getElementById(container+"_txtFname_s").value=document.getElementById(container+"_txtFname").value;
   document.getElementById(container+"_txtLname_s").value=document.getElementById(container+"_txtLname").value;
   document.getElementById(container+"_txtAddress1_s").value=document.getElementById(container+"_txtAddress1").value;
   document.getElementById(container+"_txtAddress2_s").value=document.getElementById(container+"_txtAddress2").value;
   document.getElementById(container+"_txtCity_s").value=document.getElementById(container+"_txtCity").value;
   document.getElementById(container+"_txtZip_s").value=document.getElementById(container+"_txtZip").value;
   document.getElementById(container+"_txtPhone_s").value=document.getElementById(container+"_txtPhone").value;
   //document.getElementById(container+"_txtFax_s").value=document.getElementById(container+"_txtFax").value;
   document.getElementById(container+"_txtState_s").value=document.getElementById(container+"_txtState").value;
   document.getElementById(container+"_txtCompany_s").value=document.getElementById(container+"_txtCompany").value;
   document.getElementById(container+"_ddlState_s").selectedIndex=document.getElementById(container+"_ddlState").selectedIndex;
   document.getElementById(container+"_ddlCountry_s").selectedIndex=document.getElementById(container+"_ddlCountry").selectedIndex;

 }
}

window.onloadListeners=new Array();
window.addOnLoadListener = function(listener) {
	window.onloadListeners[window.onloadListeners.length]=listener;
}
window.onload=function(){
	for(var i=0;i<window.onloadListeners.length;i++){
		func = window.onloadListeners[i];
		func.call();
	}
}
function fireAll(){
	for(var i=0;i<window.onloadListeners.length;i++){
		func = window.onloadListeners[i];
		func.call();
	}
}
function Increment(textBoxId,increment) {
	var textBoxControl = GetTextbox( textBoxId );
	if( textBoxControl != null ) textBoxControl.value = parseInt(textBoxControl.value) + increment;
}
function Decrement(textBoxId,increment) {
	var textBoxControl = GetTextbox( textBoxId );
	if( textBoxControl != null && parseInt(textBoxControl.value) != 0 ) textBoxControl.value = parseInt(textBoxControl.value) - increment;
}
function GetTextbox(textBoxId) {
	for( var i=0; i<document.forms.length; i++ ) {
		var theForm = document.forms[i];
		if( typeof(theForm[textBoxId]) != "undefined" ) {
			var textBoxControl = theForm[textBoxId];
			if ( isNaN( parseInt( textBoxControl.value ) ) ) textBoxControl.value = 0;
			return textBoxControl;
		}
	}
	return null;
}

//================================================================
function fP(){
    if ( document.Form1.hiddenP != undefined && document.Form1.hiddenP.value != "") {
        document.Form1.txtPassword.value =  document.Form1.hiddenP.value;
    }
    if ( document.Form1.hiddenRP != undefined && document.Form1.hiddenRP.value != "") {
        document.Form1.txtRetypePassword.value =  document.Form1.hiddenRP.value;
    }
}

function checkStatus(){
    var tcs = getCookie('TCS');
//alert(stage)
    if (tcs != null && (tcs == 3 || tcs == 4))  {
         document.getElementById("mainPane").style.visibility = "visible";
         document.getElementById("mainPane").style.visibility = "visible";
    }
    else {
        document.getElementById("loading").style.visibility = "visible";
        document.getElementById("loading").style.visibility = "visible";
        window.location.replace('default.aspx');
    }
}

//===================================================================================================

function Get_Cookie(name) {
  var start = document.cookie.indexOf(name + '=');
  var len = start + name.length + 1;
  if ((!start) && (name != document.cookie.substring(0,name.length)))
    return null;
  if (start == -1)
    return null;
  var end = document.cookie.indexOf(';',len);
  if (end == -1) end = document.cookie.length;
  return unescape(document.cookie.substring(len,end));
}

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Delete_Cookie(name,path,domain) {
  if (Get_Cookie(name))
    document.cookie =
      name + '=' +
      ( (path) ? ';path=' + path : '') +
      ( (domain) ? ';domain=' + domain : '') +
      ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

//================================== EasyAjax ===========================================================================

var IS_IE = true;
try
{
	window.attachEvent = window.HTMLDocument.prototype.attachEvent = window.HTMLElement.prototype.attachEvent = function (type, callback) {this.addEventListener(type.substring(2), callback, false);}
	window.detachEvent = window.HTMLDocument.prototype.detachEvent = window.HTMLElement.prototype.detachEvent = function (type, callback) {this.removeEventListener(type.substring(2),callback,false);}

	CSSStyleDeclaration.prototype.__defineGetter__('pixelLeft',function() {return parseInt(this.left) || 0;});
	CSSStyleDeclaration.prototype.__defineSetter__('pixelLeft',function(i) {this.left = i + "px";});
	CSSStyleDeclaration.prototype.__defineGetter__('pixelTop',function() {return parseInt(this.top) || 0;});
	CSSStyleDeclaration.prototype.__defineSetter__('pixelTop',function(i) {this.top = i + "px";});

	IS_IE = false;
}
catch(e) { }

function Queue()
{
	var queue = new Array();
	var space = 0;

	this.enqueue = function(element)
	{
		queue.push(element);
	}

	this.dequeue = function()
	{
		if (queue.length)
		{
			var element=queue[space];

			if (++space * 2 >= queue.length)
			{
				for (var i = space; i < queue.length; i++) 
					queue[i - space] = queue[i];

				queue.length -= space;
				space=0;
			}

			return element;
		}
		else
			return undefined;
	 }
}
	
var EasyAjax = {	
	
	callQueue : new Queue(),
	
	waiting : false,

	callNext : function ()
	{
		if (!EasyAjax.waiting)
		{
			var queuedCall = EasyAjax.callQueue.dequeue();
			
			if (queuedCall != undefined)
			{		
				EasyAjax.waiting = true;

				var url = queuedCall[0];
				var params = queuedCall[1];
				var callback = queuedCall[2];
				
				var content = "";

				if (params)
					for (var key in params)
						content += (key + "=" + encodeURI(params[key]) + "&");

				var xmlhttp;

				if (window.XMLHttpRequest)
					xmlhttp = new XMLHttpRequest();
				else if (window.ActiveXObject)
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

				setTimeout
				(
					function () 
					{ 
						if (xmlhttp.readyState != 4)
						{
							xmlhttp.abort();
							EasyAjax.waiting = false; 
							EasyAjax.callNext();
						}
					},
					10000
				);

				if (callback)
					xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { callback(xmlhttp.responseText); EasyAjax.waiting = false; EasyAjax.callNext(); } };

				if (params)
				{
					xmlhttp.open("POST",url,true);

					xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
					xmlhttp.setRequestHeader("Content-length", content.length);
					xmlhttp.setRequestHeader("Connection", "close");

					xmlhttp.send(content);
				}
				else
				{
					if (url.indexOf("?") == -1)
						url += "?";
					else 
						url += "&";
					url += "n=" + Math.floor(Math.random()*999999999)

					xmlhttp.open("GET",url,true);
					xmlhttp.send(null);		
				}
			}
		}
	},

	reload : function(node, params)
	{
		EasyAjax.callQueue.enqueue([node.getAttribute("url"), params, function (responseText) { node.innerHTML = responseText; }]);
		EasyAjax.callNext();	
	},

	init : function()
	{
		EasyAjax.step(document.body);
	},

	step : function(node)
	{
		if (node.nodeName.toUpperCase() == "EASY:AJAX" || node.nodeName.toUpperCase() == "AJAX" || node.nodeName.toUpperCase() == "DIV")
		{
			node.reload = function (params) { EasyAjax.reload(node, params); }

			if (node.getAttribute("interval")) 
			{
				node.reload();
				setInterval(function () { node.reload(); }, node.getAttribute("interval"));	
			}
		}

		for (var i = 0; i < node.childNodes.length; i++)
			EasyAjax.step(node.childNodes[i]);
	}
	
};

window.attachEvent("onload", EasyAjax.init);

//========================================== AutoComplete =================================================================================

AutoComplete = function(input, suggestions, type, button2click)
{
	var timer;

	input.attachEvent("onkeyup", handleKeyUp);
	input.attachEvent("onkeydown", handleArrowKeys);
    suggestions.attachEvent("onmouseover", handleMouseOver);
    suggestions.attachEvent("onclick", handleMouseClick);
    suggestions.attachEvent("onmouseout", handleMouseOut);

    function handleMouseOut (event)
    {
	    var target= event.srcElement ? event.srcElement : event.target;
        var id= target ? (target.id ? target.id : "ITEMDIV") : "NO TARGET";

   	    if (timer)
			    clearTimeout(timer);

	    if (input.value.length > 0)
		    timer = setTimeout("opacity(suggestions, 100, 0, 250);", 2000);
    }
    function handleMouseClick(event)
    {
        var target= event.srcElement ? event.srcElement : event.target;
        var id= target ? (target.id ? target.id : "ITEMDIV") : "NO TARGET";
        if (id == "ITEMDIV")
        {
		    if (IS_IE)
			    input.value = target.innerText;
		    else
			    input.value = target.textContent;
    
    		opacity(suggestions, 100, 0, 250);
            __doPostBack(button2click,'');
        }
    }
    function handleMouseOver(event)
    {
   	    if (timer)
		    clearTimeout(timer);
        var target= event.srcElement ? event.srcElement : event.target;
        var id= target ? (target.id ? target.id : "ITEMDIV") : "NO TARGET";
        var selectedId;
        if (id == "ITEMDIV")
        {
            selectedId = target;
        }
		var mainDiv = document.getElementById('autocomplete');
		var divs = mainDiv.getElementsByTagName('DIV');
		for (i in divs)
		{
			var div = divs[i];
			if(div == selectedId)
			{
				div.className = "selected"
			}
            else
            {
				div.className = ""
            }    
		}
    }
	function handleKeyUp(event)
	{
		if (event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13 && event.keyCode != 27)
		{
			if (input.value.length == 0)
				suggestions.innerHTML = "";

			if (timer)
				clearTimeout(timer);

			if (input.value.length >= 2)
				timer = setTimeout(reload, 400);
		}
		else if (event.keyCode == 13)
		{
			var cursor = getCursor();
			var parent = suggestions.firstChild;

			if (cursor != -1 && cursor < parent.childNodes.length)
			{
				if (IS_IE)
					input.value = parent.childNodes[cursor].innerText;
				else
					input.value = parent.childNodes[cursor].textContent;

           		opacity(suggestions, 100, 0, 250)
			}
		}
		else if (event.keyCode == 27)
		{
       		opacity(suggestions, 100, 0, 250)
		}
	}

	function reload()
	{
		opacity(suggestions, 0, 100, 250);
        if (type.type == "hidden") {
            var searchVal = type.value;
        }
        else {
            var searchVal = type.options[type.selectedIndex].value;
        }
        positionDiv(input,suggestions);
		suggestions.reload({ prefix : input.value, type : searchVal });
	}

	function handleArrowKeys(event)
	{
		try
		{
			var cursor = getCursor();
			var parent = suggestions.firstChild;

			if (cursor != -1 && (event.keyCode == 40 || event.keyCode == 38))
			{
				if (event.keyCode == 40)
				{
					if (cursor == parent.childNodes.length)
                        parent.childNodes[0].className = "selected"
					else if (cursor < parent.childNodes.length - 1)
					{
                        parent.childNodes[cursor].className = ""
                        parent.childNodes[cursor + 1].className = "selected"
					}
				}
				else
				{
					if (cursor > 0)
					{
	                    parent.childNodes[cursor].className = ""
                        parent.childNodes[cursor - 1].className = "selected"
					}
				}
				if (IS_IE)
					input.value = parent.childNodes[cursor].innerText;
				else
					input.value = parent.childNodes[cursor].textContent;

			}
		}
		catch (e) { }
	}

	function getCursor()
	{
		if (suggestions.innerHTML.length == 0)
			return -1;

		var parent = suggestions.firstChild;

		for (var i = 0; i < parent.childNodes.length; i++)
			if (
					parent.childNodes[i].className == "selected"
			   )
				return i;

		return parent.childNodes.length;
	}
}

function opacity(div, opacStart, opacEnd, millisec) {
	var id = div.id
	var speed = Math.round(millisec / 100);
	var timer = 0;
	if (opacStart > opacEnd)
	{
		setTimeout("document.getElementById('" + id + "').innerHTML = ''", (millisec * 2));
		for (i = opacStart; i >= opacEnd; i--)
		{
			setTimeout("changeOpac(" + i + ",'" + id + "')", (timer * speed));
			timer++;
		}
	}
	else if (opacStart < opacEnd)
	{
		for (i = opacStart; i <= opacEnd; i++)
		{
			setTimeout("changeOpac(" + i + ",'" + id + "')", (timer * speed));
			timer++;
		}
	}
}
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function positionDiv(inp, div)
{
	var x = 0;
	var y = inp.offsetHeight;

	while (inp.offsetParent && inp.tagName.toUpperCase() != 'BODY')
	{
		x += inp.offsetLeft;
		y += inp.offsetTop;
		inp = inp.offsetParent;
	}

	x += inp.offsetLeft;
	y += inp.offsetTop;

	div.style.left = x + 'px';
	div.style.top = y + 'px';
}
//=================================================================================================================

//Itemize characters to remove
//            function cleanString (str) {
//                return str.replace(/[\(\)\.\-\s,]/g, "");
//            }
//Remove all non-digits
function cleanString (str) {
    return str.replace(/[^\d]/g, "");
}
