 function showloader(div)
 {
 
    var cookie = getCookie('loader');
    
    if(cookie != '2')
    {
        setCookie('loader',1,3);
    }
    
    var browser=navigator.appName;
    
    //cant show in firefox!  back button bug.
    if (browser != "Netscape")
    {
        var loader;
        //alert(div)
        loader = document.getElementById(div);
        loader.style.visibility = "visible";
        loader.style.display = "block";
}

}

function ShowNone(radiobuttonlist) {
    //alert(radiobuttonlist);
    var rbl = document.getElementById("none_" + radiobuttonlist);
    rbl.style.visibility = "visible";

}

function ShowNoneBrowse(radiobuttonlist, warranty_holder) {
    //alert(radiobuttonlist);
    var rbl = document.getElementById("none_" + radiobuttonlist);
    rbl.style.visibility = "visible";

    // var holder = document.getElementById(warranty_holder);
    // holder.className = "ext_warr_3";
}


function hideme(div)
{
    var loader;
    loader = document.getElementById(div);
    loader.style.visibility = "hidden";
    loader.style.display = "none";
}

     function setCookie(c_name,value,expiredays)
	 {
		 var exdate=new Date();
		 exdate.setDate(exdate.getDate()+expiredays);
		 document.cookie=c_name+ "=" +escape(value)+
		 ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	 }

	 function getCookie(c_name)
	 {
		 if (document.cookie.length>0)
		   {
		   c_start=document.cookie.indexOf(c_name + "=");
		   if (c_start!=-1)
		     {
		     c_start=c_start + c_name.length+1;
		     c_end=document.cookie.indexOf(";",c_start);
		     if (c_end==-1) c_end=document.cookie.length;
		     return unescape(document.cookie.substring(c_start,c_end));
		     }
		   }
		 return "";
	 }
	 
	 function checkCookie()
	 {
	     var cookie = getCookie('loader');
	     //alert(cookie);
	     var loader;
	     loader = document.getElementById('TopBar1_search_loader');
    	 
	     if(cookie == '1')
	       {
	        alert("test1 " + cookie);
	        return;
	       }
	     else
	       {
	        loader.style.display = 'none';
	        alert("test2 " + cookie);
	        return;
	       }
	 }      

function openWindow(url)
{
	popupWin = window.open(url,'win','scrollbars,resizable,menubar,width=600,height=500')
} 

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

var ie = (navigator.appName.indexOf('Microsoft') != -1) ? true : false;
var ns = (navigator.appName.indexOf('Netscape') != -1) ? true : false;
var jamoke = 600;

var submitted = false;

function submitCheck(){

	if (submitted) {
	alert("Your payment is being processed. Please wait....");
	return false;
		}
		else {
		submitted = true;
		return true;
		}
	}


function printpage() {
window.print();  
}

function openWindow(url) {
          popupWin = window.open(url,'win','scrollbars,resizable,menubar,width=600,height=700')
        }

function pop(url) {
 	sealWin = window.open(url,"win",'toolbar=0,location=0,directories=0,status=0,menubar=1,scrollbars=1,resizable=1,width=700,height=450');
self.name = "mainWin"; 
}

function popSize(url, mwidth, mheight) {
	var rndNum = Math.floor(Math.random()*23);
        popup = window.open(url,'win'+rndNum,'left=' + ((screen.width-mwidth)/2) + ',top=' + ((screen.height-mheight)/2) + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=' + mwidth + ',height=' + mheight);
}

function openPyramatShipQuoteBox(theform) {
	var w = window.open('about:blank', "shipQuote",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=300,height=200');
        theform.target = "shipQuote";
	return true;
}

function popSizeScroll(url, mwidth, mheight) {
        popup = window.open(url,"win",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=' + mwidth + ',height=' + mheight);
}

function init(){
         //       define('address_type_name','string','Shipping Location',2,36);
                define('first_name','string','First Name',2,36);
                define('last_name','string','Last Name',2,36);
                define('address_1','string','Address',6,32);
                define('city','string','City',3,36);
                define('state','string','State',2,2);
                define('zip','num','Zip Code',5,10);
                define('phone_1','string','Phone Number',10,20);
                define('user_email','email','Email');

        }


function scream()
{
        alert(document.forms[1].order_payment_number.value);
}

function getDocHeight() {
  if (ie) return (document.body.scrollHeight > document.body.clientHeight) ? document.body.scrollHeight : document.body.clientHeight;
else if (ns) return (document.height > window.innerHeight) ? document.height : window.innerHeight;
   }


var menublock=new Array()
setgs = "Verdana;2;FFFF99;1;Verdana;1;FFFFFF;1;"
menublock[0]= setgs +
			 "Brands|#|;"+
                         "AT&T|/?page=shop/browse&category_id=46dfb535af92d12dc99529c40bb5e3ab|;"+
                         "Brother|test.html|;"+
                         "Engenius|/?page=shop/browse&category_id=fc0e040427b5a2d124b13c554ccff536|;"+
                         "Nortel|/?page=shop/browse&category_id=4371db2713400dd8d0aad2fb74f040c6|;"+
                      "On-Hold Plus|/?page=shop/browse&category_id=426ba283f752e38ca6df91dc84777c11|;"+
			 "Panasonic|/?page=shop/browse&category_id=6e4295be69c8420810f72d019890fd54|;"+
                         "Plantronics|/?page=shop/browse&category_id=15b24e7273b2889edb06c4ee1671890a|;"+
                         "Polycom|/?page=shop/browse&category_id=8b4439ca83d10ed01ce10d3aa281d303|;"+
                         "Siemens|/?page=shop/browse&category_id=4b07e6e635732d45680c62b99f0f57c9|;"+
                         "Sony|/?page=shop/browse&category_id=3e74ef2e5927dcf8f498cef158f58175|;"+
                         "Uniden|/?page=shop/browse&category_id=99664282173d37e8fbbfa937588b74b7|;"+
                         "V-Tech|/?page=shop/browse&category_id=7dbf09607b0176bc686958f506649336|;"



			 "Brands|#|;"+
			 "AT&T|test.html|;"+
			 "Brother|test.html|;"+
			 "Engenius|test.html|;"+
			 "Nortel|test.html|;"+
			 "On-Hold Plus|test.html|;"+
			 "Panasonic|test.html|;"+
			 "Plantronics|test.html|;"+
			 "Polycom|test.html|;"+
			 "Siemens|test.html|;"+
			 "Sony|test.html|;"+
			 "Uniden|test.html|;"+
			 "V-Tech|test.html|;"	 
		 
menublock[1]= setgs +
			 "Phones|#|;"+
			 "Cordless|test.html|;"+
			 "Corded|test.html|;"+
			 "Conference|test.html|;"+
			 "Video Conference|test.html|;"+
			 "Fax Machines|test.html|;"+
			 "Novelty Phones|test.html|;"+
			 "Special Needs|test.html|;"+
			 "Phones with Rebate|test.html|;"+
			 "Refurbished Phones|test.html|;"

menublock[2]= setgs +
			 "Accessories|#|;"+
			 "Headsets|test.html|;"+
			 "Batteries|test.html|;"+
			 "On-Hold Plus|test.html|;"+
			 "Palm-Link 2-Ways|test.html|;"+
			 "Antennas|test.html|;"+
			 "Answering Machines|test.html|;"+
			 "Caller ID|test.html|;"+
			 "Amplifiers|test.html|;"+
			 "Runt & 24V Scooters|test.html|;"	
			 
	 
var menusplit
var urlsplit
var font_weight_main
var font_weight_sub
			 
var showsubmenus=new Array()
for (i=0;i<=menublock.length-1;i++) {
	showsubmenus[i]=-1
}

function openandclose(visi) {
	//alert(visi)
	for (i=0;i<=menublock.length-1;i++) {
		if (i != visi) showsubmenus[i]=-1
	}
	showsubmenus[visi]=(-1)*showsubmenus[visi]

	var menucontent=""

	for (i=0;i<=menublock.length-1;i++) {
		menusplit=menublock[i].split(";")
		urlsplit=menusplit[8].split("|")
		if (menusplit[3]==1) {font_weight_main="<b>"}
		if (menusplit[3]==0) {font_weight_main=""}
		if (menusplit[7]==1) {font_weight_sub="&nbsp;"}
		if (menusplit[7]==0) {font_weight_sub=""}

menucontent+=font_weight_main+"<a href='javascript:openandclose("+i+")'><font style='font-size:13px' face="+menusplit[0]+" color="+menusplit[2]+" size="+menusplit[1]+">"+urlsplit[0]+"</font></a></b><br>"
		if (showsubmenus[i]==1) {
			for (ii=9;ii<=menusplit.length-1;ii++) {
				urlsplit=menusplit[ii].split("|")
    			menucontent+=font_weight_sub+"<a href="+urlsplit[1]+" target="+urlsplit[2]+"><font style='font-size:12px' face="+menusplit[4]+" color="+menusplit[6]+" size="+menusplit[5]+">"+urlsplit[0]+"</font></a><br>"
			}
		}
	}
	if (document.all) {
		menu.innerHTML=menucontent
	}
	if (document.layers) {
		document.menu.document.write(menucontent)
		document.menu.document.close()
	}
}

function assign() 

{

var ccard = window.document.checkout.order_payment_number.value;
window.document.checkout.x_Card_Num.value = ccard;
var cyear = window.document.checkout.order_payment_expire_year.options[window.document.checkout.order_payment_expire_year.selectedIndex].value;
var cmonth = window.document.checkout.order_payment_expire_month.options[window.document.checkout.order_payment_expire_month.selectedIndex].value;
window.document.checkout.x_Exp_Date.value = cmonth + "/" + cyear;

}

/**
 * Author: Lawrence So
 * Date: 8/25/2005
 * Used for "Finder Box". Dropdown menu in HTML must use 
 * "finderDropdown1" or "finderDropdown2" as <select> name.
 */
function finderGo(findBy)
{
	var selectedIndex;
	var newUrl;
	var redirect = false;
    
	if (findBy == "finderDropdown1")
	{
	    var dropdown = document.getElementById("finderDropdown1")
		selectedIndex = dropdown.selectedIndex;
		//selectedIndex = document.finder.finderDropdown1.selectedIndex;

		if (selectedIndex != 0)
		{
			newUrl = dropdown.options[selectedIndex].value;
			//newUrl = document.finder.finderDropdown1.options[selectedIndex].value;
			redirect = true;
		}
	}
	else if (findBy == "finderDropdown2")
	{
		var dropdown = document.getElementById("finderDropdown2")
		selectedIndex = dropdown.selectedIndex;
		//selectedIndex = document.finder.finderDropdown2.selectedIndex;

		if (selectedIndex != 0)
		{
			newUrl = dropdown.options[selectedIndex].value;
			//newUrl = document.finder.finderDropdown2.options[selectedIndex].value;
			redirect = true;
		}
	}

	if (redirect)
	{
		window.location.href = newUrl;
	}
}




// SOURCE: http://www.nsftools.com/misc/SearchAndHighlight.htm

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
	// the highlightStartTag and highlightEndTag parameters are optional
	if ((!highlightStartTag) || (!highlightEndTag)) {
		highlightStartTag = '<font class="finder_highlight">';
		highlightEndTag = '</font>';
	}

	// find all occurrences of the search term in the given text,
	// and add some "highlight" tags to them (we're not using a
	// regular expression search, because we want to filter out
	// matches that occur within HTML tags and script blocks, so
	// we have to do a little extra validation)
	var newText = "";
	var i = -1;
	var lcSearchTerm = searchTerm.toLowerCase();
	var lcBodyText = bodyText.toLowerCase();

	while (bodyText.length > 0) {
		i = lcBodyText.indexOf(lcSearchTerm, i+1);

		// if bodyText does not contain search term
		if (i < 0) {
			newText += bodyText;
			bodyText = "";
		} else { // if bodyText does contain search term
			numOccurrences++;
			
			// skip anything inside an HTML tag
			if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
				// skip anything inside a <script> block
					if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
						newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
						bodyText = bodyText.substr(i + searchTerm.length); // increments
						lcBodyText = bodyText.toLowerCase(); // controls highlighting??
						i = -1;
					}
			}
		}
	}

	return newText;
}

var originalText = "";
var numOccurrences = 0;

/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
	// if the treatAsPhrase parameter is true, then we should search for
	// the entire phrase that was entered; otherwise, we will split the
	// search string so that each word is searched for and highlighted
	// individually

	if (treatAsPhrase) {
		searchArray = [searchText];
	} else {
		searchArray = searchText.split(" ");
	}

	if (!document.body || typeof(document.body.innerHTML) == "undefined") {
		if (warnOnFailure) {
			alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
		}

		return false;
	}

	var bodyText = document.body.innerHTML;

	// Save original text for resetting later (Law 8/31/2005)
	if (originalText == "") {
		originalText = bodyText;
	}

	// Reset highlighting (Law 8/31/2005)
	if (originalText != "") {
		bodyText = originalText;
	}
	
	numOccurrences = 0;

	for (var i = 0; i < searchArray.length; i++) {
		bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
	}
	
	if (numOccurrences == 0) {
		alert('Sorry, no results found for \"' + searchText + '\".');
	}

	document.body.innerHTML = bodyText;
	return true;
}

function searchPrompt2(searchText, treatAsPhrase, textColor, bgColor)
{
	document.getElementById("t1").value = "";
	
	// This function prompts the user for any words that should
	// be highlighted on this web page

	// we can optionally use our own highlight tag values
	if ((!textColor) || (!bgColor)) {
		highlightStartTag = "";
		highlightEndTag = "";
	} else {
		highlightStartTag = '<font class="finder_highlight">';
		highlightEndTag = '</font>';
	}

	if (!searchText)  {
		alert("No search terms were entered.");
		return false;
	}


	/** Start Page Jump Code **/
	// SOURCE: http://www.javascripter.net/faq/searchin.htm
	var str = searchText;
	var TRange=null

	if (parseInt(navigator.appVersion) < 4) return;
	
	var strFound;
	
	if (navigator.appName == "Netscape") {
		// NAVIGATOR-SPECIFIC CODE

		strFound=self.find(str);

		if (!strFound) {
			strFound=self.find(str,0,1)
			while (self.find(str,0,1)) continue
		}
	}
	
	if (navigator.appName.indexOf("Microsoft")!=-1) {
		// EXPLORER-SPECIFIC CODE

		if (TRange!=null) {
			TRange.collapse(false)
			strFound=TRange.findText(str)
			if (strFound) TRange.select()
		}
		
		if (TRange==null || strFound==0) {
			TRange=self.document.body.createTextRange()
			strFound=TRange.findText(str)
		
			if (strFound) TRange.select()
		}
	}
	window.scrollBy(0,200);
	//if (!strFound) alert ("String '"+str+"' not found!")
	
	/** End Page Jump Code **/




	return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}




/** Script from HTMLHelpCentral.com - visit for tutorials, scripts, helpful forums and more! **/
function winBRopen(theURL, Name, popW, popH, scroll) {
	var winleft = (screen.width - popW) / 2;
	var winUp = (screen.height - popH) / 2;
	
	winProp = 'width='+popW+',height='+popH+',left='+winleft+',top='+winUp+',scrollbars='+scroll+',resizable'
	
	Win = window.open(theURL, Name, winProp)
	
	if (parseInt(navigator.appVersion) >= 4) {
		Win.window.focus();
	}
}


//-------------------------Start of code taken from the ImageGalleryFly Usercontrol-------------------------------------------------
function swapFlyGallery(hid, imgId) {
    var url = document.getElementById(hid).value;
    var image = document.getElementById(imgId);

    image.src = url;
}
function swapGalleryFull(hid, imgId) {
    var url = document.getElementById(hid).value;
    var image = document.getElementById(imgId);

    image.src = url;
}

function swapGallery(hidID) {
    var GalleryList = document.getElementById("GalleryList");
    var hidInput = document.getElementById(hidID);

    if (hidInput) {
        GalleryList.innerHTML = hidInput.innerHTML;
    }
    else {
        GalleryList.innerHTML = ""
    }
}
//-------------------------End of code taken from the ImageGalleryFly Usercontrol-------------------------------------------------
/***********************************************
* Function ValidateString : Used to validate user inputs to prevent user from getting 
* validate Request error mesages. 
***********************************************/
function ValidateString(oSrc, args) {
    var re = new RegExp("&#|<!|<\/|<[A-Za-z]");
    if (args.Value.match(re)) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}


function setStockLinks() {

    var emp = getCookie("emp");

    if (emp != "") {
        var form = document.getElementById(document.forms[0].id);
        for (i = 0; i < form.elements.length; i++) {
            if (form.elements[i].type == "hidden") {
                if (form.elements[i].id.indexOf("linkdata") != -1) {
                    var hiddenField = document.getElementById(form.elements[i].id);
                    //alert(hiddenField);
                    var values = new Array();
                    values = hiddenField.value.split("#");
                    //values[0] = container ID
                    //values[1] = store id
                    //values[2] = sub store id
                    //values[3] = category id
                    //values[4] = search term

                    var span = document.getElementById('a_' + values[0]);

                    if (span) {
                        if (values[4] != 'blank') {
                            span.innerHTML = '<br /><a href="https://admin.gogotech.com/Inventory/CatalogItemStockDisplay.aspx?cid=' + values[0] + '&ssid=' + values[2] + '&sid=' + values[1] + '&catid=' + values[3] + '&search_term=' + values[4] + '" target="_blank">Extra Info For Sales Agent.</a>';
                        } else {
                            span.innerHTML = '<br /><a href="https://admin.gogotech.com/Inventory/CatalogItemStockDisplay.aspx?cid=' + values[0] + '&ssid=' + values[2] + '&sid=' + values[1] + '&catid=' + values[3] + '" target="_blank">Extra Info For Sales Agent.</a>';
                        }
                    }
                }
            }
        }
    }

}

function OpenSSL() {
    window.open('http://www.trustlogo.com/ttb_searcher/trustlogo?v_querytype=W&v_shortname=SC2&v_search=isave.com&x=6&y=5', 'ComodoSSL', 'width=500,height=600');
}



function showEmptyCart() {
    var emptyCart = getParam("emptyCart");
    var emptyCartBanner = document.getElementById("trEmptyCart");

    if (emptyCart == "1") {
        emptyCartBanner.style.display = 'block';
    } else {
        emptyCartBanner.style.display = 'none';
    }

}


function getParam(arg) {
    /******************************************************************************
    * Bjorn Williams 07/13/2010 
    * Commented the code below as there was an issue whenever the URL keywords contain any words that 
    * where treated as URL parameter.  
    *****************************************************************************/
    var hashUrlParams = jsGetUrlParamsArray(window.location.toString().toLowerCase())
    var ParamValue = "";
    arg = arg.toLowerCase();
    if (hashUrlParams[arg] != undefined) {
        ParamValue = hashUrlParams[arg];
    }
    return ParamValue;

    //    var q = "" + window.location;
    //    var c;
    //    q = q.toLowerCase();
    //    arg = arg.toLowerCase();
    //    if (q.indexOf(arg) >= 0) {
    //        var pntr = q.indexOf(arg) + arg.length + 1;
    //        if (q.indexOf(arg, pntr) >= 0) {
    //            return q.substring(pntr, q.indexOf(arg, pntr));
    //        }
    //        else {
    //            return q.substring(pntr, q.length);
    //        }
    //    }
    //    else {
    //        return "";
    //    }
}
/*********************************************************************
* Returns associative array of name value pairs where the key is the
* URL parameter name and the value is the value associated with that
* parameter.
*
* NOTE: This function only retrieves URL parameters, NOT HTTP POST
* variables. Also, URL parameters consist of everything between the
* "?" and "#" symbols. URL parameters using SEO friendly formats
* would NOT fit under this criteria and thus would not be recognized
* as URL parameters by this function.
*********************************************************************/
function jsGetUrlParamsArray(strCurrentUrl) {
    var arrNamePairs = new Array();
    var hashUrlParams = new Array(); //note: it is possible that some url parameters in this array will have the value of "undefined"
    var strQueryString = "";
    var intQuestionMarkIndex = strCurrentUrl.indexOf("?");

    if (intQuestionMarkIndex != -1) {
        strQueryString = strCurrentUrl.substring(intQuestionMarkIndex + 1, strCurrentUrl.length);
    } else {
        return hashUrlParams;
    }

    var intUrlAnchorIndex = strQueryString.indexOf("#");
    if (intUrlAnchorIndex != -1) {
        strQueryString = strQueryString.substring(0, intUrlAnchorIndex);
    }

    if (strQueryString == "") {
        return hashUrlParams;
    } else {
        arrNamePairs = strQueryString.split("&");
        for (var i = 0; i < arrNamePairs.length; i++) {
            arrTmpCurrentRow = arrNamePairs[i].split("=");
            hashUrlParams[arrTmpCurrentRow[0]] = arrTmpCurrentRow[1];
        }

        return hashUrlParams;
    }
}


/*****************************
*   ajax pop up functions    *
*****************************/

var finished = 0;
function fetchPopUpData(container_id, link_text) {
    //    var loading = document.getElementById('loading');
    //    loading.style.display = 'block';

    if (finished == 0) {
        Sys.Net.WebRequestManager.add_invokingRequest(on_invokingRequest);
        ShipmentCalculator.buildPopUpData(container_id, link_text, populatePopUp, onError);
        Sys.Net.WebRequestManager.remove_invokingRequest(on_invokingRequest);
        finished = 1;
    }
    else {
        abortExecutor.abort();
        Sys.Net.WebRequestManager.add_invokingRequest(on_invokingRequest);
        ShipmentCalculator.buildPopUpData(container_id, link_text, populatePopUp, onError);
        Sys.Net.WebRequestManager.remove_invokingRequest(on_invokingRequest);
    }
}

function onError(poop) {

}

function on_invokingRequest(executor, eventArgs) {
    var currentRequest = eventArgs.get_webRequest();
    abortExecutor = eventArgs.get_webRequest().get_executor();
}

var gblCatalogItemInfo;

function populatePopUp(catalogItemInfo) {
    gblCatalogItemInfo = catalogItemInfo;
    var div = document.getElementById('CatalogItemPopUp');
    div.style.display = "";

    var x;
    var ie = document.all;
    var ns6 = document.getElementById && !document.all;

    if (ie) {
        x = ((document.body.offsetWidth - 698) / 2);
    } else if (ns6) {
        x = ((window.innerWidth - 698) / 2);
    } else {
        x = ((window.innerWidth - 698) / 2);
    }

    var scrollTop = document.body.scrollTop;
    if (scrollTop == 0) {
        if (window.pageYOffset)
            scrollTop = window.pageYOffset;
        else
            scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }

    div.style.top = scrollTop + 5 + "px";

    //alert(x);
    div.style.left = x + "px";

    var greyout = document.getElementById("greyout");
    greyout.style.height = document.body.scrollHeight + "px";
    greyout.style.display = "";

    var img = document.getElementById("CatalogItemPopUpImage");
    var gallery = document.getElementById("CatalogItemPopUpGallery");
    var tagline = document.getElementById("CatalogItemPopUpTagLine");
    var description = document.getElementById("CatalogItemPopUpDescription");
    var addToCart = document.getElementById("CatalogItemPopUpAddToCart");
    var priceHolder = document.getElementById("CatalogItemPopUpPriceHolder");
    var linkText = document.getElementById("CatalogItemPopUpLinkText");

    var imageStr = "";
    var parts = Array();

    //Akil 6/16/2011: if the assignment id is -1 then there are NO store override images.
    if (catalogItemInfo[0].store_image_assignment_id == -1) {
        img.src = "/images/CatalogItemVariation/" + catalogItemInfo[0].catalog_item_id + "/" + catalogItemInfo[0].catalogItemImages[1];
    } else {
        imageStr = catalogItemInfo[0].catalogItemImages[1];
        parts = Array();
        parts = imageStr.split("#%#");

        //Akil 6/16/2011: The code below tries to figure out if image 2 has a store override.
        if (parts[1]) {
            img.src = "/images/CatalogItemImageStore/" + catalogItemInfo[0].store_image_assignment_id + "/" + parts[0];
        } else {
            img.src = "/images/CatalogItemVariation/" + catalogItemInfo[0].catalog_item_id + "/" + catalogItemInfo[0].catalogItemImages[1];
        }
    }


    //Akil 6/20/2011: if the assignment id is -1 then there are NO store override images.
    if (catalogItemInfo[0].store_image_assignment_id == -1) {
        imageStr = "/images/CatalogItemVariation/" + catalogItemInfo[0].catalog_item_id + "/" + catalogItemInfo[0].catalogItemImages[0];
    } else {
        imageStr = catalogItemInfo[0].catalogItemImages[0];
        parts = imageStr.split("#%#");

        //Akil 6/20/2011: The code below tries to figure out if image 1  has a store override.
        if (parts[1]) {
            imageStr = "/images/CatalogItemImageStore/" + catalogItemInfo[0].store_image_assignment_id + "/" + parts[0];
        } else {
            imageStr = "/images/CatalogItemVariation/" + catalogItemInfo[0].catalog_item_id + "/" + catalogItemInfo[0].catalogItemImages[0];
        }
    }

    //Akil 6/16/2011: check the container override if its empty then build the description from the correct fields.
    if (catalogItemInfo[0].containerDescription[6] == "") {
        //Akil 6/16/2011: populate the tagline.
        var descStr = "";
        tagline.innerHTML = catalogItemInfo[0].containerDescription[0];
        var featuresStr = "";

        featuresStr = buildFeatures(catalogItemInfo[0].features);
        descStr = catalogItemInfo[0].modelDescription[5] + catalogItemInfo[0].modelDescription[0] + featuresStr + catalogItemInfo[0].modelDescription[1] + catalogItemInfo[0].containerDescription[1];
        description.innerHTML = descStr;
    } else { //Akil 6/16/2011: Override container description.
        description.innerHTML = catalogItemInfo[0].containerDescription[6];
    }

    priceHolder.innerHTML = '<div class="popUpPriceInner"><p class="list_price">Regular Price: <span class="price">' + catalogItemInfo[0].list_price + '</span></p><p class="Purchase_Price_Heading">$' + catalogItemInfo[0].total_amt + '</p></div>';
    var onclickString = "window.location.href ='/Shoppingcart/ShoppingCart.aspx?CMD=run&ctid=" + catalogItemInfo[0].catalog_item_id + "&sbid=" + catalogItemInfo[0].sub_store_id + "&ci=" + catalogItemInfo[0].ci + "'";
    addToCart.setAttribute('onclick', onclickString);
    //alert(catalogItemInfo[0].store_image_assignment_id + " - " + catalogItemInfo[0].catalog_item_id + " - " + catalogItemInfo[0].model_id);


    var t = "";

    if (catalogItemInfo[0].galleryImages[0] != "NONE") {
        gallery.innerHTML = buildGallery(catalogItemInfo[0].galleryImages, imageStr, img.src, catalogItemInfo[0].catalog_item_id)
    } else {
        gallery.innerHTML = "";
    }


    linkText.innerHTML = catalogItemInfo[0].linkText;

    if (catalogItemInfo.length > 1) { //Multipile Catalog Items in Container.
        description.innerHTML = description.innerHTML + '<div class="popUpCatalogItemAttribute">Choose ' + catalogItemInfo[0].attribute_name_string + ':<br />';
        description.appendChild(buildDropDown(catalogItemInfo, catalogItemInfo[0].catalog_item_id));
        description.innerHTML = description.innerHTML + '</div>';
    }

    finished = 0;
}

function buildDropDown(catalogItemData, catalog_item_id) {
    var dd = document.createElement("select");
    dd.name = "CatalogItems";
    dd.id = "popupCatalogItems";
    var onchangeString = "swapPopupCatalogItem('" + dd.id + "');";
    dd.setAttribute('onchange', onchangeString);

    for (c in catalogItemData) {
        if (catalogItemData[c].catalog_item_id == catalog_item_id) {
            dd.options[c] = new Option(catalogItemData[c].attribute_value_string, catalogItemData[c].catalog_item_id, true, true);
        }
        else {
            dd.options[c] = new Option(catalogItemData[c].attribute_value_string, catalogItemData[c].catalog_item_id, false, false);
        }

    }

    return dd;
}

function swapPopupCatalogItem(dropdownId) {
    var dd = document.getElementById(dropdownId);
    //alert(dd.options[0].value);
    //alert(dd.options[0].value);
    //alert(dd.options[1].value);
    //alert(dd.options[dd.selectedIndex].value);
    for (c in gblCatalogItemInfo) {
        if (gblCatalogItemInfo[c].catalog_item_id == dd.options[dd.selectedIndex].value) {
            rePopulatePopup(gblCatalogItemInfo[c]);
            break;
        }
    }
}

function rePopulatePopup(catalogItemInfo) {

    var div = document.getElementById('CatalogItemPopUp');
    var img = document.getElementById("CatalogItemPopUpImage");
    var gallery = document.getElementById("CatalogItemPopUpGallery");
    var tagline = document.getElementById("CatalogItemPopUpTagLine");
    var description = document.getElementById("CatalogItemPopUpDescription");
    var addToCart = document.getElementById("CatalogItemPopUpAddToCart");
    var priceHolder = document.getElementById("CatalogItemPopUpPriceHolder");
    var linkText = document.getElementById("CatalogItemPopUpLinkText");

    var imageStr = "";
    var parts = Array();

    //Akil 6/16/2011: if the assignment id is -1 then there are NO store override images.
    if (catalogItemInfo.store_image_assignment_id == -1) {
        img.src = "/images/CatalogItemVariation/" + catalogItemInfo.catalog_item_id + "/" + catalogItemInfo.catalogItemImages[1];
    } else {
        imageStr = catalogItemInfo.catalogItemImages[1];
        parts = Array();
        parts = imageStr.split("#%#");

        //Akil 6/16/2011: The code below tries to figure out if image 2 has a store override.
        if (parts[1]) {
            img.src = "/images/CatalogItemImageStore/" + catalogItemInfo.store_image_assignment_id + "/" + parts[0];
        } else {
            img.src = "/images/CatalogItemVariation/" + catalogItemInfo.catalog_item_id + "/" + catalogItemInfo.catalogItemImages[1];
        }
    }


    //Akil 6/20/2011: if the assignment id is -1 then there are NO store override images.
    if (catalogItemInfo.store_image_assignment_id == -1) {
        imageStr = "/images/CatalogItemVariation/" + catalogItemInfo.catalog_item_id + "/" + catalogItemInfo.catalogItemImages[0];
    } else {
        imageStr = catalogItemInfo.catalogItemImages[0];
        parts = imageStr.split("#%#");

        //Akil 6/20/2011: The code below tries to figure out if image 1  has a store override.
        if (parts[1]) {
            imageStr = "/images/CatalogItemImageStore/" + catalogItemInfo.store_image_assignment_id + "/" + parts[0];
        } else {
            imageStr = "/images/CatalogItemVariation/" + catalogItemInfo.catalog_item_id + "/" + catalogItemInfo.catalogItemImages[0];
        }
    }

    //Akil 6/16/2011: check the container override if its empty then build the description from the correct fields.
    if (catalogItemInfo.containerDescription[6] == "") {
        //Akil 6/16/2011: populate the tagline.
        var descStr = "";
        tagline.innerHTML = catalogItemInfo.containerDescription[0];
        var featuresStr = "";

        featuresStr = buildFeatures(catalogItemInfo.features);
        descStr = catalogItemInfo.modelDescription[5] + catalogItemInfo.modelDescription[0] + featuresStr + catalogItemInfo.modelDescription[1] + catalogItemInfo.containerDescription[1];
        description.innerHTML = descStr;
    } else { //Akil 6/16/2011: Override container description.
        description.innerHTML = catalogItemInfo.containerDescription[6];
    }

    priceHolder.innerHTML = '<div class="popUpPriceInner"><p class="list_price">Regular Price: <span class="price">' + catalogItemInfo.list_price + '</span></p><p class="Purchase_Price_Heading">$' + catalogItemInfo.total_amt + '</p></div>';
    var onclickString = "window.location.href ='/Shoppingcart/ShoppingCart.aspx?CMD=run&ctid=" + catalogItemInfo.catalog_item_id + "&sbid=" + catalogItemInfo.sub_store_id + "&ci=" + catalogItemInfo.ci + "'";
    addToCart.setAttribute('onclick', onclickString);
    //alert(catalogItemInfo[0].store_image_assignment_id + " - " + catalogItemInfo[0].catalog_item_id + " - " + catalogItemInfo[0].model_id);


    var t = "";

    if (catalogItemInfo.galleryImages[0] != "NONE") {
        gallery.innerHTML = buildGallery(catalogItemInfo.galleryImages, imageStr, img.src, catalogItemInfo.catalog_item_id)
    }


    linkText.innerHTML = catalogItemInfo.linkText;

    if (gblCatalogItemInfo.length > 1) { //Multipile Catalog Items in Container.
        description.innerHTML = description.innerHTML + '<div class="popUpCatalogItemAttribute">Choose ' + catalogItemInfo.attribute_name_string + ':<br />';
        description.appendChild(buildDropDown(gblCatalogItemInfo, catalogItemInfo.catalog_item_id));
        description.innerHTML = description.innerHTML + '</div>';
    }

}

function buildGallery(galleryData, mainImage, mainImage2, catalog_item_id) {
    var galleryHTML = "";
    galleryHTML = '<ul id="CatalogItemPopUpGalleryList">';
    galleryHTML += '<li onmouseover="swapCatalogItemPopUpGallery(\'' + mainImage2 + '\')" onclick="swapCatalogItemPopUpGallery(\'' + mainImage2 + '\')"><div class="popgallcent1"><div class="popgallcent2"><img src="' + getThumbNail(mainImage, "m") + '"></div></div></li>';

    var image = "";
    for (i = 0; i <= galleryData.length; i++) {
        //alert(galleryData[i]);
        if (i < 2) {
            if (galleryData[i] != "NONE") {
                //galleryData[i] = "/images/CatalogItemVariation/" + catalog_item_id + "/" + galleryData[i];

                image = "/images/CatalogItemVariation/" + catalog_item_id + "/" + galleryData[i];
                galleryHTML += '<li onmouseover="swapCatalogItemPopUpGallery(\'' + getBrowseGalleryImage(image, "g") + '\')" onclick="swapCatalogItemPopUpGallery(\'' + getBrowseGalleryImage(image, "g") + '\')"><div class="popgallcent1"><div class="popgallcent2"><img src="' + getThumbNail(image, "g") + '"></div></div></li>';
            }
        }
    }

    galleryHTML += "</ul>";

    return galleryHTML;
}

function swapCatalogItemPopUpGallery(imgSrc) {
    var img = document.getElementById("CatalogItemPopUpImage");
    img.src = imgSrc;
}


function getThumbNail(imageSrc, type) {
    if (type == "m") {
        imageSrc = imageSrc.replace("-img1.", "-img1_thumb1.");
    } else {
        imageSrc = imageSrc.replace(".jpg", "_thumb1.jpg");
        imageSrc = imageSrc.replace(".png", "_thumb1.png");
        imageSrc = imageSrc.replace(".gif", "_thumb1.gif");
        imageSrc = imageSrc.replace(".jpeg", "_thumb1.jpeg");
        imageSrc = imageSrc.replace(".JPEG", "_thumb1.JPEG");
        imageSrc = imageSrc.replace(".JPG", "_thumb1.JPG");
        imageSrc = imageSrc.replace(".PNG", "_thumb1.PNG");
        imageSrc = imageSrc.replace(".GIF", "_thumb1.GIF");
    }

    return imageSrc;
}


function getBrowseGalleryImage(imageSrc, type) {
    if (type == "m") {
        imageSrc = imageSrc.replace("-img1.", "-img1_thumb1.");
    } else {
        imageSrc = imageSrc.replace(".jpg", "_250X220.jpg");
        imageSrc = imageSrc.replace(".png", "_250X220.png");
        imageSrc = imageSrc.replace(".gif", "_250X220.gif");
        imageSrc = imageSrc.replace(".jpeg", "_250X220.jpeg");
        imageSrc = imageSrc.replace(".JPEG", "_250X220.JPEG");
        imageSrc = imageSrc.replace(".JPG", "_250X220.JPG");
        imageSrc = imageSrc.replace(".PNG", "_250X220.PNG");
        imageSrc = imageSrc.replace(".GIF", "_250X220.GIF");
    }

    return imageSrc;
}

function buildFeatures(features) {
    var featuresStr = "";
    var f = "";
    for (f in features) {
        featuresStr = featuresStr + "<li>" + features[f] + "</li>";
    }

    featuresStr = featuresStr + "<br />"

    return featuresStr;
}

function closePopUps() {
    var catalogItemPopUp = document.getElementById('CatalogItemPopUp');
    var viewAllPopUp = document.getElementById('view_all_popup');
    var greyout = document.getElementById("greyout");
    
    if (viewAllPopUp) {
        viewAllPopUp.style.display = "none";
    }
    if (catalogItemPopUp) {
        catalogItemPopUp.style.display = "none";
    }
    
    greyout.style.display = "none";

}


function showDD() {
    //var divToHide = document.getElementById(div_id);
    //divToHide.style.display = "none";

    // Show Quantity Drop Downs
    var checkoutButton = document.getElementById('cart_button_widget');
    if (checkoutButton) { checkoutButton.style.visibility = "visible"; }
    var form = document.getElementById(document.forms[0].id);
    for (i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == "select-one") {
            var dropdown = document.getElementById(form.elements[i].getAttribute("id"));
            dropdown.style.visibility = "visible";
        }
    }
}

