﻿// Common.js

var d = document;
var detect, browser, thestring, OS;

var workingImageHTML =  "<div class='workingImageWrap'><img class='workingImage' src='/Images/working_new.gif' />" +
   "<img class='workingImageBkgrnd png' src='/Images/circle_new.png' /></div>"
                                 
// Body_OnLoad should be called from the master page's body onload.
// It checks to see if a function named ContentPage_OnLoad exists, and 
// if so, it runs it.  ContentPage_OnLoad can be defined differently
// on each content page that uses the master.
function Body_OnLoad() {
   SetVariables_Master();
   
   if (typeof ContentPage_OnLoad == 'function') {
      ContentPage_OnLoad();
   }

/*
   // Get width and height of logo image and set up PNG hack for it
   var logoImage = $get("ctl00_logoImage");
   logoImage.style.width = logoImage.width + "px";
   logoImage.style.height = logoImage.height + "px";
   AddClass(logoImage, "png");
*/
   
   // Get count of cart items from cookie and display it
   var cartCount = readCookie("cartCount");
   if (cartCount == null) {cartCount = 0;}
   SetCartCount(cartCount, false);

   // Get count of favorites from cookie and display it
   var favoritesCount = readCookie("favoritesCount");
   if (favoritesCount == null) {favoritesCount = 0;}
   SetFavoritesCount(favoritesCount, false);
}//end Body_OnLoad

function mpe_onShown(){
   // Lower z-index on header items so they will be hidden by modal popups
   $get("ctl00_logoImage").style.zIndex = 10;
   $get("ctl00_bannerImage").style.zIndex = 10;
   $get("ctl00_linksTable").style.zIndex = 10;
}//end mpe_onShown

function mpe_onHidden(){
   // Raise z-index on header items back up after modal popup is closed
   $get("ctl00_logoImage").style.zIndex = 200;
   $get("ctl00_bannerImage").style.zIndex = 200;
   $get("ctl00_linksTable").style.zIndex = 200;
}//end mpe_onHidden

// Display the count of items in the cart.
// If setCookie is true, set the cookie to the given value, also.
function SetCartCount(cartCount, setCookie) {
   if (setCookie) {createCookie("cartCount", cartCount, 7)}
   if (cartCount == 1) {
      $get("ctl00_cartCount").innerHTML = cartCount + " item";
   } else {
      $get("ctl00_cartCount").innerHTML = cartCount + " items";
   }
}//end SetCartCount

// Display the count of favorites.
// If setCookie is true, set the cookie to the given value, also.
function SetFavoritesCount(favoritesCount, setCookie) {
   if (setCookie) {createCookie("favoritesCount", favoritesCount, 7)}
   if (favoritesCount == 1) {
      $get("ctl00_favoritesCount").innerHTML = favoritesCount + " image";
   } else {
      $get("ctl00_favoritesCount").innerHTML = favoritesCount + " images";
   }
}//end SetCartCount

/*
 * function createCookie
 * 
 * Create a cookie with the given name and value, which expires after the 
 * specified number of days.
 */

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	d.cookie = name+"="+value+expires+"; path=/";
}

/* 
 * function readCookie
 * 
 * Return the value of the cookie with the given name.
 */

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = d.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 eraseCookie
 * 
 * Erase the cookie with the given name.
 */

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

/************************************
	function CloseModalPopup

	CloseModalPopup should be called to close a modal popup instead of using
	the default CancelControlId property of the modalpopupextender to prevent
	popup reappearing during page navigation in some browsers.
   mpe = modalpopupextender object
   pnl = panel object to hide
   
   NOTE: Unlike the version on PLE, the GRI version takes the actual objects 
      as arguments, not their ids.
*************************************/    
function CloseModalPopup(mpe, pnl) {
   mpe.hide(); 
   pnl.style.display = 'none';
   return false;
}//end CloseModalPopup

/***************************/
/*** CSS Class Functions ***/
/***************************/

function RemoveClass(ctl, classN) {
   var classList = ctl.className.split(" ");
   for (var i = 0; i <= classList.length; i++) {
      if (classList[i] == classN) {
         classList.splice(i, 1)
      }
   }
   ctl.className = classList.join(" ");
}//end RemoveClass

function AddClass(ctl, classN) {
   var classList = ctl.className.split(" ");
   var alreadyExists = false;
   for (var i = 0; i <= classList.length; i++) {
      if (classList[i] == classN) {
         alreadyExists = true;
         break;
      }
   }
   if (!alreadyExists) {
      classList.push(classN);
   }
   
   ctl.className = classList.join(" ");
}//end AddClass

function HasClass(ctl, classN) {
   var classList = ctl.className.split(" ");
   var hasClass = false;
   for (var i = 0; i <= classList.length; i++) {
      if (classList[i] == classN) {
         hasClass = true;
         break;
      }
   }
   return hasClass;
}//end HasClass

/**********************************/
/*** Button Mouseover Functions ***/
/**********************************/

function BtnHover(btn, img) {
   btn.src = img;
}//end BtnHover

function BtnUnHover(btn, img) {
   btn.src = img;
}//end BtnUnHover

/************************************
 Generic AJAX failure handler.
*************************************/
function AJAX_Failure(err,userContext,methodName) {
   var msg = "An unexpected error has occurred.\n\n";
   
   msg += "Error:  " + err.get_message() + "\n\n";
   
   //if (debugFlag) {
      msg += err.get_stackTrace() + "\n\n";
   //}
   
   msg += "If you continue to experience difficulties, please contact us at 1-888-537-1304.";

   alert(msg);
}//end AJAX_Failure

// Useful for debugging
function serialize(_obj)
{

   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
   {
      alert('gecko');
      return _obj.toSource();
   }

   // Other browsers must do it the hard way
   switch (typeof _obj)
   {
      // numbers, booleans, and functions are trivial:
      // just return the object itself since its default .toString()
      // gives us exactly what we want
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;

      // for JSON format, strings need to be wrapped in quotes
      case 'string':
         return '\'' + _obj + '\'';
         break;

      case 'object':
         var str;
         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined')
         {
            str = '[';
            var i, len = _obj.length;
            for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
            str += serialize(_obj[i]) + ']';
         }
         else
         {
            str = '{';
            var key;
            for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
            str = str.replace(/\,$/, '') + '}';
         }
         return str;
         break;

      default:
         return 'UNKNOWN';
         break;
   }
}//end serialize

/***************************/
/*** Keypress functions  ***/
/***************************/

// These all return true if keypress was the given key, false otherwise

function EnterKeyPressed(e) {
	return KeyPressed(13, e);
}//end EnterKeyPressed

function EscapeKeyPressed(e) {
	return KeyPressed(27, e);
}//end EscapeKeyPressed

function DeleteKeyPressed(e) {
	return (KeyPressed(46, e) || KeyPressed(46, e));
}//end DeleteKeyPressed

function BackspaceKeyPressed(e) {
	return KeyPressed(8, e);
}//end BackspaceKeyPressed

function TabKeyPressed(e) {
	return KeyPressed(9, e);
}//end TabKeyPressed

function LeftArrowKeyPressed(e) {
	return KeyPressed(37, e);
}//end LeftKeyPressed

function RightArrowKeyPressed(e) {
	return KeyPressed(39, e);
}//end RightKeyPressed

function KeyPressed(keyCode, e) {
	var key;
	if (window.event)
	{
		key = window.event.keyCode;  //IE
	}
	else
	{
		key = e.which;	//firefox
	}
	if (key == keyCode)
		return true;
	else 
		return false;	
}//end KeyPressed

/************************************
	function DetectBrowser

	Detect browser of the user
*************************************/
function DetectBrowser() {
	detect = navigator.userAgent.toLowerCase();
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	} else if (checkIt('safari')) browser = "Safari"
	else if (checkIt('omniweb')) browser = "OmniWeb"
	else if (checkIt('opera')) browser = "Opera"
	else if (checkIt('webtv')) browser = "WebTV"
	else if (checkIt('icab')) browser = "iCab"
	else if (checkIt('netscape')) browser = "Netscape Navigator"
	else if (checkIt('firefox/2')) browser = "FireFox 2"
	else if (checkIt('firefox')) browser = "FireFox"
	else if (checkIt('msie')) browser = "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	} else browser = "An unknown browser";
}//end DetectBrowser

/************************************
	function checkIt(string)

	Find instance of variable in string
*************************************/
function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}//end CheckIt
