var popWindow = null;
var InDistributorDashboard = false;
var InVirtualSite = false;
var SearchType = "product";
var tabCount = 8;

var xmlHttpReq;
if (window.XMLHttpRequest) { xmlHttpReq = new XMLHttpRequest(); }
else if (window.ActiveXObject) { xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); }

function onload_A4R(showPopup,LoggedInCartID){
	//deleteCookie('LoggedInCartID', '/', '');
	if(LoggedInCartID != ''){
		//alert("set: "+LoggedInCartID);
		setCookie('LoggedInCartID', LoggedInCartID, '', '/', '', '');
	}
	//alert("get: "+getCookie('LoggedInCartID'));
	
	initializeSearch();
	if(showPopup){
		Popup_Home();
	}
}

function onload_VirtualSite(isSearchType){
	InVirtualSite = true;
	if(location.host == 'localhost' || location.host.indexOf("iframe.ryan") == 0){
		iFrameCheck();
	}
	SearchType = isSearchType;
	initializeSearch();
}


function onload_DistributorDashboard(isInDistributorDashboard,isSearchType){
	SearchType = isSearchType;
	if(isInDistributorDashboard == "True"){
		InDistributorDashboard = true;
	}
	else{
		InDistributorDashboard = false;
	}
	if(InDistributorDashboard){
		initializeSearch();
	}
}

function getPreferredPopup(linkref,textcontainer) {
    // requires jQuery and qTip
    $(linkref).qtip({
        content: {
            text: getElement(textcontainer).innerHTML,
            prerender: false
        },
        show: 'mouseover',
        hide: { fixed: true, delay: 1000 },
        style: {
            width: 156,
            padding: 5,
            background: '#ffffff',
            color: '#333333',
            border: {
                width: 1,
                radius: 0,
                color: '#FF6937'
            },
            tip: 'leftMiddle',
            name: 'light' // Inherit the rest of the attributes from the preset dark style
        },
        position: {
            corner: {
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            }
        }
    })
}

function getRequestInfoMessagePopup(linkref,textcontainer){
    // requires jQuery and qTip
    $(linkref).qtip({
        content: {
            text: getElement(textcontainer).innerHTML,
            prerender: false
        },
        show: 'mouseover',
        hide: { fixed: true, delay: 1000 },
        style: {
            width: 200,
            padding: 5,
            background: '#ffffff',
            color: '#333333',
            border: {
                width: 1,
                radius: 0,
                color: '#FF6937'
            },
            tip: 'leftTop',
            name: 'light' // Inherit the rest of the attributes from the preset dark style
        },
        position: {
            corner: {
                target: 'rightTop',
                tooltip: 'leftTop'
            }
        }
    })
}

function iFrameCheck(){
	
	var inIframe = false;
	
	try{
		parentlocation = parent.location + '';
		if(parentlocation == undefined){
			inIframe = true;
		}
	}
	catch(err){
		inIframe = true;
	}
	
	var ThisDomain = location.host;
	if(ThisDomain == "localhost"){ ThisDomain = getQuerystring("sitedomain"); }
	
	var ThisDirectory = '';
	
	var iFrameURL = 'specpage_iframe='+escape(window.location.toString());

	var SiteIntegrationURL;
	
	var url = "/ajax_GetSiteIntegrationURL.asp";
	
	if(!inIframe && ThisDomain.indexOf("iframe.") == 0){
		
		if(xmlHttpReq) {
			
			if (xmlHttpReq.readyState != 0){
				xmlHttpReq.abort();
			}
			
			xmlHttpReq.open("GET", url, true);
			xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlHttpReq.onreadystatechange = function() {
				if(xmlHttpReq.readyState == 4 || xmlHttpReq.readyState=="complete") {
					
					SiteIntegrationURL = xmlHttpReq.responseText + '';
					
					if(SiteIntegrationURL != ''){
						if(SiteIntegrationURL.indexOf('http') < 0){
							SiteIntegrationURL = "http://" + SiteIntegrationURL;
						}
						if(iFrameURL != ''){
							if(SiteIntegrationURL.indexOf('?') >= 0){
								iFrameURL = '&' + iFrameURL;
							}
							else{
								iFrameURL = '?' + iFrameURL;
							}
						}
						window.location = SiteIntegrationURL + iFrameURL;
					}
					
				}
			}
			xmlHttpReq.send("");
		}
		
	}
	
}

function openFirstTab() {

	closeAllTabs();

	var i;
	var o1 = null;
	var o2 = null;
	
	for(i=0;i<=tabCount;i++) {
		
		if(document.all) {
			o1 = document.all("tabBtn"+i);
			o2 = document.all("tabPane"+i);
		}
		else if(document.getElementById) {
			o1 = document.getElementById("tabBtn"+i);
			o2 = document.getElementById("tabPane"+i);
		}

		if(o1!=null && o2!=null) {

		    if (o1.style.display != "none") {
		        o1.className = o1.className.replace("Off", "On");
				o1.style.display = ""
				o2.style.display = "";
				i = tabCount+1;
			}
			else {
			    o1.className = o1.className.replace("On", "Off");
				o2.style.display = "none";
				
				if(tabCount==i){ // if at last tab and none are visible
					// hide entire box
					if(document.all) {
						document.all("DetailsBox").style.display = "none";
					}
					else if(document.getElementById) {
						document.getElementById("DetailsBox").style.display = "none";
					}
				}
			}
		}
	}
}

function openTab(tabIndex) {

	closeAllTabs();

	var o1 = null;
	var o2 = null;

	if(document.all) {
		o1 = document.all("tabBtn"+tabIndex);
		o2 = document.all("tabPane"+tabIndex);
	}
	else if(document.getElementById) {
		o1 = document.getElementById("tabBtn"+tabIndex);
		o2 = document.getElementById("tabPane"+tabIndex);
	}

	if(o1!=null && o2!=null) {

		if(tabIndex==2 && o1.style.display=="none") {
			//requested tab is not enabled
			//open the related tab tab
			openTab(3);
		}
		else if(tabIndex==3 && o1.style.display=="none") {
			//requested tab is not enabled
			//open the attributes tab
			//openTab(1);
        } else {
            o1.className = o1.className.replace("Off", "On");
			o1.style.display = ""
			o2.style.display = "";
		}
	}
}

function hideTabButton(tabIndex) {
	var o1 = null;
	if(document.all) { o1 = document.all("tabBtn"+tabIndex); }
	else if(document.getElementById) { o1 = document.getElementById("tabBtn"+tabIndex); }
	if(o1!=null) { o1.style.display = "none"; }
}

function closeAllTabs() {

	var i;
	var o1 = null;
	var o2 = null;

	for(i=0;i<=tabCount;i++) {

		o1 = null;
		o2 = null;

		if(document.all) {
			o1 = document.all("tabBtn"+i);
			o2 = document.all("tabPane"+i);
		}
		else if(document.getElementById) {
			o1 = document.getElementById("tabBtn"+i);
			o2 = document.getElementById("tabPane"+i);
		}

		if(o1!=null && o2!=null) {
		    o1.className = o1.className.replace("On", "Off");
			o2.style.display = "none";
		}

	}

}

function CheckBidCheckboxes(ThisItem,ThisFormName,ThisBidName,ThisPagingName,ThisKeywordName,ThisCategoryName,CurrentPage,CurrentKeyword,CurrentCategory,CheckboxArray){
	
	var NoneChecked = true;
	
	var x;
	
	for (x in CheckboxArray)
	{
		if (getElement(CheckboxArray[x]+'').checked){
			NoneChecked = false;
		}
	}
	
	if(NoneChecked){
			
		if(ThisItem != "Search"){
			// set keyword back
			getElement(ThisKeywordName).value = CurrentKeyword;
			
			if(ThisItem == "Category"){
				// set page back
				getElement(ThisPagingName).options[0].selected = true;
			}
		}
		
		// submit form
		getElement(ThisFormName).submit();
			
	}
	else{
		if(confirm("You have some products checked.\nWould you like to set the bid amount for these products to " + formatCurrency(getElement(ThisBidName).value) + "?")){
			
			if(ThisItem != "Search"){
				// set keyword back
				getElement(ThisKeywordName).value = CurrentKeyword;
				
				if(ThisItem == "Category"){
					// set page back
					getElement(ThisPagingName).options[0].selected = true;
				}
			}
			
			// submit form
			getElement(ThisFormName).submit();
			
		}
		else{
			
			// set page back
			for (var i=0;i<getElement(ThisPagingName).options.length;i++) {
				if (getElement(ThisPagingName).options[i].value == CurrentPage){
					getElement(ThisPagingName).options[i].selected = true;
				}
			}
			
			// set category back
			for (var i=0;i<getElement(ThisCategoryName).options.length;i++) {
				if (getElement(ThisCategoryName).options[i].value == CurrentCategory){
					getElement(ThisCategoryName).options[i].selected = true;
				}
			}
			
			return false;
		}
	}
}

function SetBids(ThisBidName,ThisKeywordName,MinimumBid,CurrentKeyword,CheckboxArray){
	
	var Bid = (+getElement(ThisBidName).value);
	
	var NoneChecked = true;
	
	var x;
	
	for (x in CheckboxArray)
	{
		if (getElement(CheckboxArray[x]+'').checked){
			NoneChecked = false;
		}
	}
	
	if(NoneChecked){
		alert("No bids checked.");
		return false;
	}
	else if(IsNumeric(Bid) && IsNumeric(MinimumBid) && (Bid >= MinimumBid || Bid == 0)){
		
		// set keyword back
		getElement(ThisKeywordName).value = CurrentKeyword;
		
		return true;	
	}
	else{
		if(IsNumeric(MinimumBid)){
			alert("Bid must be at least "+formatCurrency(MinimumBid));
		}
		else{
			alert("Error.  Minimum bid is invalid.")
		}
		return false;
	}
}

function UpdateLeadStatus(ThisFormName,ThisStatusName,CurrentStatus,NewStatus,ActivationPrice,PricePaid){
	
	if(PricePaid > 0){ActivationPrice = 0;}
	
	if(NewStatus=="Activate"){
		
		if(confirm(formatCurrency(ActivationPrice) + " will be deducted from your funds.")){
			getElement(ThisStatusName).value = NewStatus;
			getElement(ThisFormName).submit();
		}
		else{
			for (var i=0;i<getElement(ThisStatusName).options.length;i++) {
				if (getElement(ThisStatusName).options[i].value == CurrentStatus){
					getElement(ThisStatusName).options[i].selected = true;
				}
			}
		}
		
	}
	else if(NewStatus=="Refund"){
		
		if(confirm(formatCurrency(PricePaid) + " will be refunded to this account.")){
			getElement(ThisStatusName).value = NewStatus;
			getElement(ThisFormName).submit();
		}
		else{
			for (var i=0;i<getElement(ThisStatusName).options.length;i++) {
				if (getElement(ThisStatusName).options[i].value == CurrentStatus){
					getElement(ThisStatusName).options[i].selected = true;
				}
			}
		}
		
	}
	else if(confirm("This request's status will be changed to '"+NewStatus+"'.")){
		getElement(ThisStatusName).value = NewStatus;
		getElement(ThisFormName).submit();
	}
	else{
		for (var i=0;i<getElement(ThisStatusName).options.length;i++) {
			if (getElement(ThisStatusName).options[i].value == CurrentStatus){
				getElement(ThisStatusName).options[i].selected = true;
			}
		}
	}
	
}

function IgnoreEnterKey(field, event){
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		return false;
	} 
	else
	return true;
}

function CheckAll(ThisForm,ThisCheckbox,CheckboxArray){
	
	var Checked = getElement(ThisCheckbox).checked;
	
	var x;
	
	for (x in CheckboxArray)
	{
		getElement(CheckboxArray[x]+'').checked = Checked;
	}

}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}


function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

function Popup_Home() {
	if(getCookie("Popup_Home") != "false"){						
		setCookie("Popup_Home","false");
		var newwindow = popwindow('/Popup_Home/',500,360);
		try{
			newwindow.blur();
			if(document.all){window.opener.focus();}
		}
		catch(err){}
	}	
}

function showConfig(pagename) {
	var o1 = null;
	var o2 = null;
	if(document.all) {
		o1 = document.all("prodImage");
		o2 = document.all("prodOptions");
	}
	else if(document.getElementById) {
		o1 = document.getElementById("prodImage");
		o2 = document.getElementById("prodOptions");
	}

	if(o1!=null && 02!=null) {

		if(pagename!="") {
			o1.style.display = "none";
			o2.style.display = "block";

			parent.optionFrame.location.href = "frameloader.asp?goto="+escape(pagename);
		} else {
			o1.style.display = "block";
			o2.style.display = "none";
			parent.optionFrame.src = "blank.html";
		}

	}

}

function showLBConfig(pagename) {
	if(pagename!="") {
		showBox();
		parent.optionFrame.location.href = "frameloader.asp?goto="+escape(pagename);
	} else {
		parent.optionFrame.src = "blank.html";
		hideBox();
	}
}



function setLabel(labelID, labelValue) {
	var o = null;
	var hrefObj = null;
	var numericValue = 0;
	
	if(document.all) {
		o = document.all("lbl"+labelID);
		hrefObj = document.all("href"+labelID);
	}
	else if(document.getElementById) {
		o = document.getElementById("lbl"+labelID);
		hrefObj = document.getElementById("href"+labelID);
	}

	if(o!=null && o.innerText) {
		o.innerText = labelValue;
	}

	if(labelValue!="" && !isNaN(labelValue)) {
		numericValue = parseInt(labelValue);
	}


	if(numericValue==0) {
		hrefObj.style.color = "#999999";
	} else {
		hrefObj.style.color = "";
	}
}


function setProductTypeName(titleVal) {
	var o = null;
	var autoVal = "";
	var lastSpaceIndex = 0;
	if(titleVal!="") {
		for(i=titleVal.length;i>0;i--) {
			if(titleVal.charAt(i)==" ") { lastSpaceIndex=i; break; }
		}
		autoVal = titleVal.substr(lastSpaceIndex,titleVal.length);
		if(document.all) { o = document.all("ProductTypeAuto"); }
		else if(document.getElementById) { o = document.getElementById("ProductTypeAuto"); }
		if(o!=null) {
			o.innerText = autoVal;
		}
	}
}


function showGSAOptions(b) {
	var o = null;
	if(document.all) { o = document.all("GSAOptions"); }
	else if(document.getElementById) { o = document.getElementById("GSAOptions"); }

	if(o!=null && o.style) {
		if(b) {
			o.style.display = "none";
		} else {
			o.style.display = "block";
		}
	}
}



function popwindow(url,width,height) {
	var midX = (screen.width/2)-(width/2);
	var midY = (screen.height/2)-(height/2);
	popWindow = window.open (''+[url]+'','popwin', "width="+[width]+",height="+[height]+",toolbar=no,menubar=no,scrollbars=yes,resizable=yes,top="+midY+",left="+midX+",screenX="+midX+",screenY="+midY+"");
	if(popWindow != null){
		popWindow.focus();
		return popWindow;
	}
}

function popwindowFixed(url,width,height) {
	var midX = (screen.width/2)-(width/2);
	var midY = (screen.height/2)-(height/2);
	popWindow = window.open (''+[url]+'','popwin', "width="+[width]+",height="+[height]+",toolbar=no,menubar=no,scrollbars=no,resizable=no,top="+midY+",left="+midX+",screenX="+midX+",screenY="+midY+"");
	popWindow.focus();
}

function validateNumber(FNumber) {
	var pattern = /\D|^0/;
	if (pattern.test(FNumber.value)) {
		message = "This field accepts positive whole numbers only.\n\n"
		message += "Please try again.  Thank you."
		alert(message);
		FNumber.value = FNumber.defaultValue;
		FNumber.focus();
		return false;
	} else {
		return true;
	}
}

function validateDecimal(FNumber) {
var pattern = /[^\d\.]|\.{2,}/;
if (pattern.test(FNumber.value))
{
	message = "This field accepts positive numbers only.\n\n"
	message += "Please try again.  Thank you."
	alert(message);
	FNumber.value = FNumber.defaultValue;
	FNumber.focus();
	return false;
}
else
	return true;
}

function validateDate(FDate)
{
if (isWhitespace(FDate.value))
	return true;
if (isNaN(Date.parse(FDate.value)))
{
	text = "You have entered an invalid date.\n";
	text += "Please use the mm/dd/yyyy format.";
	alert(text);
	FDate.value = FDate.defaultValue;
	FDate.focus();
	return false;
}
else
	return true;
}

function validatePrice(FPrice)
{
if (validateDecimal(FPrice))
	FPrice.value = rectifyPrice(FPrice.value);
}

function validateEmail(FEmail)
{
FEmail.value = FEmail.value.replace(/\s/g,"");

var pattern = /^[\w-]+(\.[\w-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/;
if (isWhitespace(FEmail.value))
	return true;
else if (pattern.test(FEmail.value))
	return true;
else
{
	message = "You have entered an invalid e-mail address.\n\n";
	message += "Please try again.  Thank you.";
	alert(message);
	FEmail.value = FEmail.defaultValue;
	FEmail.focus();
	return false;
}
}


function isURL(FValue)
{
var pattern = /^ht{2}ps?:\/{2}/i;
if (pattern.test(FValue))
	return true;
else
	return false;
}

function validateURL(FURL)
{
if (FURL.value == "")
	return true;
else if (isURL(FURL.value))
	return true;
else
{
	message = "This field must begin with http:// or https://.\n\n"
	message += "Please try again.  Thank you."
	alert(message);
	FURL.value = FURL.defaultValue;
	FURL.focus();
	return false;
}
}

function trim(FString)
{
return FString.replace(/^\s*|\s*$/g,"");
}


function isWhitespace(FValue)
{
var pattern = /^\s*$/;
if (pattern.test(FValue))
	return true;
else
	return false;
}

// -- COMMON SCRIPTS -- //
function toggleElement(name,displaytype){
	if(displaytype==undefined){displaytype='';}
	if(getElement(name) != null){
		if(getElement(name).style.display == displaytype || getElement(name).style.display == ""){
			hideElement(name);
		}
		else{
			showElement(name,displaytype);
		}
	}
}

function showElement(name, displaytype) {
	if(displaytype==undefined){displaytype='';}
	var o1 = null;
	if(document.all) {
		o1 = document.all(name);
	}
	else if(document.getElementById) {
		o1 = document.getElementById(name);
	}
	if(o1!=null) {
		o1.style.display = displaytype;
	}
}

function hideElement(name) {
	var o1 = null;
	if(document.all) {
		o1 = document.all(name);
	}
	else if(document.getElementById) {
		o1 = document.getElementById(name);
	}
	if(o1!=null) {
		o1.style.display = "none";
	}
}

function getElement(name) {
	var o1 = null;
	if(document.all) {
		o1 = document.all(name);
	}
	else if(document.getElementById) {
		o1 = document.getElementById(name);
	}
	return o1;
}

function setCookie( 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 getCookie(check_name)
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function deleteCookie( name, path, domain ) {
	if ( getCookie(name) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function getQuerystring(key)
{
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if(qs == null)
		return "";
	else
		return qs[1];
} 

function randomNum()
{
	return Math.floor(Math.random()*1024000);
}

function GetXmlHttpObject(handler)
{ 
	var objXmlHttp=null;
	
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP";
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler;
			return objXmlHttp;
		} 
		catch(e)
		{ 
			alert("Error. Scripting for ActiveX might be disabled");
			return;
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler;
		return objXmlHttp;
	}
}