//shopfunc.js

//EMAIL / FORM Verification
//function submitInfo(host,action,form,secure){
function submitInfo(host,action,secure){
//alert('secure '+secure);
    if (secure == 1)
        action = 'https://'+host+'/'+action;
    else 
        action = 'http://'+host+'/'+action;
    document.forms['navinfo'].action = action;
    document.forms['navinfo'].submit();
}

function sndml(emailhost){
  var email     = "contact";
  window.location='mailto:'+email+'@'+emailhost;
}

function checkemail(email){
    if (!emailisvalid(email)){
        alert('Email doesn\'t appear to be a valid address'); 
        return false;
    }
    else
        return true;
}

function checkpassword(password,passconf){
    if ( password.length < 6){
        alert('Password error: Must be at least 6 characters long'); 
        return false;
    }
 
    if (passconf.length > 0 && password != passconf){
        alert('Password mismatch: Please Re-enter Password and Retype Password'); 
        return false;
    }
    return true;
}

function setonmaillist(){
    if (document.getElementById('onmaillistbox').checked == true)
        document.getElementById('onmaillist').value = 1;
    else
        document.getElementById('onmaillist').value = 0;
 
//alert(document.forms['navinfo'].onmaillist.value);
}

function checkentry(frm){
    //if new login need to set top login values so passes empty check
    if (frm.email.value.length > 0  && frm.email1 != null)
        frm.email1.value = frm.email.value;
    if (frm.password.value.length > 0 && frm.password1 != null)
        frm.password1.value = frm.password.value;
    frm.company.optional    = "true";
    frm.phone2.optional     = "true";
    frm.b_address2.optional = "true";
    frm.firstname2.optional = "true";
    frm.lastname2.optional  = "true";
    frm.phone3.optional     = "true";
    frm.s_address2.optional = "true";
    var msg;
    var empty_fields = "";
    var empcnt = 0;
    var errors = "";

    for (var i=0; i<frm.length; i++){
        var e = frm.elements[i];
        if ((e.type == "text" || e.type == "textarea" || e.type == "password") && !e.optional && e.name != "sw1"){
             if ((e.value == null) || (e.value == "") || isblank(e.value)){
                empty_fields += "\n        "+ e.title;
                empcnt++;
                continue;
             }
             if (e.name == "password" && frm.password.value.length < 6)
                 errors += "- Password Error: Must be at least 6 characters long\n";   
             if (e.name == "passconf" && frm.password.value != frm.passconf.value)
                 errors += "- Password Error: Re-enter Password and Retype Password\n";   
             
             if (e.name == "email"){
                if (!emailisvalid(e.value))
                   errors += "- Email doesn't appear to be valid\n";
             }
/*
            //check for numeric only fields
            if (e.numeric || (e.min != null) || (e.max != null)){
                var v = parseFloat(e.value);
                if (isNaN(v) || ((e.min != null) && (v < e.min)) ||
                                ((e.max != null) && (v > e.max)))
                {
                    errors += "- The entry " + e.title + " must be a number";
                    if (e.min != null)
                         errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null)
                         errors += " and less than " + e.max;
                    else if (e.max != null)
                         errors += " that is less than " + e.max;
                    errors += ".\n";
                 }
             }
*/
        }
    }//end for
    if (frm.shipinfo != null && frm.shipinfo.value == "0,0.0")
        errors += "- Shipping Method Error: You must choose a Shipping Method\n";  

    if (frm.b_state.value == "")
        errors += "- You must choose a State/Province\n";  
     if (frm.s_state.value == "")
        errors += "- You must choose a Shipping State/Province\n";  
            
    if (!empty_fields && !errors)
        return true;

    msg =  "______________________________________________\n\n";
    msg += "We'll still need more information to finish your order.\n";
    msg += "Please recheck the following to complete your Ordering Information:\n";
    msg += "______________________________________________\n\n";

    if (empty_fields)
    {
        if (empcnt > 1)
            msg += "- The following required entries are blank:" + empty_fields + "\n";
        else
            msg += "- The following required entry is blank:" + empty_fields + "\n";

        if (errors) 
            msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

function hasBlanks(str){
    for (var i = 0; i< str.length; i++){
        var c = str.charAt(i);
        if (c == ' ') 
            return true;
    }
    return false;
}

function isblank(str){
    for (var i = 0; i< str.length; i++){
        var c = str.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) 
            return false;
    }
    return true;
}

function emailisvalid(str){
    var foundat  = false;
    var founddot = false;
    for (var i = 0; i< str.length; i++){
        if (str.charAt(i) == '@')
            foundat = true;
        if (str.charAt(i) == '.')
            founddot = true;
    }
    if (foundat && founddot)
        return true;
    else
        return false;
}

//SHOPPING CART FUNCTIONS

//check for related checkboxes that might need changing
function checkOptchks(lx){
    optchecked = document.getElementById('lnbox'+lx).checked;
    xstr = String(lx+1);	//start at first addon below this opt
    x = parseInt(xstr);
    //Check any Addons - if dependent and this opt is being unchecked - unclick them
    if (!optchecked){		//this option is still true but has just been deselected - so turn off all dependent addons
        document.getElementById('quantity'+lx).value = 0;		//set qty to 0
        document.getElementById('total'+lx).value = '$0.00';	//set total to 0
        while (document.getElementById('prodtype'+xstr).value == 5){
            dependent = document.getElementById('dependent'+xstr).value;
            if (dependent == 1){
                document.getElementById('lnbox'+xstr).checked = false;
                document.getElementById('quantity'+xstr).value = 0;
                document.getElementById('total'+xstr).value = '$0.00';
            }
            x++;
            xstr = String(x);
        }
    }else{		//this option was just selected - so set qty to 1 and total
        document.getElementById('quantity'+lx).value = 1;
        price = document.getElementById('price'+lx).value;
        price = price.substr(1);	//remove prepended $
        total = document.getElementById('quantity'+lx).value * price;
        document.getElementById('total'+lx).value = '$'+total.toFixed(2);
        document.getElementById('origqty'+lx).value = document.getElementById('quantity'+lx).value;
    }
    updItemTot();
}

//check for related checkboxes that might need changing
function checkAddchks(lx,paridx){
    addchecked = document.getElementById('lnbox'+lx).checked;		//is this addon being checked or unchecked?
    if (!addchecked){		//it has just been unchecked - so clear qty,total
        document.getElementById('quantity'+lx).value = 0;
        document.getElementById('origqty'+lx).value = 0;
        document.getElementById('total'+lx).value = '$0.00';
    }else{								//addon is being checked
	dependent = document.getElementById('dependent'+lx).value;		//is this addon dependent on parent
        parchecked = document.getElementById('lnbox'+paridx).checked;		//is parent checked
        if (dependent == 1 && !parchecked){					//if addon just selected and parent hasn't, select parent,qty,total automatically
            document.getElementById('lnbox'+paridx).checked = true;	//check parent
            //parname = document.getElementById('itemname'+paridx).value;			//don't really need to tell them
            //alert('Since this Add On relates to the \''+parname+'\'. It has now been selected');
            document.getElementById('quantity'+paridx).value = 1;	//set parents qty to 1
            document.getElementById('origqty'+paridx).value = 1;	//set origqty to 1
            price = document.getElementById('price'+paridx).value;
            price = price.substr(1);	//remove prepended $
            total = document.getElementById('quantity'+paridx).value * price;
            document.getElementById('total'+paridx).value = '$'+total.toFixed(2); 
        }
        //Set this addons values
        if (dependent == 1){		
            document.getElementById('quantity'+lx).value = document.getElementById('quantity'+paridx).value;   //set qty to par qty
        }else{
            document.getElementById('quantity'+lx).value = 1;   //just initialize to 1
            document.getElementById('origqty'+lx).value = document.getElementById('quantity'+lx).value;
        }
        price = document.getElementById('price'+lx).value;
        price = price.substr(1);	//remove prepended $
        total = document.getElementById('quantity'+lx).value * price;
        document.getElementById('total'+lx).value = '$'+total.toFixed(2);
        //document.getElementById('total'+lx).value = '$'+price.toFixed(2);	//set addon's total just to it's price (qty = 1)
        //document.getElementById('total'+lx).value = '$'+price;	//set addon's total 

        if (dependent == 1){		//if dependent, only allow one addon selected - emulate radio button
            xstr = String(paridx+1);	//start at first addon below parent
            x = parseInt(xstr);
            //Make checkbox act like radio button - scan all addons for this parent and turn off checks
            while (document.getElementById('prodtype'+xstr).value == 5){
                if (x != lx){				//if this line isn't the one that came in checked - uncheck it
                    document.getElementById('lnbox'+xstr).checked = false;
                    document.getElementById('quantity'+xstr).value = 0;
                    document.getElementById('total'+xstr).value = '$0.00';
                }
                x++;
                xstr = String(x);
            }
        }
    }
    updItemTot();
}



//check that at least one item is to be added to the shopping cart
function selectsOK(lncnt){
    error=false;
    checked = false;
    for (lx=0;lx<lncnt;lx++){
//alert('lx '+lx);
        if (document.getElementById('lnbox'+lx).checked){
            checked = true;
            document.getElementById('lnbox'+lx).value=1;		//set to selected
//alert('chked '+document.getElementById('lnbox'+lx).value);
        }else
            document.getElementById('lnbox'+lx).value=0;		//set to unselected

//alert('chked '+document.getElementById('lnbox'+lx).value);
    }

    if (!checked){
        alert('Sorry - You must select something in order for it to be added to the Shopping Cart');
        error = true;
    }
    return !error;
}

function checkQty(idx,pcatid,prodid,ordlineid,price,ordsku){
    if (document.getElementById('quantity'+idx).value!= document.getElementById('origqty'+idx).value){
        document.forms['navinfo'].newqty.value=document.getElementById('quantity'+idx).value;
        document.forms['navinfo'].mode.value='Q';
        document.forms['navinfo'].pcatid.value=pcatid;
        document.forms['navinfo'].prodid.value=prodid;
        document.forms['navinfo'].ordlineid.value=ordlineid;
        document.forms['navinfo'].price.value=price;
        document.forms['navinfo'].ordsku.value=ordsku;
        document.forms['navinfo'].pgname.value = 'shopping-cart.php';
        document.forms['navinfo'].action='poster.php';
        document.forms['navinfo'].submit();
     }
}

//update product-details.php line Option items totals
function updOptTotal(lx){
    if (document.getElementById('quantity'+lx).value != document.getElementById('origqty'+lx).value) {
        if (document.getElementById('lnbox'+lx).checked == false){
            document.getElementById('lnbox'+lx).checked = true;
            //parname = document.getElementById('itemname'+lx).value;					//don't really need to tell them
            //alert('This is the quantity of  \''+parname+'s\' which has now been selected');
        }
        price = document.getElementById('price'+lx).value;
        price = price.substr(1);	//remove prepended $
        total = document.getElementById('quantity'+lx).value * price;
        document.getElementById('total'+lx).value = '$'+total.toFixed(2);
        document.getElementById('origqty'+lx).value = document.getElementById('quantity'+lx).value;
    }

    //if there are dependent addons - and they are selected - need to update their qty also
    x = parseInt(lx)+1;
    xstr = String(x);	//start at first addon below this opt
    while (document.getElementById('prodtype'+xstr).value == 5){
        dependent = document.getElementById('dependent'+xstr).value;
        addchecked = document.getElementById('lnbox'+xstr).checked;
        if (dependent == 1 && addchecked){
            if (document.getElementById('quantity'+xstr).value > document.getElementById('quantity'+lx).value){
                document.getElementById('quantity'+xstr).value = document.getElementById('quantity'+lx).value; //set to parents qty
                price = document.getElementById('price'+xstr).value;
                price = price.substr(1);	//remove prepended $
                total = document.getElementById('quantity'+xstr).value * price;
                document.getElementById('total'+xstr).value = '$'+total.toFixed(2);
            }
        }
        x++;
        xstr = String(x);
    }
    updItemTot();
}


//update product-details.php line Addon items totals
function updAddTotal(lx,paridx){
    if (document.getElementById('quantity'+lx).value != document.getElementById('origqty'+lx).value) {
        if (document.getElementById('quantity'+lx).value > 0){		//if box not checked - check it
            document.getElementById('lnbox'+lx).checked = true;

            dependent = document.getElementById('dependent'+lx).value;	//is dependent?

            if (dependent){
                document.getElementById('lnbox'+paridx).checked = true;	//check parent option even if it is already checked

                if (document.getElementById('quantity'+paridx).value < document.getElementById('quantity'+lx).value)
                    document.getElementById('quantity'+paridx).value = document.getElementById('quantity'+lx).value; //if less set par to addon qty
                price = document.getElementById('price'+paridx).value;
                price = price.substr(1);	//remove prepended $
                total = document.getElementById('quantity'+paridx).value * price;
                document.getElementById('total'+paridx).value = '$'+total.toFixed(2);
            }

        }else
            document.getElementById('lnbox'+lx).checked = false;

        document.getElementById('origqty'+lx).value = document.getElementById('quantity'+lx).value;
        price = document.getElementById('price'+lx).value;
        price = price.substr(1);	//remove prepended $
        total = document.getElementById('quantity'+lx).value * price;
        document.getElementById('total'+lx).value = '$'+total.toFixed(2);
        

    }
    updItemTot();
}
function updItemTot(){
    itemtot = 0.00;
    x = 1;
    xstr = String(x);
    while (document.getElementById('lnbox'+xstr)){
        total = document.getElementById('total'+xstr).value;
        total = total.substr(1);	//remove prepended $
        itemtot+=parseFloat(total);
        x++;
        xstr = String(x);	//start at first addon below this opt
    }
    document.getElementById('itemtot').value = '$'+itemtot.toFixed(2);
}


function adjustTotal(){
    adjtotal = parseFloat(document.getElementById('totcost').value) - parseFloat(document.getElementById('coupamt').value);
    document.getElementById('adjtotal').value = adjtotal.toFixed(2);
}


function copyAddr(){
    d = document.forms['navinfo'];
    d.firstname2.value = d.firstname1.value;
    d.lastname2.value  = d.lastname1.value;
    d.phone3.value     = d.phone1.value;
    d.s_address1.value = d.b_address1.value;
    d.s_address2.value = d.b_address2.value;
    d.s_city.value     = d.b_city.value;
    d.s_state.value    = d.b_state.value;
    d.s_zip.value      = d.b_zip.value;
    d.s_country.value  = d.b_country.value;
}

function placeOrder(host){
    var paymeth = document.getElementById('paymeth').value;
    if (paymeth == 0){
        alert('You must first choose a Payment Method:\nPay by Credit Card, Paypal or Check');
        return;
    }

    else{
        //everything is OK - so display the "please wait" div
       // document.forms['navinfo'].waitmsg.style.display = 'block';	
        document.getElementById('waitmsg').style.display = 'block';
        switch(parseInt(paymeth)){
            case 1:		//Payment via Credit Card 
                document.forms['navinfo'].mode.value = 'C';	     //Credit card via Request Money
                //document.forms['navinfo'].action = 'http://'+host+'/order-thank-you.php';
                break;
            case 2:		//Pay via Paypal
                document.forms['navinfo'].mode.value = 'P';	     //Paypal
                //document.forms['navinfo'].action = 'http://'+host+'/order-thank-you.php';
                break;
            case 3:		//Payment is by check
                document.forms['navinfo'].mode.value='T'; 		//Thank You
                //document.forms['navinfo'].action = 'http://'+host+'/order-thank-you.php'
                break;
            case 4:	     //No Charge e.g. via giftcert 
                document.forms['navinfo'].mode.value='F'; 		//Free
                //document.forms['navinfo'].action = 'https://'+host+'/order-thank-you.php';
                break;
        }
        document.forms['navinfo'].pgname.value = 'order-thank-you.php';	 
        document.forms['navinfo'].action = 'http://'+host+'/poster.php';
        document.forms['navinfo'].submit();
        return;
    }
}



//calculate discount - almost symmetric with same function in shopping-cart.php
//This returns the total price
function calcDcnt(qty,price,dcnt,poptcnt){
    var x=0;
    var d = document.addtocart;
    var newprice = 0;
    while(x<dcnt){		//search for the first applicable discount - if any
        if (d.dcnttype[x] == 1){	//qty discount
            //check if applies
            if (qty >= d.min[x] && qty < d.max[x]) {
                newprice = qty*price;
	          if (d.dcntmode[x] == 1){	//percent discount
	              newprice -= newprice*d.percent[x];
                    break;
                }else{			//flat amount
		       newprice -= d.amount[x];
                   break;
                }
           }
       }else{				// (dcnttype == 2)	//price discount
           //check if applies
           if (newprice >= d.min[x] && newprice < d.max[x])	{
               newprice = qty*price;
	         if (d.dcntmode[x] == 1){	//percent discount
                   newprice = qty*price;
	             newprice -= newprice*d.percent[x];
               }else			//flat amount
		       newprice -= d.amount[x];
           }
       } 
       x++;
   } 
   if (newprice == 0)
       newprice = qty*price;	//no discounts applied

   if (poptcnt > 0){	//check for addons - add their (price*qty)
       for (x=0;x<d.addon.length;x++){	//for each addon
           if (d.addon[x].checked){		//if it is checked
               d.prodadd.value = d.thispadd[x].value;
               newprice += qty*d.paddamt[x].value;
           }
       }
   }
   return '$'+roundNumber(newprice,2);
}

function roundNumber(number,decimal_points) {
	if(!decimal_points) return Math.round(number);
	if(number == 0) {
		var decimals = "";
		for(var i=0;i<decimal_points;i++) decimals += "0";
		return "0."+decimals;
	}
	var exponent = Math.pow(10,decimal_points);
	var num = Math.round((number * exponent)).toString();
	return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points)
}

//update Gift certificate totals
function updateTot(){
    var el = document.getElementById('usegiftcert');
    if (el.checked){
        if (parseFloat(document.getElementById('remainamt').value) > parseFloat(document.getElementById('totcost').value)){
            newval = 0;
            bal = document.getElementById('remainamt').value - document.getElementById('totcost').value;
            document.getElementById('remainamt').value = bal.toFixed(2);
            document.getElementById('redeemamt').value = document.getElementById('totcost').value;

        }else{
            newval = document.getElementById('totcost').value - document.getElementById('remainamt').value;
            bal = 0; 
            document.getElementById('remainamt').value = bal.toFixed(2);
            document.getElementById('redeemamt').value = document.getElementById('totcost').value;
        }
    }else{
        var newval = parseFloat(document.getElementById('totcostorig').value);
        document.getElementById('remainamt').value = document.getElementById('remainamtorig').value; 
        document.getElementById('redeemamt').value =0;
        document.getElementById('paymethdv').style.visibility = 'visible';
    }
 
//alert('newval '+newval+' bal '+document.getElementById('remainamt').value );

    document.getElementById('totcost').value = newval.toFixed(2);
    if (document.getElementById('totcost').value == 0){
         document.getElementById('paymethdv').style.visibility = 'hidden';
         document.getElementById('paymeth').value = 4;	//signal none
    }
}

