var panelToChange;
var panelWidth;

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

function setSelectedValue(selectbox, val) {
    for ( var i = 0; i < selectbox.options.length; i++ ) {
        if ( selectbox.options[i].value == val ) {
            selectbox.options[i].selected = true;
            return;
        }
    }
}
function randomFromTo(from, to){
   return Math.floor(Math.random() * (to - from + 1) + from);
}

//removes options from dropdown "d" other than those whose values are in array "a"
function removeOptionsOtherThan(d, a) {
    var tmpSelect = document.createElement("select");
    
    for ( var i = 0; i < d.options.length; i++ ) {
        if ( a.indexOf(d.options[i].value) > -1 ) {
            var theOption = document.createElement("OPTION");
            theText = document.createTextNode(d.options[i].text);
            theOption.appendChild(theText);
            theOption.setAttribute("value",d.options[i].value);
            tmpSelect.appendChild(theOption);
        }
    }
    d.options.length=0;
    for( var i=0; i < tmpSelect.options.length; i++)
    {
        var theOption = document.createElement("OPTION");
        theText = document.createTextNode(tmpSelect.options[i].text);
        theOption.appendChild(theText);
        theOption.setAttribute("value",tmpSelect.options[i].value);
        d.appendChild(theOption);
    }
}

function replaceTargetImage(target, image)
{
  if(image != ''){
    $(target).src = image;
  }
}

//trim string... good for imposing maxlengths in textareass
function Trim(s, maxlength) {
    if (s.value.length > maxlength) 
    s.value = s.value.substring(0,maxlength);
}

function setCookie(name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
	
function readCookie(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;	
}

//grays out anything on the screen with z-index less than 1500
//vis = true to start the gray-out, false to remove the gray out.
function grayOut(vis, options) {
      // Pass true to gray out screen, false to ungray
      // options are optional.  This is a JSON object with the following (optional) properties
      // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
      // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
      // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
      // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
      // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
      // in any order.  Pass only the properties you need to set.
      var options = options || {}; 
      var zindex = options.zindex || 1500;
      var opacity = options.opacity || 50;
      var opaque = (opacity / 100);
      var bgcolor = options.bgcolor || '#000000';
      var dark=document.getElementById('darkenScreenObject');
      if (!dark) {
        // The dark layer doesn't exist, it's never been created.  So we'll
        // create it here and apply some basic styles.
        // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
        var tbody = document.getElementsByTagName("body")[0];
        var tnode = document.createElement('div');           // Create the layer.
            tnode.style.position='absolute';                 // Position absolutely
            tnode.style.top='0px';                           // In the top
            tnode.style.left='0px';                          // Left corner of the page
            tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
            tnode.style.display='none';                      // Start out Hidden
            tnode.id='darkenScreenObject';                   // Name it so we can find it later
        tbody.appendChild(tnode);                            // Add it to the web page
        dark=document.getElementById('darkenScreenObject');  // Get the object.
      }
      if (vis) { 
        
    var xScroll, yScroll;    
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		xScroll = document.documentElement.scrollWidth;
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	pageWidth = xScroll;
	pageHeight = yScroll;
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
        
        
        
        //set the shader to cover the entire page and make it visible.
        dark.style.opacity=opaque;                      
        dark.style.MozOpacity=opaque;                   
        dark.style.filter='alpha(opacity='+opacity+')'; 
        dark.style.zIndex=zindex;        
        dark.style.backgroundColor=bgcolor;  
        dark.style.width= '100%';//pageWidth + 'px'; on KD the body width is 950 so it was using that
        dark.style.height= pageHeight + 'px';
        dark.style.display='block';                          
      } else {
         dark.style.display='none';
      }
}

function openDHTMLDivWindow(id, title, div_name, width, height, left, top, gray_out)
{
    grayOut(true);
    ajaxwin=dhtmlwindow.open(id, "div", div_name, title, "width="+width+"px,height="+height+"px,left="+left+"px,top="+top+"px,resize=0,scrolling=0");
}

function IsANumber(x)
{
    var anum=/(^\d+$)|(^\d+\.\d+$)/
    if (anum.test(x))
        return true;
    else{
        return false;
    }
}

function GetAspFieldValue(id)
{
    var element_array = Form.getElements('form1');
    var len = element_array.length;
    var namestring = " ";
           
    for(var i=0; i < len; i++)
    {
        var element = Form.getElements('form1')[i];
        var var_len = element.length;
        
        namestring = namestring + " " + element.name;
    
        if(element.name.search(id) != -1)
        {
            return element.value;
        }
    }
    
    return "";
}
function GetAspField(id)
{
    var element_array = Form.getElements('form1');
    var len = element_array.length;
           
    for(var i=0; i < len; i++)
    {
        var element = Form.getElements('form1')[i];
        var var_len = element.length;
    
        if(element.id.search(id) != -1)
        {
            return element;
        }
    }
    
    return "";
}
//get the asp field by id and class
function GetAspFieldByClass(id,className)
{  
    var field = null;
    $$(className).each(
            function(element)
            {
                if(element.id.search(id) != -1)
                {
                    field = element;
                    $break;
                }
           }
         )        
    return field;
} 
function GetAspFieldId(id)
{
    var element_array = Form.getElements('form1');
    var len = element_array.length;
    var namestring = " ";
           
    for(var i=0; i < len; i++)
    {
        var element = Form.getElements('form1')[i];
        var var_len = element.length;
        
        namestring = namestring + " " + element.name;
    
        if(element.name.search(id) != -1)
        {
            return element.id;
        }
    }
    
    return "";
} 
function isIE6() {
	var appVer = navigator.appVersion;
	appVer = appVer.split(';');
	if(appVer[1] == ' MSIE 6.0') {
		return true;
	}				
}

function updateOptions(option_title,chosen_option,initial_load)
{
	$(option_title + '_loading').toggle()
	var options_string = GetAspFieldByClass(option_title.toLowerCase() + "_" + chosen_option.replace(' ','_').toLowerCase(),"input").value;

	var options = options_string.split("|");

	for(var j=0; j<options.length; j++)
	{
		var opt_str = options[j];
	    var option_values = opt_str.split(":");

	    var option = option_values[0];
	    var values = option_values[1].split(",");

	    var select = GetAspFieldByClass(option,"select.option_Dropdown");
	    var selectedIndex = select.selectedIndex;
	    //we don't want to preseve the selection if this is a change in color, only if it's a postback
	    var preserveSelection = false;
        //if select.innerHTML.indexOf('selected') > -1 then something other than Select... was chosen
    	if(initial_load && select.innerHTML.indexOf('selected') > -1)
        {
            preserveSelection = true;
        }
	    select.descendants().each(Element.remove); 
        
        var newOption = new Option("Select...","Select");

		try
		{
		  select.options[select.length] = newOption; 
		}
		catch(ex) {
		  select.add(newOption, select.options[select.length]); // non-IE only
		}	    

	    for(var i=0; i< values.length; i++)
	    {
	    	var value = values[i];

	    	var newOption = new Option(value,value);


			try
			{
			  select.options[select.length] = newOption;  
			}
			catch(ex) {
			  select.add(newOption, select.options[select.length]); // non-IE only
			}

	    	/*
			var newOption = new Option(value, value);
	    	$(option).options[$(option)length];*/
	    }
	    
	    if(preserveSelection)
        {
           select.selectedIndex = selectedIndex + 1;
	    }

	}
    setTimeout("$('" + option_title + "_loading').toggle()",500);
}
function getComputedHeight(theElt){
        var browserName=navigator.appName;
         if (browserName=="Microsoft Internet Explorer"){
                var is_ie=true;
         } else {
                var is_ie=false;
         }
        if(is_ie){
                tmphght = $(theElt).offsetHeight;
        }
        else{
                docObj = $(theElt);
                var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("height");
                tmphght = tmphght1.split('px');
                tmphght = tmphght[0];
        }
        return tmphght;
}

function isDefined(varname)
{
    if ( typeof( window[ varname ] ) != "undefined" ) {
       return true;
    } 
    else {
       return false;
    }
}

function isFunction(name)
{
    if(typeof name == 'function') { 
        return true;
    }
    return false;
}

function addMailingList(email,panel,image) {
    if($F(email) != ''){
        panelToChange = panel;
        
        Element.hide(image);
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        Element.show(panel);
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</span>');
        var url = 'process.aspx';
        var params = 'type=mailinglist&email=' + $F(email);
        try
        {
            var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: addMailingListResult });
        }
        catch(exc)
        {
            if($('emailError')!=null)
            { 
                Element.show($('emailError'));
            } 
            else 
            {
                Element.show(panel);
                new Insertion.Top(panel, '<span id="adding" style="width:100%;text-align:right;">There has been an error.</span>');
            }
        }
    }
    else
    {
            if($('emailError')!=null){ 
                Element.show($('emailError'));
            } else {
                Element.show(panel);
                new Insertion.Top(panel, '<span id="adding" style="width:100%;text-align:right;">Please enter an email address.</span>');
            }
    }
}
function removeFromMailingList(panel,image,email) {
    if($F(email) != ''){
        Element.hide(image);
        Element.show(panel);
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Unsubscribing...</span>');
        
        var url = 'process.aspx';
        var params = 'type=removemailinglist&email=' + $F(email);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: removeFromMailingListResult });
    }
    else{
        Element.show($('unsubscribe_email_error'));
    }
}

function addMailingListWithName(email,name,panel,image) {
    if(email != ''){
        panelToChange = panel;
        
        Element.hide(image);
        Element.show(panel);
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</span>');
        var url = 'process.aspx';
        var params = 'type=mailinglist&email=' + email + "&name=" + name;
        try
        {
            var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: addMailingListResult });
        }
        catch(exc)
        {
            Element.show($('emailError'));
        }
    }
    else
    {
        Element.show($('emailError'));
    }
}

function addMailingListResult(result){
    Element.hide('adding');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">Email successfully added.</span>');        
    }
    else{
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">You are already on our mailing list.</span>');        
    }    
}
function removeFromMailingListResult(result)
{
    $("adding").style.textDecoration = "none";
    if(result.responseText == "True")
    {
        $("adding").update('Email Successfully Removed');        
    }
    else{
        $("adding").update('You are already on our mailing list.');        
    }  
}

function addDiscountMailingList(email,panel,image,errorpanel) {
    if($F(email) != ''){
        panelToChange = panel;
        
        Element.hide(image);
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</span>');
        var url = 'process.aspx';
        var params = 'type=discountmailinglist&email=' + $F(email);
        try
        {
            var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: addDiscountMailingListResult });
        }
        catch(exc)
        {
            Element.show(errorpanel);
        }
    }
    else
    {
        Element.show(errorpanel);
    }
}

function addDiscountMailingListResult(result){
    Element.hide('adding');
    if(result.responseText.indexOf("True") > -1)
    {
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;"> Thanks. Your coupon will be sent by email.</span>');        
    }
    else{
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;"> You are already on our mailing list.</span>');        
    }    
}


function sendLostPasswdByNameEmail(username,email,panel,image) {
    if($F(username) != '' || $F(email) != ''){
        panelToChange = panel;
        
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Sending...</span>');
        var url = 'process.aspx';
        var params = 'type=lostpassword&email='+$F(email)+'&username=' + $F(username);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: lostPasswdResult });
    }
    else{
        Element.show($('passwdSentFailure'));
    }
}

function sendLostPasswd(username,panel,image) {
    if($F(username) != ''){
        panelToChange = panel;
        
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Sending...</span>');
        var url = 'process.aspx';
        var params = 'type=lostpassword&username=' + $F(username);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: lostPasswdResult });
    }
    else{
        Element.show($('passwdSentFailure'));
    }
}

function lostPasswdResult(result){
    if(result.responseText == "True")
    {
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">Your password has been sent to your email account.</span>');        
    }
    else{
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">Your email address cannot be retrieved. For more help, please contact Customer Support.</span>');        
    }    
}

function removeMailingList(panel,image,email) {
    if($F(email) != ''){
        $('unsubscribeMessage').style.textDecoration = "blink";
        Element.update( $('unsubscribeMessage'), "Unsubscribing...")

        var url = 'process.aspx';
        var params = 'type=removemailinglist&email=' + $F(email);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: removeMailingListResult });
    }
    else{
        Element.show($('unsubscribe_email_error'));
    }
}

function removeMailingListResult(result){
    $('unsubscribeMessage').style.textDecoration = "none";
    if(result.responseText == "True")
    {
        Element.update( $('unsubscribeMessage'), "Email Unsubscribe Successful")
    }
    else{
        Element.update( $('unsubscribeMessage'), "Email address not found")
    }    
}

function askAQuestion(panel,button,question,email,name,subject,skuLink) {
    if($F(question) != '' && $F(email) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingQuestion" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=question&email=' + $F(email) + '&question=' + $F(question) + '<br>' + skuLink + '&name=' + $F(name) + '&subject=' + subject;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: askAQuestionResult });
        $(question).value = '';
        $(email).value = '';
        $(name).value = '';
    }
    else{
        if($F(question) == ''){
            $(question + '_error').style.display = 'inline';
        }
        else{
            $(question + '_error').style.display = 'none';
        }
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        }        
    }
}

function requestPasswordEmail(panel,button,email,first_name,last_name,company,zip,other) {
    if($F(email) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingQuestion" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=passwordEmail&email=' + $F(email) + '&first_name=' + $F(first_name) + '&last_name=' + $F(last_name) + '&company=' + $F(company) + '&zip=' + $F(zip) + '&other=' + $F(other);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: passwordEmailResult });
        $(email).value = '';
        $(first_name).value = '';
        $(last_name).value = '';
        $(company).value = '';
        $(zip).value = '';
        $(other).value = '';
    }
    else{
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        }        
    }
}

function askAQuestionResult(result){
    Element.hide('sendingQuestion');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your question has been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your question.</div>');        
    }        
}

function passwordEmailResult(result){
    Element.hide('sendingQuestion');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;color:red;">Thank you. Your request has been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;color:red;">There was an error sending your request.</div>');        
    }        
}

function tellAFriend(panel,button,message,your_email,your_name,their_email,title,sku,mode) {
    if($F(message) != '' && $F(your_email) != '' && $F(their_email) != ''){
        var emailSubject;
        emailSubject = $F(your_name) + ' wants you to know about the ' + title;
        panelToChange = panel;
        Element.hide(button);
        new Insertion.Top(panel, '<div id="sendingQuestion" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=tell&your_email=' + $F(your_email) + '&message=' + $F(message) + '&your_name=' + $F(your_name) + '&their_email=' + $F(their_email)  + '&subject=' + emailSubject + '&sku=' + sku + '&title=' + title + '&mode=' + mode;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: tellAFriendResult });
        $(message).value = '';
        $(your_email).value = '';
        $(your_name).value = '';
        $(their_email).value = '';        
    }
    else{
        if($F(message) == ''){
            $(message + '_error').style.display = 'inline';
        }
        else{
            $(message + '_error').style.display = 'none';
        }
        
        if($F(your_email) == ''){
            $(your_email + '_error').style.display = 'inline';
        }        
        else{
            $(your_email + '_error').style.display = 'none';
        } 
        
        if($F(their_email) == ''){
            $(their_email + '_error').style.display = 'inline';
        }        
        else{
            $(their_email + '_error').style.display = 'none';
        }                
    }
}

function getFraudScore(order_number, min_score) //min_score will come from web config
{
    var url = 'process.aspx';
    var params = 'type=getFraudScore';
    //riskSocre is now returned from process - YH 4/15/10
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: fraudScoreResult });
}

function fraudScoreResult(result)
{
    RunVerification(result.responseText);
}

function expandVerificationAddress(section_name)
{
    if($(section_name).style.display == 'none')
    {
        $(section_name).style.display = 'block';
        $('addressTable').style.display = 'block';
    }
    else
    {
        $(section_name).style.display = 'none';
    }
    
    if($('shippingAddress').style.display=='none' && $('billingAddress').style.display=='none')
    {
        $('addressTable').style.display = 'none';
    }
    return false;
}

function SubmitVerification(site_id, user_id, order_number)
{
    if( ValidateVerificationFields() )
    {
        var url = 'process.aspx';
        var params = 'type=verification'+($('sFirstName') != null ? "&sFname="+$F('sFirstName')+"&sLname="+$F('sLastName')+"&sAddress1="+ encodeURIComponent($F('sAddress1'))+
                       "&sAddress2="+ encodeURIComponent($F('sAddress2'))+"&sCompany="+$F("sCompany")+"&sZip="+$F("sZip")+"&sCity="+$F("sCity")+
                       "&sState="+(GetAspFieldValue("ShippingCountry")=='US' ? GetAspFieldValue("ShippingState") : $F("sState"))+"&sCountry="+GetAspFieldValue("ShippingCountry")+'&bFname='+$F('bFirstName')+"&bLname="+$F('bLastName')+
                       "&bAddress1="+encodeURIComponent($F('bAddress1'))+"&bAddress2="+encodeURIComponent($F('bAddress2'))+"&bCompany="+$F("bCompany")+"&bZip="+$F("bZip")+"&bCity="+$F("bCity")+
                       "&bState="+(GetAspFieldValue("BillingCountry")=='US' ? GetAspFieldValue("BillingState") : $F("bState"))+"&bCountry="+GetAspFieldValue("BillingCountry") : "")+
                       ($("bankName")!=null? "&bankName="+$F("bankName") : "" )+($('bankPhone')!=null ? "&bankPhone="+$F("bankPhone") : "")+
                       ($("b1FirstName")==null ? "" : "&b1Fname="+$F("b1FirstName")+"&b1Lname="+$F("b1LastName")+"&b1Address1="+encodeURIComponent($F("b1Address1"))+"&b1Address2="+ encodeURIComponent($F("b1Address2")) +
                       "&b1Company="+$F("b1Company")+"&b1City="+$F("b1City")+"&b1State="+(GetAspFieldValue("Billing1Country")=='US' ? GetAspFieldValue("Billing1State") : $F("b1State"))+"&b1Zip="+$F("b1Zip")+"&b1Country="+GetAspFieldValue("Billing1Country"));

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: verificationResult });
    }
}

function ValidateVerificationFields()
{
    passes_validation = true;
    filled_in = false;

    try{
        if($('sAddress1')!=null)
        {
            if($F('sAddress1')!="" || $F('sZip')!="" || $F('sCity')!="")
            {
                if($F('sFirstName')=="") { $('sFirstNameLabel').style.color="red"; passes_validation = false; } else { $('sFirstNameLabel').style.color="black"; } 
                if($F('sLastName')=="") { $('sLastNameLabel').style.color="red"; passes_validation = false; } else { $('sLastNameLabel').style.color="black";} 
                if($F('sAddress1')=="") { $('sAddress1Label').style.color="red"; passes_validation = false; } else { $('sAddress1Label').style.color="black";} 
                if($F('sCity')=="") { $('sCityLabel').style.color="red"; passes_validation = false; } else { $('sCityLabel').style.color="black";} 
                if($F('sZip')=="") { $('sZipLabel').style.color="red"; passes_validation = false; } else { $('sZipLabel').style.color="black";} 
                if($F('sState')=="" && GetAspFieldValue("ShippingCountry")!='US') { $('sStateLabel').style.color="red"; passes_validation = false; } else { $('sStateLabel').style.color="black";} 
                filled_in = true;
            }
        }
        
        if($('bAddress1')!=null)
        {
            if($F('bAddress1')!="" || $F('bZip')!="" || $F('bCity')!="")
            {
                if($F('bFirstName')=="") { $('bFirstNameLabel').style.color="red"; passes_validation = false; } else { $('bFirstNameLabel').style.color="black"; } 
                if($F('bLastName')=="") { $('bLastNameLabel').style.color="red"; passes_validation = false; } else { $('bLastNameLabel').style.color="black";} 
                if($F('bAddress1')=="") { $('bAddress1Label').style.color="red"; passes_validation = false; } else { $('bAddress1Label').style.color="black";} 
                if($F('bCity')=="") { $('bCityLabel').style.color="red"; passes_validation = false; } else { $('bCityLabel').style.color="black";} 
                if($F('bZip')=="") { $('bZipLabel').style.color="red"; passes_validation = false; } else { $('bZipLabel').style.color="black";} 
                if($F('bState')=="" && GetAspFieldValue("BillingCountry")!='US') { $('bStateLabel').style.color="red"; passes_validation = false; } else { $('bStateLabel').style.color="black";} 
                filled_in = true;
            }
        }
        
        if($('b1Address1')!=null)
        {
            if($F('b1Address1')!="" || $F('b1Zip')!="" || $F('b1City')!="")
            {
                if($F('b1FirstName')=="") { $('b1FirstNameLabel').style.color="red"; passes_validation = false; } else { $('b1FirstNameLabel').style.color="black"; } 
                if($F('b1LastName')=="") { $('b1LastNameLabel').style.color="red"; passes_validation = false; } else { $('b1LastNameLabel').style.color="black";} 
                if($F('b1Address1')=="") { $('b1Address1Label').style.color="red"; passes_validation = false; } else { $('b1Address1Label').style.color="black";} 
                if($F('b1City')=="") { $('b1CityLabel').style.color="red"; passes_validation = false; } else { $('b1CityLabel').style.color="black";} 
                if($F('b1Zip')=="") { $('b1ZipLabel').style.color="red"; passes_validation = false; } else { $('b1ZipLabel').style.color="black";} 
                if($F('b1State')=="" && GetAspFieldValue("Billing1Country")!='US') { $('b1StateLabel').style.color="red"; passes_validation = false; } else { $('b1StateLabel').style.color="black";} 
                filled_in = true;
            }
        }
        
        if($('bankName')!=null)
        {
            if($F("bankName")!="" || $F("bankPhone")!="")
            {
                $("bankNameLabel").style.color="black";
                $("bankPhoneLabel").style.color=="black";
                filled_in = true;
            }
        }
    }catch(exc) 
    {
    }
    
    if(filled_in && !passes_validation)
    {
        $('v_nothing_entered').style.display = 'none'; 
        $("v_err_msg").style.display = "inline"; 
    }
    else if(!filled_in)
    {
        $('v_nothing_entered').style.display = 'inline'; 
        $("v_err_msg").style.display = "none"; 
        passes_validation = false;
    }
    else
    {
        $('v_nothing_entered').style.display = 'none'; 
        $("v_err_msg").style.display = "none"; 
    }
    
    /*
    if(passes_validation)
    { 
        $("v_err_msg").style.display = "none"; 
    } 
    else 
    { 
        $("v_err_msg").style.display = "inline"; 
    } 
    
    if(!filled_in)
    {
        $('v_nothing_entered').style.display = 'inline'; 
        passes_validation = false;
    }
    else if(filled_in && passes_validation)
    {
        $('v_nothing_entered').style.display = 'none'; 
    }
    
    
  /*  if($('bAddress1')!=null)
    {
        if($F('bAddress1')=="" && $F('bZip')=="" && $F('sAddress1')=="" && $F('sZip')=="") 
        { 
            if($("bankPhone") !=null)
            {
                if($F("bankName")=="" && $F("bankPhone")=="")
                {
                    if($("b1Address1")==null)
                    {
                        $('v_nothing_entered').style.display = 'inline'; 
                        passes_validation = false;
                    }
                    else
                    {
                        if($F("b1Address1")=="" && $F("b1City")=="" && $F("b1Zip")=="")
                        {
                            $('v_nothing_entered').style.display = 'inline'; 
                            passes_validation = false;
                        }
                    }
                }
            }
            else if($("b1Address1")!=null)
            {
                if($F("b1Address1")=="" && $F("b1City")=="" && $F("b1Zip")=="")
                {
                    $('v_nothing_entered').style.display = 'inline'; 
                    passes_validation = false;
                }
            }
            else
            {
                $('v_nothing_entered').style.display = 'inline'; 
                passes_validation = false;
            }
        }
    }
    else if($("bankPhone") !=null)
    {        
        if($("b1Address1")==null)
        {
            if($F("b1Address1")=="" && $F("b1City")=="" && $F("b1Zip")=="")
            {
                $('v_nothing_entered').style.display = 'inline'; 
                passes_validation = false;
            }
        }
        else if($F("bankName")=="" && $F("bankPhone")=="")
        {
            $('v_nothing_entered').style.display = 'inline'; 
            passes_validation = false;
        }
    }
    else
    {
        $('v_nothing_entered').style.display = 'none';  
    }*/
    
    return passes_validation;
}

function verificationResult()
{
    $("verificationContent").innerHTML = "<table width='660' height='420'><tr><td align='center' valign='middle'><font color='red' size='+1'>Thank you. Your updates have been processed.</font><br><br><br><font size='+1'> We will contact you if any further information is needed.</font><br><br><br><a href='javascript:void(0);' onclick='window.parent.ajaxwin.close();'><u>Close Window</u></a></td></tr></table>";
}

function tellAFriendResult(result){
    Element.hide('sendingQuestion');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your email has been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your email.</div>');        
    }        
}

function suggestProduct(panel,button,comment,email,name,subject,page,site_id) {
    if($F(comment) != '' && $F(email) != '' && $F(name) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingComments" style="width:100%;text-align:right;text-decoration: blink;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=suggestProduct&email=' + $F(email) + '&comment=' + $F(comment) + '&name=' + $F(name) + '&subject=' + subject+'&page='+page+'&site_id='+site_id;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: suggestProductResult });
        $(comment).value = '';
        $(email).value = '';
        $(name).value = '';
    }
    else{
        if($F(comment) == ''){
            $(comment + '_error').style.display = 'inline';
        }
        else{
            $(comment + '_error').style.display = 'none';
        }
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        } 
        if($F(name) == ''){
            $(name + '_error').style.display = 'inline';
        }        
        else{
            $(name + '_error').style.display = 'none';
        }         
    }
}

function suggestProductResult(result){
    Element.hide('sendingComments');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your comments have been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your comments.</div>');        
    }        
}

function tellUs(panel,button,comment,email,name,subject,page,site_id) {
    if($F(comment) != '' && $F(email) != '' && $F(name) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingComments" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=tellus&email=' + $F(email) + '&comment=' + $F(comment) + '&name=' + $F(name) + '&subject=' + subject+'&page='+page+'&site_id='+site_id;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: tellUsResult });
        $(comment).value = '';
        $(email).value = '';
        $(name).value = '';
    }
    else{
        if($F(comment) == ''){
            $(comment + '_error').style.display = 'inline';
        }
        else{
            $(comment + '_error').style.display = 'none';
        }
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        } 
        if($F(name) == ''){
            $(name + '_error').style.display = 'inline';
        }        
        else{
            $(name + '_error').style.display = 'none';
        }         
    }
}

function tellUsResult(result){
    Element.hide('sendingComments');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your comments have been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your comments.</div>');        
    }        
}



    function fill_form(id, firstname, lastname, address1, address2, company, city, state, country, zip, dayphone, nightphone, fax,use_this)
    {
        var element_array = Form.getElements('form1');
        var len = element_array.length;
        var namestring = " ";
        var stateTextBoxId = "";
        //if use_this is 1, then the customer choose an address, else they didn't
        
        //$("address_id").value = id;        
        for(var i=0; i < len; i++)
        {
            var element = Form.getElements('form1')[i];
            var var_len = element.length;
            
            namestring = namestring + " " + element.name;
        
            if(element.name.search("FirstNameTextbox") != -1)
            {
                element.value=firstname;
                if(use_this == 1){
                    element.readOnly="readOnly";
                }
                continue;
            }
            
            if(element.name.search("LastNameTextbox") != -1)
            {
                element.value=lastname;
                if(use_this == 1){
                    element.readOnly="readOnly";
                }
                continue;
            }
            
            if(element.name.search("Address1Textbox") != -1)
            {
                element.value=address1;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("CompanyTextbox") != -1)
            {
                element.value=company;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("Address2Textbox") != -1)
            {
                element.value=address2;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("CityTextbox") != -1)
            {
                element.value=city;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("StateDropDown") != -1)
            {
                element.value = state;
                if(use_this == 1){
                    element.readOnly="readOnly";
                    Element.hide("StateDropdownDiv");                
                    Element.show("StateTextboxDiv");                   

                }
                continue;
            }
            
            if(element.name.search("StateTextbox") != -1)
            {
                stateTextBoxId = element.id;
                element.value=state;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("CountryCodeDropDownList") != -1)
            {
                element.value = country;
                if(use_this == 1){
                    Element.hide("CountryDropdownDiv");                
                    Element.show("CountryTextboxDiv");                
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("ZipTextbox") != -1)
            {
                element.value=zip;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("DayPhoneTextbox") != -1)
            {
                element.value=dayphone;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("NightPhoneTextbox") != -1)
            {
                element.value=nightphone;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("FaxTextbox") != -1)
            {
                element.value=fax;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }                   
        }     
        
        
        if(use_this == 1){                 
            $('StateTextboxDiv').innerHTML = "<input type=text name='StateTextbox' id='" + stateTextBoxId + "' maxlength='128' value=" + state + "></input>";
            $(stateTextBoxId).readOnly="readOnly";
        }
        
        
        if(use_this == 1){  
            $('CountryTextboxDiv').innerHTML = "<input type=text name='CountryTextbox' id='CountryTextbox' value=" + country + "></input>";
            $("CountryTextbox").readOnly="readOnly";
            Element.show("CreateNewAddressDiv"); 
            if($('SaveToMyAddressBook') != null)
            {
                Element.hide("SaveToMyAddressBook"); 
            }
        }        
    }     
    
    function allow_new_form()
    {
        var element_array = Form.getElements('form1');
        var len = element_array.length;
        var namestring = " ";
        
        $("address_id").value = -1;
        $("use_this").value = 0;
         
        for(var i=0; i < len; i++)
        {
            var element = Form.getElements('form1')[i];
            var var_len = element.length;
            
            namestring = namestring + " " + element.name;
        
            if(element.name.search("FirstNameTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("LastNameTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("Address1Textbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("CompanyTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("Address2Textbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("CityTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("StateDropDown") != -1)
            {                
                Element.show("StateDropdownDiv");
                Element.show(element);
                element.readOnly="";

                continue;
            }
            
            if(element.name.search("StateTextbox") != -1)
            {
                element.readOnly="";
                element.value = '';
                continue;
            }
            
            if(element.name.search("CountryCodeDropDownList") != -1)
            {                
                element.value = "US";
                Element.show("CountryDropdownDiv");
                element.readOnly="";

                continue;
            }
            
            if(element.name.search("ZipTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("DayPhoneTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("NightPhoneTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("FaxTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
         
        }   
        $('CountryTextboxDiv').innerHTML = "";
        $('StateTextboxDiv').innerHTML = "";
        Element.hide("CreateNewAddressDiv");         
        if($('SaveToMyAddressBook') != null)
        {
            Element.show("SaveToMyAddressBook"); 
        }
        if($('same_address_checkbox') != null)
        {
            $('same_address_checkbox').checked = false;
        }        
    }


    
function loadAjaxText()
{
	var dest = "www13.karatedepot.com/catalog/ajax_test.txt";

	try
	{
	
		if (window.XMLHttpRequest)     // Object of the current windows
		{
			xmlhttp = new XMLHttpRequest();     // Firefox, Safari, ...
		}
		else if (window.ActiveXObject)   // ActiveX version
		{
		       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");    // Internet Explorer
		}
	
	}catch(e)
	{
		//no javascript
	}
	
	xmlhttp.onreadystatechange = triggered();
	xmlhttp.open("GET", dest, true);
	xmlhttp.send(null);
	
}

function triggered() {
	if (xmlhttp.readyState == 4) {
		document.getElementById("ajax_form").innerHTML = xmlhttp.responseText;
	}
}    
function updateAjaxDisplay()
{
	var pars = '';
	var url = "/sites/scripts/ajax_test.txt";

	var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,       
				onComplete: showResponse
			});
}

function showPopup(panel){
    Effect.Appear(panel,{ duration: .25});
} 

function hidePopup(panel){
    Effect.Fade(panel,{ duration: .25});
} 

function showResponse(originalRequest)
{
	//put returned XML in the textarea
	$('ajax_div').innerHTML = originalRequest.responseText;
}

String.prototype.toTitleCase = function() {
    var ls = this.toLowerCase();
    var la = ls.split(' ');
    for (var i = 0; i < la.length; i++ ) {
    la[i] = la[i].charAt(0).toUpperCase() + la[i].slice(1);
    }
    return la.join(' ');
}

//check if function is an array
function isArray(obj) {
return (obj.constructor.toString().indexOf("Array") != -1);
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}
//gets numeric price value from price string, RT 11/08/2010
function getCurrencyAmount(price)
{
    return parseFloat(price.replace('$',''));
}

String.prototype.trim = function() 
{
	var l=0; 
	var r=this.length - 1;
	
	while(l < this.length && this[l] == ' ')
	{	l++; }
	
	while(r > l && this[r] == ' ')
	{	r-=1;	}
	
	return this.substring(l, r+1);
}

String.prototype.ltrim = function() 
{
	var l=0;
	while(l < s.length && this[l] == ' ')
	{	l++; }
	return this.substring(l, this.length);
}

String.prototype.rtrim = function() 
{
	var r=this.length -1;
	while(r > 0 && this[r] == ' ')
	{	r-=1;	}
	return s.substring(0, r+1);
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5 && version < 7) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";border:none;"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
if(navigator.appName == "Microsoft Internet Explorer"){
    window.attachEvent("onload", correctPNG);
}

function detectArrayItem(originalArray, itemToDetect) {
    for (var j=0; j < originalArray.length; j++) {
        if (originalArray[j] == itemToDetect) {
            return true;
        }
    }
    return false;
}

function removeArrayItem(originalArray, itemToRemove) {
    for (var j=0; j < originalArray.length; j++) {
        if (originalArray[j] == itemToRemove) {
            originalArray.splice(j,1);
        }
    }
    return originalArray;
}

function display_submenu(elmnt){
       
    if (ClickTaleIsIn("recording") && typeof ClickTaleExec == "function") {
		var elmntId = elmnt.id;
		if(elmntId) {
			ClickTaleExec("display_submenu(document.getElementById('" + elmntId + "'))");
		}
	}
         
	elmnt.childNodes[2].style.visibility='visible';
	elmnt.childNodes[2].style.left='auto';
	elmnt.addClassName('w_d_down_hover');
	elmnt.removeClassName('w_d_down');
	//alert(elmnt.childNodes[2].type)
}

function bhhag(elmnt,mode){   
    //only execute if this is coming from an onmouseout and it's not IE or it's coming from onmouseleave
    if((mode == "out" && !document.all) || mode == "leave")
    {
        if (ClickTaleIsIn("recording") && typeof ClickTaleExec == "function") {
		    var elmntId = elmnt.id;
		    if(elmntId) {
			    ClickTaleExec("bhhag(document.getElementById('" + elmntId + "'))");
		    }
	    }
             
	    elmnt.childNodes[2].style.left='-3000px';
	    elmnt.childNodes[2].style.visibility='hidden';
	    elmnt.addClassName('w_d_down');
	    elmnt.removeClassName('w_d_down_hover');
	    //elmnt.className = elmnt.className.replace(' t_menu_selected', '');
	}
}

//clears a field if there is a title and the current value does not equal the title
function ClearField(field)
{   
    if(field != null)
    {
        if(field.title != '' && field.value == field.title)
        {
            field.value = '';
        }
    }
}

//returns the default valueto a field (the title) if the field is empty and there is a title
function DefaultValue(field)
{
    if(field != null){
        if(field.title != '' && field.value == '')
        {
            field.value = field.title;
        }
    }
}

function luhn_check(s) {

  var i, n, c, r, t;

  // First, reverse the string and remove any non-numeric characters.

  r = "";
  for (i = 0; i < s.length; i++) {
    c = parseInt(s.charAt(i), 10);
    if (c >= 0 && c <= 9)
      r = c + r;
  }

  // Check for a bad string.

  if (r.length <= 1)
    return false;

  // Now run through each single digit to create a new string. Even digits
  // are multiplied by two, odd digits are left alone.

  t = "";
  for (i = 0; i < r.length; i++) {
    c = parseInt(r.charAt(i), 10);
    if (i % 2 != 0)
      c *= 2;
    t = t + c;
  }

  // Finally, add up all the single digits in this string.

  n = 0;
  for (i = 0; i < t.length; i++) {
    c = parseInt(t.charAt(i), 10);
    n = n + c;
  }

  // If the resulting sum is an even multiple of ten (but not zero), the
  // card number is good.

  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}

function isValidEmail(email) {

    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email.value)) 
    {
        return false;
    }
    return true;    
}

// Changes the cursor to an hourglass
function waitcursor() {
document.body.style.cursor = 'wait';
}

// Returns the cursor to the default pointer
function clearcursor() {
document.body.style.cursor = 'default';
}
/*
function showInfoTip(title, innerHTML)
{
Tip(innerHTML, WIDTH, 300, TITLE, title, SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)
}*/
function showInfoTip(title, innerHTML)
{    
    if(ClickTaleIsIn("recording") && (typeof ClickTaleExec == "function"))
         ClickTaleExec("showInfoTip('"+title+"', '"+innerHTML+"')");
         
    ajaxwin=dhtmlwindow.open("infoWin", "inline", innerHTML, title, "left=270px,top=220px,resize=1,scrolling=0");
    _gaq.push(['_trackEvent', 'Info Tip', title]);
}

function ShowLiveChat(id,pageTitle)
{
	window.open('http://www.fightsupport.net/livezilla/livezilla.php?intgroup=' + id + '=&hg=Pw__&reset=true','','width=590,height=550,left=0,top=0,resizable=yes,menubar=no,location=yes,status=yes,scrollbars=yes');
	_gaq.push(['_trackEvent', 'Live Chat', pageTitle]);
}

function showDiggThis(){
    var newWindow = window.open('http://digg.com/submit/?phase=2&url='+ encodeURIComponent(location.href) +'&title='+encodeURIComponent(document.title),'diggThis','location=no,menubar=no,toolbar=no,scrollbars=yes');
    newWindow.focus();
    return false;
} 

//gets selected radio from a list
//RT 5/26/2010
function GetSelectedRadio(name)
{
    var radioButtons = document.getElementsByName(name);
      for (var x = 0; x < radioButtons.length; x++) {
        if (radioButtons[x].checked) {
          return radioButtons[x];
        }
      }
      return "";
} 

// Clears the field is the value is equal to the defaulText (if specified)
//YH 5/26/10
function ClearIfDefault(element)
{
    if(element.attributes["defaultText"] != null)
    {
        var defaultText = element.attributes["defaultText"].value;
        if(element.value == defaultText)
        {
            element.value = '';
        }
    }
}

//restore default text as content of input box - RT 10/26/10
function restoreDefaultText(element)
{
    if(element.value=='' && element.attributes["defaultText"] != null)
    {
        element.value = element.attributes["defaultText"].value;
    }
}


//cross-browser method for getting element that triggered the event. x is the event object
// RT 5/21/10
function getTarget(x){
    x = x || window.event;
    return x.target || x.srcElement;
} 

//gets URL parameter from a URL
function getUrlParam(url, name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

// function for preloading images... takes parameters of image paths
// RT 7/6/2010
function preloadImages() {
    for(var i=0; i<arguments.length; i++){
        var img = new Image();        // error image for validation
        img.src = arguments[i];
    }
}
// returns whether should perform clicktale action. should be used with clicktale functions to avoid error
// true if clicktale is loaded and in recording session, otherwise false
// RT 7/15/2010
function doClickTale() {
    if (typeof ClickTaleExec == "function") {
        if(ClickTaleIsIn("recording")) {
            return true;
        }
    } else {
        return false;
    }
}


function PadLeft(s, c, n) {
    if (! s || ! c || s.length >= n) {
        return s;
    }

    var max = (n - s.length)/c.length;
    for (var i = 0; i < max; i++) {
        s = c + s;
    }

    return s;
}

// right padding s with c to a total of n chars
function PadRight(s, c, n) {
    if (! s || ! c || s.length >= n) {
        return s;
    }

    var max = (n - s.length)/c.length;
    for (var i = 0; i < max; i++) {
        s += c;
    }

    return s;
}
// functions for editing personal account info
// RT 10/18/2010
function changeName(firstName, lastName, waitFunction, returnFunction) {
    if(typeof waitFunction == 'function') {
        waitFunction();
    }
    
    var url = 'process.aspx';
    var params = 'type=updatename&fname='+firstName+'&lname='+lastName;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
function changePassword(oldPassword, newPassword, confirmPassword, waitFunction, returnFunction) {
    if(newPassword != confirmPassword)
    {
        if(typeof returnFunction == 'function') {
            returnFunction("Confirm password does not match. Please retype your new password.", 'password');
        }
        return false;
    }
    if(typeof waitFunction == 'function') {
        waitFunction();
    }
    

    var url = 'process.aspx';
    var params = 'type=updatepassword&oldPassword='+oldPassword+'&newPassword='+newPassword;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
function changeEmail(email, waitFunction, returnFunction) {
    if(typeof waitFunction == 'function') {
        waitFunction();
    }
    
    var url = 'process.aspx';
    var params = 'type=updateemail&email='+email;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
function changeDisplayName(displayName, waitFunction, returnFunction) {
    if(typeof waitFunction == 'function') {
        waitFunction();
    }
    
    var url = 'process.aspx';
    var params = 'type=updatedisplayname&displayName='+displayName;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
function changeLocation(location, waitFunction, returnFunction) {
    if(typeof waitFunction == 'function') {
        waitFunction();
    }
    
    var url = 'process.aspx';
    var params = 'type=updatelocation&location='+location;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
function changeBio(bio, waitFunction, returnFunction) {
    if(typeof waitFunction == 'function') {
        waitFunction();
    }
    
    var url = 'process.aspx';
    var params = 'type=updatebio&bio='+bio;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}

//shows orders that match the order number typed so far
// RT 11/02/10 
function showMatchingOrders(order_num) 
{
    $$("div[id^=order_]").each(
        function(div){
            div.hide();
        });
        
    if($$("div[id^=order_"+order_num.toUpperCase()+"]").length < 1)
    {
        $('noMatchingOrders').show();
    } 
    else
    {
        $('noMatchingOrders').hide();
            
        //show those that match whats in the textbox
        $$("div[id^=order_"+order_num.toUpperCase()+"]").each(
            function(div){
                div.show();
            });
    }
}
    
function deleteCartItemBySku(sku, returnFunction) {    
    var url = 'process.aspx';
    var params = 'type=removecartitem&sku='+sku;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
function deleteCartItem(id, returnFunction) {    
    var url = 'process.aspx';
    var params = 'type=removecartitembyid&id='+id;

    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}

// check that HTML5 video can be played... needed for FF which will show embedded video element
// even if it cant play it
// RT 11/16/2010
var detectVideoSupport = function (){
    var detect = document.createElement('video') || false;
    this.html5 = detect && typeof detect.canPlayType !== "undefined";
    this.mp4 = this.html5 && (detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably");
    this.ogg = this.html5 && (detect.canPlayType("video/ogg") === "maybe" || detect.canPlayType("video/ogg") === "probably");
    return this;
};

//complete an ajax request
//RT 01/20/2011
function completeAjaxRequest(url, params, returnFunction){
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
        function(result) {
            if(typeof returnFunction == 'function') {
                returnFunction(result.responseText);
            }
        }        
    });
}
//delete user list. RT -3/11/2011
function deleteUserList(i, returnFunction)
{
    var params = "type=deleteuserlist&id=" + i;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }        
        });
}
//delete user list item. RT -3/14/2011
function deleteUserListItem(site_sku, list_id, returnFunction)
{
    var params = "type=deleteuserlistitem&sku=" + site_sku + "&list_id=" + list_id;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }        
        });
}
//edit a product note, RT - 1/27/2011
function editProductNote(i, newtext, returnFunction)
{
    var params = "type=editnote&id=" + i + "&text=" + newtext;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }       
        });
}
//edit list description
function editListNote(listId, noteText, returnFunction)
{
    var params = "type=editlistnote&id=" + listId + "&text=" + noteText;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }       
        });
}
//delete a product note, RT - 1/27/2011
function deleteProductNote(i, returnFunction)
{
    var params = "type=deletenote&id=" + i;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }        
        });
}
//edit product note by sku
function editProductNoteForSku(sku, newtext, returnFunction) {
    var params = "type=editnoteforsku&sku=" + sku + "&text=" + newtext;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }       
        });
}
//edit product note by sku
function editProductCartNote(cartId, noteText, returnFunction) {
    var params = "type=addcartnote&note=" + noteText;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }       
        });
}
//set user's default address
//RT 2/17/2011
function setUserDefaultAddress(addressId, returnFunction) {
    var params = "type=setdefaultaddress&id=" + addressId;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }       
        });
}
//set user's default payment method
//RT 2/17/2011
function setUserDefaultPayment(methodId, returnFunction) {
    var params = "type=setdefaultpaymentmethod&id=" + methodId;
    var myAjax = new Ajax.Request( "process.aspx", { method: 'get', parameters: params, onComplete: 
            function(result) {
                if(typeof returnFunction == 'function') {
                    returnFunction(result.responseText);
                }
            }       
        });
}

//fix for http://www.codeproject.com/KB/aspnet/pendingcallbacks.aspx
function WebForm_CallbackComplete_SyncFixed() {
     // the var statement ensure the variable is not global
     for (var i = 0; i < __pendingCallbacks.length; i++) {
        callbackObject = __pendingCallbacks[i];
        if (callbackObject && callbackObject.xmlRequest && 
			(callbackObject.xmlRequest.readyState == 4)) {
            // SyncFixed: line move below // WebForm_ExecuteCallback(callbackObject);
            if (!__pendingCallbacks[i].async) { 
                __synchronousCallBackIndex = -1;
            }
            __pendingCallbacks[i] = null;
            var callbackFrameID = "__CALLBACKFRAME" + i;
            var xmlRequestFrame = document.getElementById(callbackFrameID);
            if (xmlRequestFrame) {
                xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
            }
            // SyncFixed: the following statement has been moved down from above;
            WebForm_ExecuteCallback(callbackObject);
        }
    }
}

var OnloadWithoutSyncFixed = window.onload;

window.onload = function Onload(){
    if (typeof (WebForm_CallbackComplete) == "function") {
        // Set the fixed version
        WebForm_CallbackComplete = WebForm_CallbackComplete_SyncFixed;
        // CallTheOriginal OnLoad
        if (OnloadWithoutSyncFixed!=null) OnloadWithoutSyncFixed();
    }
}
//]]>

//cookie functions from http://www.elated.com/articles/javascript-and-cookies/
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}



function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function updateCheckoutCountryDropdown(countrycode) {
    Event.onDOMReady(function(){
        $("countryDropdown").show();
        removeOptionsOtherThan($$("select[id$=_Country]")[0], [countrycode]);
    });
}

//if image doesnt exist, loads alternate. RT 11/22/2011
function GetImageToShow(imageUrl, onsuccess, onfailure)
{
    var brandBgImage = new Image();
    brandBgImage.name = "tmpImage";
    brandBgImage.onload = onsuccess.bind(brandBgImage);
    brandBgImage.onerror = onfailure.bind(brandBgImage);
    brandBgImage.src = imageUrl;   //use actual brand 
}
