//establish default global variables.
var description;
var booGrommet;
var booHem;
var booSalesTax;
var intWidthFeet;
var intWidthInches;
var intWidth;
var intLengthFeet;
var intLengthInches;
var intLength;
var intLinealFeet;
var intGrommet;
var intSquareFeet;
var intLengthFeetBilled;
var intWidthFeetBilled;
var SelectedProductName;
var myValue;
var curHemPrice;
var curGrommetPrice;
var curHandlingPrice;
var curDiscount;
var curDiscountDisplay;
var curSlitFee;
var curSalesTax;
var curQty;
var panel;
var ProductList;
var DiscountRateList;
var Setup;
var PPQty;
var PPOption;
var DblLayer;
var PPCost;
var SlitCost;
var DLHandlingFee;
var PPlength;

function Test()
{
    DiscountRateList = new Array();
    alert("start");
    FillDiscountRateList(DiscountRateList);
    //alert(DiscountRateList.length);
    alert(CalcDiscount(0));
    
}

function reCalc()
{
    Init();
    Product = GetObject(ProductList,SelectedProductName);
    Setup = GetSetup();
    description = BuildDescription();
	 description = BuildDescription();
    if(curQty > 1){panel = "panels";}
    if(booHem == true){curHemPrice = (Setup.HemPrice * intLinealFeet);}
    if(booGrommet==true)
    {
        document.forms["quote"]["chkHem"].checked = true
        curGrommetPrice = Setup.GrommetPrice * (intGrommet);
        curHemPrice = (Setup.HemPrice * intLinealFeet);
    }
    if(intSquareFeet < Setup.MinHandlingFeeSQFT)
    {    
        curHandlingPrice = Setup.HandlingFee;
     }

    
    //Width
    				if(intWidthInches>12)
				{
					intWidthFeet=(intWidthFeet*1)+Math.floor((intWidthInches*1)/12)
					intWidthInches=(intWidthInches*1) % 12				
				}
				if(intWidthInches==12)
				{
					intWidthFeet=(intWidthFeet*1)+1
					intWidthInches=0
				}
 
    //Length
    if(intLengthInches>12)
    {
        intLengthFeet=(intLengthFeet*1) + Math.floor((intLengthInches*1)/12)
        intLengthInches=(intLengthInches*1) % 12				
    }
    if(intLengthInches==12)
    {
        intLengthFeet=(intLengthFeet*1)+1
        intLengthInches=0
    }

    intWidthFeetBilled = GetintWidthFeetBilled(intWidthFeet);
    
    var SqFtBilledMaterial;
    var PPBilledPrice;
    PPBilledPrice = 0;
    
	//Pinch Pleat calcs    
    PPlength=""
    if(PPOption == 'Width' )
    {
      PPBilledPrice = (PPQty * intWidthFeet * PPCost);    
      PPlength=intWidthFeet + " feet";
        if(intWidthInches != 0)
        {
            PPlength = PPlength + " " + intWidthInches + " inch";
        }
    }
    else if(PPOption == 'Length')
    {
      PPBilledPrice = (PPQty * intLengthFeet * PPCost);
      PPlength=intLengthFeet + " feet";
        if(intLengthInches != 0)
        {
            PPlength = PPlength + " " + intLengthInches + " inch";
        }
    }   
    
     
    SqFtBilledMaterial = (intLength/12) * intWidthFeetBilled;
    curDiscount = CalcDiscount(SqFtBilledMaterial); 
    var curSqFtPrice = (SqFtBilledMaterial * Product.CostSqFt);
    
    if (DblLayer == true)
    {
        curSqFtPrice = (curSqFtPrice * 2);
    }
    
    if(intWidthFeetBilled != intWidthFeet)
    {
        curSlitFee = (intLength/12) * SlitCost;
    }
    
    myValue += curHemPrice;
    myValue += curGrommetPrice;
    myValue += PPBilledPrice;
    myValue += curSqFtPrice;
    myValue += parseInt(curHandlingPrice);
    myValue += curSlitFee;

    //pass values to form
    document.forms["quote"]["txtSqFt"].value = intSquareFeet;
    document.forms["quote"]["txtSqFtBilled"].value = (intLength/12)*intWidthFeetBilled;
    document.forms["quote"]["txtLinealFt"].value = intLinealFeet;
    document.forms["quote"]["txtHemPrice"].value = to_currency(curHemPrice);
    document.forms["quote"]["txtGrommetPrice"].value = to_currency(curGrommetPrice);
    document.forms["quote"]["txtPerSqFt"].value = to_currency(Product.CostSqFt);
    document.forms["quote"]["txtHandling"].value = to_currency(curHandlingPrice);
    document.forms["quote"]["txtcurQty"].value = curQty;
    document.forms["quote"]["txtcurSqFtPrice"].value = curSqFtPrice;
    document.forms["quote"]["ctlResult"].value = to_currency(myValue);
    document.forms["quote"]["txtDiscount"].value = curDiscount;
    document.forms["quote"]["txtDiscountDisplay"].value =	curDiscount*100;
    document.forms["quote"]["txtWidth"].value = intWidth;
    document.forms["quote"]["txtLength"].value = intLength;
    document.forms["quote"]["txtSlitFee"].value = curSlitFee;
    document.forms["quote"]["txtWidthFeetBilled"].value = intWidthFeetBilled;
    document.forms["quote"]["txtLengthFeetBilled"].value = intLengthFeetBilled;
    document.forms["quote"]["txtDescription"].value = description;
    document.forms["quote"]["DESCRIPTION"].value = description;
    document.forms["quote"]["lstWidthFeet"].value = intWidthFeet;
    document.forms["quote"]["lstLengthFeet"].value = intLengthFeet;
    document.forms["quote"]["lstWidthInches"].value = intWidthInches;
    document.forms["quote"]["lstLengthInches"].value = intLengthInches;
    document.forms["quote"]["lstFactor"].value = SelectedProductName;
    document.forms["quote"]["PPlength"].value = PPlength;
	document.forms["quote"]["txtPPQty"].value = PPQty;


//Calculate Sales Tax
    if(booSalesTax==true)
    {
        if(((myValue-(myValue*curDiscount)))+curSalesTax<75)
        {
            curSalesTax = (curQty*(75*.029));
        }
        else
        {
            curSalesTax = (curQty*((myValue-(myValue*curDiscount))*.029));
        }
    }

// Calculate display and dollar amount passed to payment provider

  if(DblLayer == true)
     {
        if(((myValue-(myValue*curDiscount)))+curSalesTax<75)
            {
                document.forms["quote"]["txtDiscountctlResult"].value =  to_currency(((75*curQty)+curSalesTax)+30);
                document.forms["quote"]["AMOUNT"].value =  (((75*curQty)+curSalesTax)+30).toFixed(2);
            }
            else
            {
                document.forms["quote"]["txtDiscountctlResult"].value = to_currency((((myValue-(myValue*curDiscount))*curQty)+curSalesTax)+30);
                document.forms["quote"]["AMOUNT"].value = (((((myValue-(myValue*curDiscount))*curQty)+curSalesTax+30))).toFixed(2);
            }
       }
 else
 
     {
        if(((myValue-(myValue*curDiscount)))+curSalesTax<75)
            {
                document.forms["quote"]["txtDiscountctlResult"].value =  to_currency((75*curQty)+curSalesTax);
                document.forms["quote"]["AMOUNT"].value =  ((75*curQty)+curSalesTax).toFixed(2);
            }
            else
            {
                document.forms["quote"]["txtDiscountctlResult"].value = to_currency(((myValue-(myValue*curDiscount))*curQty)+curSalesTax);
                document.forms["quote"]["AMOUNT"].value = ((((myValue-(myValue*curDiscount))*curQty)+curSalesTax)).toFixed(2);
            }
       }
}

function to_currency(val,currency)
{
    val = "" + Math.round(100 * val);
    var dec_point = val.length-2;
    var first_part = val.substring(0,dec_point);
    var second_part=val.substring(dec_point,val.length);
    var result = first_part + "." + second_part;
    if(result < .01)
    {
    result = 0;
    }
    return "$" + result;
}

function BuildDescription()
{
    result = "Delivered Price for " + curQty + " " + panel + " " + intWidthFeet + " feet";
    if(intWidthInches != 0)
    {
        result = result + " " + intWidthInches + " inch";
    }
    result = result + " Width by " + intLengthFeet + " feet";
    if(intLengthInches != 0)
    {
        result = result + " " + intLengthInches + " inch";
    }
    result = result + " Length in " + SelectedProductName;
    
    if(booGrommet == true)
    {
        result = result + " with taped hem and grommets every foot"
    }
    
    if(booHem == true && booGrommet != true)
    {
            result = result + " with taped hem (no grommets)"
    }
    
        if(booHem != true && booGrommet != true)
    {
            result = result + " plain cloth (no hem or grommets)"
    }
    
        if(PPQty != 0)
        {
            result = result + " and " + PPQty + " grommeted pinch pleat(s) " + PPlength + " evenly spaced on panel"
        }
            
        if (DblLayer == true)
        {
            result = result + " in double layer fabric"
        }
          
    return result + ".";
}

function GetintWidthFeetBilled(QuoteWidth)
{
    var result = 0;
    QuoteWidth = parseInt(QuoteWidth) + intWidthInches / 12;
    for (var i=0;i<Product.availableWidths.length;i++)
    { 
        if(QuoteWidth <= Product.availableWidths[i])
        {
            if(result == 0)
            {           
                result = Product.availableWidths[i];
            }
        }
    }
    if(QuoteWidth > 0 && result == 0)
    {
        result = Product.maxwidth;
    }
    if(QuoteWidth > Product.maxwidth)
    {
        s = "The largest stock width for " + Product.Name + " is " + Product.maxwidth + " foot. \n";
        s = s + "Please email natural@colorado.net or contact us at 800-563-9720 \n";
        s = s + "to discuss sewing two panels together to create larger panels." 
        alert(s);
		  intWidthFeet=Product.maxwidth;
    }
    if(PPQty != 0 && DblLayer == true)
    {
    	  s = "We can not install grommeted pinch pleats on double layer panels.  \n";
    	  s = s + "Please accept our apologies for any inconvenience.";
        alert(s);
        PPQty=0;
        
    }
    return(result);  
}

function CalcDiscount(SquareFeet)
{
    var result = 0;
    DiscountRateList = new Array();
    FillDiscountRateList(DiscountRateList);    
    DiscountRateList.sort();
//    DiscountRateList.reverse(); //Descending
    for (var i=0;i<=DiscountRateList.length-1;i++)
    { 
        if(SquareFeet >= DiscountRateList[i].SqFeet)
        {result = DiscountRateList[i].Discount;}
    }
    
    
//    if(SquareFeet >= Setup.BulkDiscountSQFT)
//    {
//        s = "Your order qualifies for a special bulk discount. \n";
//        s = s + "Please email natural@colorado.net \n";
//        s = s + "or contact us at 800-563-9720 for personal assistance." 
//        alert(s);
//   }
    return(result); 
    
}

function GetMaterialList()
{
var file = "../shadecloth_app/data/Product.xml";

try //Internet Explorer
    {
     xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
     xmlDoc.async=false;
     xmlDoc.load(file);
    }
catch(e)
        {
        try //Firefox, Mozilla, Opera, etc.
             {
              xmlDoc=document.implementation.createDocument("","",null);
              xmlDoc.async=false;
              xmlDoc.load(file);
             }
         catch(e)
             {
                  try //Google Chrome
                  {
                   var xmlhttp = new window.XMLHttpRequest();
                   xmlhttp.open("GET",file,false);
                   xmlhttp.send(null);
                   xmlDoc = xmlhttp.responseXML.documentElement;
                  }
              catch(e)
               {
                error=e.message;
               }
           }
       }

   if (xmlDoc!=null) 
        {
            var x=xmlDoc.getElementsByTagName("Type");
            for (var i=0;i<x.length;i++)
            { 
                document.write(x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue);
                document.write(x[i].getElementsByTagName("CostSqFt")[0].childNodes[0].nodeValue);
            }
            document.write("</table>");
       }
}

function Init()
{
    //Set Cost Variables ***************************
    SlitCost = .3;
    PPCost = 1.25;
    //Cost variables ***************************
    
    description = "";
    booGrommet = document.forms["quote"]["chkGrommet"].checked;
    booHem = document.forms["quote"]["chkHem"].checked;
    booSalesTax = document.forms["quote"]["chkSalesTax"].checked;
    intWidthFeet = document.forms["quote"]["lstWidthFeet"].value.replace(/^[0]+/g,"");
    intWidthFeet = intWidthFeet.replace(/\./,"");
    intWidthInches = Math.floor(document.forms["quote"]["lstWidthInches"].value);
    intWidth = ((document.forms["quote"]["lstWidthFeet"].value*12) + (Math.floor(document.forms["quote"]["lstWidthInches"].value))*1);
    intLengthFeet = document.forms["quote"]["lstLengthFeet"].value.replace(/^[0]+/g,"");
    intLengthFeet = intLengthFeet.replace(/\./,"");
    intLengthInches = Math.floor(document.forms["quote"]["lstLengthInches"].value);
    intLength = ((document.forms["quote"]["lstLengthFeet"].value*12)+(Math.floor(document.forms["quote"]["lstLengthInches"].value))*1);
    intLinealFeet = ((intLength/12)*2)+((intWidth/12)*2);
    intGrommet = Math.floor(intLinealFeet);
    intSquareFeet = (intLength/12)*intWidthFeet;
    intLengthFeetBilled = (intLength/12);
    intWidthFeetBilled = 0;
    SelectedProductName = document.forms["quote"]["lstFactor"].value;
    myValue = 0;
    curSlitFee = 0;
    curHemPrice = 0;
    curGrommetPrice = 0;
    curHandlingPrice = 0;
    curDiscount = 0;
    curDiscountDisplay = 0;
    curSalesTax = 0;
    curQty = document.forms["quote"]["txtcurQty"].value;
    panel = "panel";
    PPQty = document.forms["quote"]["txtPPQty"].value;
    PPOption = document.forms["quote"]["lstPPOption"].value;
    DblLayer = document.forms["quote"]["chkDblLayer"].checked;

}

function GetProductList()
{
    ProductList = new Array();
    FillProductList(ProductList);
    var s = "<option value='" + ProductList[0].Name + "' selected>" + ProductList[0].Name + "</option>";
    for (var i=1;i<ProductList.length;i++)
    {
        s = s + "<option value='" + ProductList[i].Name + "'>" + ProductList[i].Name + "</option>";    
    }
    return s;
}                     

function GetObject(arr,Name)
{
  for(var i=0; i<arr.length; i++) 
  {
    if (arr[i].Name == Name)
    {
        return arr[i];
    }
  }
}

//#region Objects

function objProduct()
{
    var Name;
    var CostSqFt;
    var maxwidth;
    var availableWidths;
}

function objSetup(MyGrommetPrice,MyHemPrice,MyMinHandlingFeeSQFT,MyHandlingFee,MyBulkDiscountSQFT,MyDLHandlingFee)
{
    this.GrommetPrice = MyGrommetPrice;
    this.HemPrice = MyHemPrice;
    this.MinHandlingFeeSQFT = MyMinHandlingFeeSQFT;
    this.HandlingFee = MyHandlingFee;
    this.BulkDiscountSQFT = MyBulkDiscountSQFT;
    this.DLHandlingFee = MyDLHandlingFee;
}

function objDiscountRate(DiscountRateList)
{
    var SqFeet;
    var Discount;
}

//#end region