var req;
var addrReq;
var addrListReq;
var showReq;
var ns4 = (document.layers) ? true : false;
var ie4 = (document.all && !document.getElementById) ? true : false;
var ie5 = (document.all && document.getElementById) ? true : false;
var ns6 = (!document.all && document.getElementById) ? true : false;
var gender = ""
var cat = ""
var subcat = ""
var color = ""
var size = ""
var width = ""
var brand = ""
var sort = "1"
var isFURL = true //is Friendly URL. For reloading the page and keeping the group/FU information. Mainly for sort. 
qs=""
function callPage(pageUrl, divElementId, loadinglMessage, pageErrorMessage) {
     document.getElementById(divElementId).innerHTML = loadinglMessage;
     req=GetXmlHttpObject(); 
     req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);};
     req.open("GET",pageUrl,true);
     req.send(null);
  }
function responsefromServer(divElementId, pageErrorMessage) {
   var output = '';
   if(req.readyState == 4) {
       output = req.responseText;
       if (req.status == 200) {         
         document.getElementById(divElementId).innerHTML = output;         
         } else {
         document.getElementById(divElementId).innerHTML = pageErrorMessage+"\n"+output;
         }
      }
  }
  
function callPageWReq(pageURL, divElementID, loadingMessage, pageErrorMessage, theReq) {
    document.getElementById(divElementID).innerHTML=loadingMessage;
    theReq=GetXmlHttpObject();
    theReq.onreadystatechange=function() {responsefromServerWReq(divElementID,pageErrorMessage,theReq)}
    theReq.open("GET",pageURL,true)
    theReq.send(null);
}
function responsefromServerWReq(divElementId, pageErrorMessage, theReq) {
   var output = '';
   if(theReq.readyState == 4) {      
      if(theReq.status == 200) {
         output = theReq.responseText;      
         document.getElementById(divElementId).innerHTML = output;
       } else {
         document.getElementById(divElementId).innerHTML = pageErrorMessage+"\n"+output;
       }
   }
}
//Function to get encoded data for Checkout by Amazon
function encodeme(mycart) {
    URL = "/cba/cbaencoder.aspx?cart=" + mycart
    callEncodePage(URL)
}
function callEncodePage(pageUrl) {
    req = GetXmlHttpObject();
    req.onreadystatechange = function() { responsefromServerEncode(); };
    req.open("GET", pageUrl, true);
    req.send(null);
}
function responsefromServerEncode() {
    var output = '';
    if (req.readyState == 4) {
        output = req.responseText;
        if (req.status == 200) {
            document.getElementById("merchant_signature").value = output;
            document.getElementById("cbaButton1").style.display = 'block';
        } else {
            alert(output)
            //document.getElementById(divElementId).innerHTML = pageErrorMessage + "\n" + output;
        }
    }
}
/* this function is for tab panels */
function activeTab(tab,destpage,destdiv)
{   	

	document.getElementById("tab"+tab).className = "active";
	if(destdiv=='content')
	{
		show(false,'tabdiv');
		show(true,'content');
	}else{
		show(true,'tabdiv');
		show(false,'content');
	}	
	callPage(destpage, destdiv, '<img src=\"imgs/loading.gif\" /> content is loading, please wait...', 'error in loading page <img src=\"imgs/error_caution.gif\" />');		
}

function aPostForm(formName,divElementId) {
    var pageErrorMessage='Error in Loading page';
    req=GetXmlHttpObject();
    pagename="login1.aspx";
    passData='&dowhat=Login';
    if (null == eval("document."+formName+".UserName.value")) {
        frmuser="";
    }else{
        frmuser=eval("document."+formName+".UserName.value");
    }    
    if (null == eval("document."+formName+".Password.value")) {
        frmpassword="";   
    }else{
        frmpassword=eval("document."+formName+".Password.value");
    }   
    
    passData='dowhat=Login';
    passData=passData+'&Password='+escape(frmpassword);
    passData=passData+'&UserName='+escape(frmuser);

    req.open("POST",pagename,true); 
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);}; 
    req.send(passData);
}

function aQuerystringForm(formName,divElementId){
    var pageErrorMessage='Error in Loading page';
    req=GetXmlHttpObject();
    pagename="survey.aspx";  
    frmmember=eval("document."+formName+".member.value");
    frmsurveyid=eval("document."+formName+".surveyid.value");
    for (var i=0; i < document.frmSurvey.answer.length; i++)
    {
    if (document.frmSurvey.answer[i].checked)
      {
      var rad_val = document.frmSurvey.answer[i].value;
      }
    }
    frmanswer = rad_val;
    passData='member='+escape(frmmember);
    passData=passData+'&answer='+escape(frmanswer);
    passData=passData+'&surveyid='+escape(frmsurveyid);
    passData=passData+'&dowhat=save';
    
    req.open("POST",pagename,true); 
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);}; 
    req.send(passData);
}
function singleCall(destpage,destdiv) {
    callPage(destpage,destdiv,'<img src=\"imgs/loading.gif\" /> content is loading, please wait...', 'error in loading page');
}

function nothingfunction(){
}

function GetXmlHttpObject() {
   var xmlHttp=null;
   try  { // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
   }
   catch (e) {  // Internet Explorer
      try {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   return xmlHttp;
}


function showme(divname){
	showdis=document.getElementById(divname).innerHTML
	document.getElementById('showmetext').value=showdis
}
function calPickDay(theday,themonth,theyear) {
    destpage="quickCalendar.aspx?monum=" + themonth + "&daynum=" + theday + "&yearnum=" + theyear
    callPage(destpage, 'calspan', '<img src=\"imgs/loading.gif\" /> content is loading, please wait...', 'error in loading page <img src=\"imgs/error_caution.gif\" />');		

}
function popupme() {
    alert("Got Here");
}
 function EditLine(formName,divElementId,pagename,editID) {
    var pageErrorMessage='Error in Loading page';
    req=GetXmlHttpObject();    
    passData='dowhat=Edit';
    passData=passData+'&editID='+editID;
    req.open("POST",pagename,true); 
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.onreadystatechange = function() {responsefromServer(divElementId, pageErrorMessage);}; 
    req.send(passData);
}

function gotoPage(pagename)  {
    parent.location = pagename
}
function show(sw,obj) {
	// show/hide the divisions
	if (sw && (ie4 || ie5) ) document.all[obj].style.visibility = 'visible';
	if (!sw && (ie4 || ie5) ) document.all[obj].style.visibility = 'hidden';
	if (sw && ns4) document.layers[obj].visibility = 'visible';
	if (!sw && ns4) document.layers[obj].visibility = 'hidden';
}
function openeditX(HT,WT,sbars) {
	var winX = (document.all)?window.screenLeft:window.screenX;
	var winY = (document.all)?window.screenTop:window.screenY;
	theX=parseFloat(winX)+parseFloat(100)
	theY=parseFloat(winY)+parseFloat(50)
	var W = "height="+HT+",width="+WT+",scrollbars="+sbars+",left="+theX+",top="+theY
	editwinX=open("blank.html","editwinX",W)
	return true
}

function loadBrands(gender) {    
    document.getElementById("womens-tab").className="tab"
    document.getElementById("mens-tab").className="tab"
    document.getElementById("kids-tab").className = "tab"
    document.getElementById("infants-tab").className = "tab"    
    if (gender=="F") {
        document.getElementById("womens-tab").className="tab active"        
    }
    if (gender=="M") {
        document.getElementById("mens-tab").className="tab active"
    }
    if (gender=="K") {
        document.getElementById("kids-tab").className="tab active"
    }
    if (gender == "I") {
        document.getElementById("infants-tab").className = "tab active"
    }    
    url="brands.asp?gender=" + gender
    callPage(url,"tabbrand","Loading","Hmmm guess that didn't work.")
}

function selectGender(gender, field, value) { //This is for the brandlist page. Sets the gender of the QS to be passed to the search.
    qs = gender + qs
    reloadPage(field,value)
}
function reloadPage(field, value) {
    setField(field, value)
	window.location="shoelistpage.asp?qs=" + qs
}
function reloadWordSearch(value) {
    window.location = "tsaSearch.asp?thispage=" + value
}
function setField(field, value) {
        arrQS = new Array
	arrQS=qs.split("~")
	if (field!=8) {
	   arrQS[8]=1
    }
    if (field == 1 || field == 2) {   // category and sub category
	   arrQS[2]="*"  // clear subcat
	   arrQS[3]="*"  // clear brand
	   arrQS[4]="*"  // clear size
	   arrQS[5]="*"  // clear width	   
	   arrQS[6]="*"  // clear color
	   arrQS[7]="*"  // clear price
	}
	if (field == 3) {
	   if (value == "*") {arrQS[2] = "*"}
	   arrQS[4] = "*"
	   arrQS[5] = "*"
	   arrQS[6] = "*"  // clear color
	   arrQS[7] = "*"  // clear price
	}	
	arrQS[field]=value
	qs=""
	for (x=0;x<arrQS.length;x++) {
		qs=qs+arrQS[x]+"~"
	}
	qs=qs.substr(0,qs.length-1)
	
}
function setGender() {
    theGender = document.getElementById("SelGender").value
    setField(0, theGender)
    //document.getElementById("genderrolls").style.display = "none"
    //document.getElementById("select-menu").style.display = "block"
    URL = "/searchoptions.asp?gender=" + theGender 
    callPage(URL,"genderrolls","Loading more options...","Loading failed.")
}
function setSizeWidthColor() {
	theSize=document.getElementById("size").value
	theWidth=document.getElementById("width").value
	theColor = document.getElementById("color").value
	thePrice = document.getElementById("ssPrice").value
	setField(7,thePrice)
	setField(6,theColor)
	setField(4,theSize)
	setField(5,theWidth)	
	window.location="shoelistpage.asp?qs=" + qs
}
function setSizeWidthColorWS() {
    theSize = document.getElementById("size").value
    theWidth = document.getElementById("width").value
    theColor = document.getElementById("color").value
    window.location = "tsaSearch.asp?size=" + theSize + "&width=" + theWidth + "&color=" + theColor + "&thisPage=1"
}
function setPullDowns(thesize,thewidth,thecolor) {
	pdsize=document.getElementById("size")
	if (thesize!="*" && thesize!="%") {
		pdsize.value=thesize
	}
	pdwidth=document.getElementById("width")
	if (thewidth != "*" && thewidth != "%") {		
		pdwidth.value=thewidth
	}
	pdcolor=document.getElementById("color")
	if (thecolor != "*" && thecolor != "%") {
		pdcolor.value=thecolor
	}
	
}	

function reviewTab(shoenum,maxnum) {
  	url="reviews.asp?shoenum=" + shoenum +"&maxnum=" + maxnum 
  	document.getElementById("revlink").className="active"
  	document.getElementById("sizelink").className=""
  	callPage(url,"revtab","Loading...","Guess that was a really bad review... WHOA...")
}  	
function sizeChartTab(vendornum,catID,gender,invno) {
    url = "sizechart.asp?vendornum=" + vendornum
    url = url + "&catID=" + catID
    url = url + "&gender=" + gender
    url = url + "&invno=" + invno
  	document.getElementById("sizelink").className="active"
  	document.getElementById("revlink").className=""
        
        callPage(url,"revtab","Loading...","Size Chart is unavailable at the moment.")
}        
function switchshoe(newshoe,majorID) {
	window.location="item.asp?invnum=" + newshoe.value
}

function checkqty() {
	if (document.tocart.ShoeSelected.selectedIndex<=0) {
			alert("Please Select a shoe")
			return false;
	}
	parts=document.tocart.ShoeSelected[document.tocart.ShoeSelected.selectedIndex].value.split("^")
	if (parts[4]<parseFloat(document.tocart.qtynum.value)) {
		alert("We are sorry, there's currently "+ parts[4] + " available. Please change the quantity to continue.")
		return false
	}
	document.tocart.submit()
}
function openPoll(theshoe) {
	window.open("poll.asp?invnum=" + theshoe,"poll","width=845,height=500")
}

function switchImg2(newimage) {
	newimage="/resize/resizeimg.aspx?img="+newimage+"&height=360"
	shoeImg=document.getElementById("theShoeImage")
	shoeImg.src=newimage
}

function signMeUp(theEmail) {
    if (theEmail == "addemail2") {
        theDiv = "emailsignup2"
    } else {
        theDiv = "emailsignup"
    }
    thisEmail=document.getElementById(theEmail).value
    if (thisEmail.indexOf("@")==-1 || thisEmail.indexOf(".")==-1) {
        alert("Please use a valid email.")
        return;    
    }
    url="signup.asp?email=" + thisEmail
    //callPage(url,theDiv,"Adding your name","Hmm.. that didn't work..")
    window.location=url
}    
    
function sendToFriend(theShoe) {
   window.open("sendfriend.asp?num="+escape(theShoe),"sendfriend","width=400,height=650")
}   

function openStatus() {
   window.open("reqstatus.asp","statuswin","width=1000,height=800,scrollbars=1")
}   
function openedit1() {
	var winX = (document.all)?window.screenLeft:window.screenX;
	var winY = (document.all)?window.screenTop:window.screenY;
	theX=parseFloat(winX)+parseFloat(100)
	theY=parseFloat(winY)+parseFloat(50)
	var W = "height=400,width=550,scrollbars=yes,left="+theX+",top="+theY
	editwin1=open("blank.html","editwin1",W)
	return true
}
function checkResponse() {
    checkXWeb("/peltzCC/checkResponse.aspx", "response", "", "Unable to communicate with our credit card processor.  Please try later.")
}

function checkXWeb(pageUrl, divElementId, loadinglMessage, pageErrorMessage) {
    document.getElementById(divElementId).innerHTML = loadinglMessage;
    req = GetXmlHttpObject();
    req.onreadystatechange = function() { whatwastheresponse(divElementId, pageErrorMessage); };
    req.open("GET", pageUrl, true);
    req.send(null);
}
function whatwastheresponse(divElementId, pageErrorMessage) {
    var output = '';
    if (req.readyState == 4) {
        if (req.status == 200) {
            output = req.responseText;
            parts = output.split("~")
            //document.getElementById(divElementId).innerHTML = output            
            if (parts[0] == "000") {
                document.frm_checkout.approval.value = parts[1]
                document.frm_checkout.transID.value = parts[2]
                document.frm_checkout.ccnum.value = parts[3]
                document.frm_checkout.AVSCode.value = parts[4]
                document.frm_checkout.alias.value = parts[5]
                document.frm_checkout.cvv.value = parts[6]
                document.frm_checkout.cctype.value = parts[7]
                document.frm_checkout.submit()
            } else {
                if (parts[0] == "101") {
                    document.getElementById("ccinfo").innerHTML = '<a href="#ccinfo" onclick="getCCInfo()"><img src="/images/proceedtopayment.jpg" alt="Proceed to Payment" title="Proceed to Payment"/></p>'
                    clicked = 0;
                } else {
                    startchecking()
                }
            }
        } else {
            document.getElementById(divElementId).innerHTML = pageErrorMessage + "\n" + output;
        }
    }

}

function startchecking() {
    setTimeout("checkResponse()", 5)
}

var isloggedin

function loggedin() {      
    req = GetXmlHttpObject();
    req.onreadystatechange = function() { setloggedin(); };
    req.open("GET", "chat/default2.aspx", true);
    req.send(null);
}
function setloggedin() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            isloggedin = req.responseText
        } else {
            isloggedin='no'
            //alert(req.responseText)
        }
        
    }
}
var preq
function checkpromo(someTxtfld) {
    document.getElementById("promomessage").innerHTML = "Loading...."
    preq = GetXmlHttpObject();
    preq.onreadystatechange = setpromocode
    someTxtfld.value = someTxtfld.value.replace(" ", "")
    someTxtfld.value = someTxtfld.value.toUpperCase()
    preq.open("GET", "checkcode.asp?promocode=" + someTxtfld.value, true)
    preq.send(null);    
}
function setpromocode() {
    if (preq.readyState == 4) {
        disc = 0
        calcTotal()
        if (preq.status == 200) {
            results = preq.responseText
            parts = results.split(",")
            if (parts[0] < 0) {
                document.getElementById("promomessage").innerHTML = "<span class=\"error\">" + parts[1] + "</span>"
            } else {
                discparts = parts[1].split("~")
                disc = parseFloat(discparts[0])
                document.getElementById("dispDisc").className="seen"
                calcTotal()
                document.getElementById("promomessage").innerHTML="<span class=\"error\">Code Applied</span>" 
            }
        } else {
            alert(preq.responseText)
        }
    }
}
function updateprice(Code,total) {
    parts = Code.value.split("~")
    newtotal = total * 1 + parts[1] * 1
    if (parts[1] == 0) {
        document.getElementById("shipCost").innerHTML = "FREE"
    } else {
        document.getElementById("shipCost").innerHTML = formatCurrency(parts[1])
    }
    document.getElementById("COBut1").href = "/checkout.asp?code=" + parts[0]
    document.getElementById("COBut2").href = "/checkout.asp?code=" + parts[0]
    document.getElementById("carttotal").innerHTML = formatCurrency(newtotal)
}
function formatCurrency(num) {
    // remove old formating
    num = num.toString().replace(/\$|\,/g, '')
    // check to see if it is numeric if not set to 0
    if (isNaN(num)) num = "0"
    // check to see if this is a neg number
    sign = (num == (num = Math.abs(num)));
    // round to the nearest penny
    num = Math.floor(num * 100 + 0.50000000001);
    // grab the cents part  using the MOD command
    cents = num % 100;
    // grab the non cents part by grapping just the dollars
    num = Math.floor(num / 100).toString();
    // Put a preceeding 0 in front of the cents
    if (cents < 10) cents = "0" + cents;
    // add commas every 3 numbers 
    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 the formated number
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function conversion() {
    var style = ""
    var vendor = ""
    var conGender = ""
    if (document.getElementById("constyle").value.length > 1) {
        style = document.getElementById("constyle").value
    }
    if (document.getElementById("convendor").value.length > 1) {
        vendor = document.getElementById("convendor").value
    }
    if (document.getElementById("congender").value.length > 1) {
        conGender = document.getElementById("congender").value
    }
    if (style != "" || vendor != "" || conGender != "") {
        URL = "fillConversion.asp?constyle=" + style
        URL = URL + "&convendor=" + vendor
        URL = URL + "&conGender=" + conGender
        callPage(URL, "conversion", "Gathering Info...", "Oh noes! My conversion table is gone...")
    }
}
function conversionDel() {
    //Same as above, but with a dowhat.
    var style = ""
    var vendor = ""
    var conGender = ""
    var dowhat = ""
    var conscID = document.getElementById("conscID").value
    if (document.getElementById("constyle").value.length > 1) {
        style = document.getElementById("constyle").value
    }
    if (document.getElementById("convendor").value.length > 1) {
        vendor = document.getElementById("convendor").value
    }
    if (document.getElementById("congender").value.length > 1) {
        conGender = document.getElementById("congender").value
    }
    if (document.getElementById("condowhat").value.length > 1) {
        X = confirm("Are you sure you want to delete?")
        if (X) {
            dowhat = document.getElementById("condowhat").value
        }
    }
    if (style != "" || vendor != "" || conGender != "") {
        URL = "fillConversion.asp?constyle=" + style
        URL = URL + "&convendor=" + vendor
        URL = URL + "&conGender=" + conGender
        URL = URL + "&dowhat=" + dowhat
        URL = URL + "&conscID=" + conscID
        callPage(URL, "conversion", "Gathering Info...", "Oh noes! My conversion table is gone...")
    }
}
function GetPrices() {
    URL = "Prices.asp"
    callPageWReq(URL, "PriceLookUp", "", "FAILED")

}
