//shopfunc.js

function sndml(emailhost)
{
  var email     = "contact";
  window.location='mailto:'+email+'@'+emailhost;
}

function checkBuy(prodtype,name,optsname,poptcnt,prodopt)
{
   if (poptcnt > 1)	//otherwise no need to check radio button
   {
       if (prodtype != document.buynow.prodtype.value)
       {
           alert('You must first click to choose a '+name+' '+optsname+' above.');
           return false;
       }
       else
           return true;
   }
   else
   {
       document.buynow.prodopt.value=prodopt;	//assign prodopt[0]
       document.buynow.prodtype.value=prodtype;
       return true;
   }
}

function copyAddr()
{
    d = document.acctinfo;

    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(d)
{
    if (!d.paychoice1.checked && !d.paychoice2.checked)
    {
        alert('You must first choose a Payment Method:\nCredit Cart payment or Check payment');
        return false;
    }
    else
    {
        if (d.paychoice1.checked)	//payment via PayPal
        {
            d.paymeth.value = 1;
            document.paypal.submit();
        }
        else
        {
            d.paymeth.value = 2;
            //d.submit();			//payment via check
        }
        return true;
    }
}

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 checkentry(frm)
{
    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)
        {
             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.shipmeth.value == "0,0.0")
        errors += "- Shipping Method Error: You must choose a Shipping Method\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;
}

//calculate discount - almost symmetric with same function in shopping-cart.php
//This returns the total price
//function calcDcnt(qty,price,dcnt,dtype,dmode,percent,amount,min,max)
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)
}
