var color_flag=0;
var order_num=0;
var orders=new Array();
var total=0;
var shipping=0;
var clear_color=0;
var tax=0;
var distance=0;
var plants = [{SID: "", CN: "", SN: "", SIZE: "", QTY: "", DOL: "", STATE: "", PRICE: "" } ];

function change_qty_color(obj)
{
			$("#qty_"+obj).css('background-color','Red');
}

function add_order_entry(obj)
{
                        
	var tmpSID=$("#suggest").val();
    var LC=$(obj).find('div');
    
    var plantName=LC[2].innerHTML;
    var qtyAvail=LC[0].innerHTML;
    qtyAvail=qtyAvail.replace(/(^.*\()/,'');
    qtyAvail=qtyAvail.replace(/(\).*)/,'');
    
    
    
    
	$("#suggest").attr({ value: ''});
    if(tmpSID==0)
    {
                        alert('Please Select with your mouse from the pull down list the Plant you want added to your order');
    }
    else{

	order_exists=false;
	for(i=0;i<orders.length; i++)
	{
		if(tmpSID==orders[i].SID)
		{
			order_exists=true;
			setTimeout('change_qty_color('+tmpSID+')',2000);
			alert('You have already added this Plant to your order - Please update the Quantity (colored Red in your order)');
		}
	}

	if(order_exists==false)
	{
                        
        prompt_qty(tmpSID,plantName,qtyAvail);
        //alert('qty: ' + qty);
        //add_new_plant(tmpSID,data);
        
                        
     }
                        

	calculate();
    }
}

function prompt_qty(tmpSID,plantName,qtyAvail)
{
            $("#show_qty").css("visibility","visible","display","block");
                        var data=1;
                        $("#jqDialog_content").css("height","100px");
                        $("#jqDialog_content").css("padding-top","5px");
                        $("#jqDialog_content").css("width","300px");
                        $("#jqDialog_box").css("height","160px");
                        $("#jqDialog_box").css("width","320px");
                        $("#jqDialog_box").css("z-index","9999999");
    jqDialog.prompt(plantName+'<p><br>Qty Avail: ' + qtyAvail+"<br>Qty Desired:", '1',
      function(data) {
                        add_new_plant(tmpSID,data);
                        return data;
                        }, // callback function for 'OK' button
      function() {} // callback function for 'Cancel' button
    );
}

function prompt_terms()
{
                        
                        $("#jqDialog_content").css("height","360px");
                        $("#jqDialog_content").css("width","500px");
                        $("#jqDialog_box").css("height","420px");
                        $("#jqDialog_box").css("width","520px");
                        $("#jqDialog_box").css("z-index","9999999");
                        
                        jqDialog.confirm("<b>*</b>This tool is designed to assist in quoting and to place orders.  If you have questions about its use, please contact us by phone at 303-279-5060 or by email at info@plantsourceit.com.<p>&nbsp;<br><b><u>*Inventory changes frequently</u></b>.  This database reflects availability as of the date the list was uploaded (shown on each line item).  <p>&nbsp;<br><b>*</b>Freight costs indicated are an estimate only.  Actual freight charges will be determined at the time of shipping.<p>&nbsp;<br><b>*</b>The database does not include all of the plant material we have available.  <u><b><i>If you do not find what you are looking for, please contact us!</i></u></b><p>&nbsp;<br><b>*</b>All orders are subject to the <u><b>Terms & Conditions</b></u> established by Plant Source, Incorporated.<p>&nbsp;<br><b>*</b>An approved credit account or prepayment is required to purchase from Plant Source, Incorporated.<p>&nbsp;<br> <p>&nbsp;<br><u><b>Do you Agree with these terms and conditions?</u></b>",
			function() { update_terms() },		// callback function for 'YES' button
			function() { alert('You must accept the terms of this agreement prior to using this tool'); }		// callback function for 'NO' button
		);
                        
}


function add_plant_to_order(tmpSID,qty)
{
                        
	for(i=0;i<plants.length; i++)
	{
                        
		if(plants[i].SID==tmpSID)
		{
			color_flag++;
			// Add to global order array
			orders.push({SID: plants[i].SID, QT_AVAIL: plants[i].QT_AVAIL, PRICE: plants[i].PRICE, QT_AVAIL: plants[i].QT_AVAIL, LF: plants[i].LF, ZIP: plants[i].ZIP, CID: plants[i].CID, Harvest: plants[i].Harvest });
			var colour = (color_flag % 2 == 0)? 'order_even': 'order_odd';
            var leaf='';
            if(plants[i].Harvest.toLowerCase()=='fall')
            {
                        leaf='<img src=fireworks_source/leaf.png align=absmiddle>';
            }
            if(plants[i].Harvest.toLowerCase()=='spring')
            {
                        leaf='<img src=fireworks_source/leaf_green.png align=absmiddle>';
            }

			$("#order").append("<div class=" + colour + " id=" + plants[i].SID + ">" +
					"<span class=c1><input style='width: 34px' name=qty_" + plants[i].SID + " id=qty_" + plants[i].SID +
                    " size=2 value='"+qty+"' onChange='calculate()'> here " + leaf + "</span>" + 
					"<span class=c1>" + plants[i].SIZE + "<br><i>(" + plants[i].QT_AVAIL + ")</i></span>" +
                    
					"<span class=c2>" + formatCurrency(plants[i].PRICE) + "<br>&nbsp;&nbsp;&nbsp;<span id=lf_" + plants[i].SID + ">" + plants[i].LF + "</span></span>" +
                    
                    
					"<span class=c3>" + plants[i].SN + "<br>&nbsp;&nbsp;&nbsp;&nbsp;" + plants[i].CN + "</span>" +
                    
					"<span class=c4>"+ plants[i].CID + "</a><br><font size=-2>&nbsp;&nbsp;" + plants[i].DOL + "</font></span>" +
                    
					"<span class=c5>" + plants[i].STATE + "</span>" +
                    
                    
					"<span class=c6 id=ftinfo_"+plants[i].SID+">Freight<br>&nbsp;&nbsp;% Load</span>" +
                    
					"<span class=c7><input type=checkbox onClick=remove_item(" + plants[i].SID + ") align=absmiddle title='remove this item'></span><div style='clear:both'/>" +
                    //"<span id=compute_"+plants[i].SID+">Calculations from Google&copy;... Please wait</span>" +
					"<input type=hidden name=price_" + plants[i].SID + " id=price_" + plants[i].SID + " value=" + plants[i].PRICE + ">" + 
					"<input type=hidden name=shipping_" + plants[i].SID + " id=shipping_" + plants[i].SID + " value=" + plants[i].PRICE + ">" + 
					"<input type=hidden name=sid_" + plants[i].SID + " id=sid_" + plants[i].SID + " value=" + plants[i].SID + ">" + 
					"</div><div style='clear: both;'/>");
			total=total+parseFloat(plants[i].PRICE,2);
		}
	}
    
    update_orders();
                        
}



function calculate()
{
    $(document).ready(function () {
    var total=0;
    var shipping=0;
    var tax=0;
    var distance=0;
	get_total();
	get_tax();
	get_load_factor();
	get_grand_total();
	show_quoteit();
	<!-- enforce_qty(); -->
    get_calculations();
                        });
}

function enforce_qty()
{
	for(i=0;i<orders.length;i++)
	{
		item_qty=$("#qty_"+orders[i].SID).val();
        item_qty=parseFloat(item_qty);
        items_avail=orders[i].QT_AVAIL;
        items_avail=parseFloat(items_avail);
        if(item_qty>items_avail)
        {
		    <!-- $("#qty_"+orders[i].SID).val(items_avail); -->
            alert('Your quantity exceeds what is available from this supplier.');
		    $("#qty_"+orders[i].SID).css('background-color','Yellow');
        }
        
	}

}

function get_total()
{
	total=0;
        //alert(orders.length);
	for(i=0;i<orders.length;i++)
	{
		item_sid=orders[i].SID;
        //alert(orders[i].QTY_Available);
		item_cost=$("#price_"+orders[i].SID).val();
		item_qty=$("#qty_"+orders[i].SID).val();
		total=total+(item_cost*item_qty);
		$("#qty_"+item_sid).css('background-color','white');
		$.post('ajax_data_collection.php',{SID: item_sid, QTY: item_qty, COST: item_cost});
	}

	$("#total").html("<h4>Plant Subtotal: <font color=Black>" + formatCurrency(total) + "</font></h4>");
}

function get_load_factor()
{
	for(i=0;i<orders.length;i++)
	{
		var item_sid=orders[i].SID;
		var item_cost=$("#price_"+orders[i].SID).val();
		var item_qty=$("#qty_"+orders[i].SID).val();
                var item_lf=orders[i].LF;
                var new_lf=item_lf*item_qty;
                new_lf=new_lf.toFixed(4);
		//$("#lf_"+item_sid).css('background-color','red');
		//$("#lf_"+item_sid).html(new_lf);
		$("#lf_"+item_sid).html('');
	}

}

function get_calculations()
{
                        
    var customer_zipcode=$("#order_zipcode").val();
    
    shipping=0;
                                           
	for(i=0;i<orders.length;i++)
	{
		var item_sid=orders[i].SID;
		var item_cost=$("#price_"+orders[i].SID).val();
		var item_qty=$("#qty_"+orders[i].SID).val();
                var item_lf=orders[i].LF;
                var item_zip=orders[i].ZIP;
                //var new_lf=item_lf*item_qty;
                var new_lf=item_lf*1;
                new_lf=new_lf.toFixed(4);
                update_calculation(customer_zipcode,item_zip,item_sid,new_lf,item_qty);
	}

}


// Google Driving Distance in miles
function update_calculation(to,from,sid,lf,qty)
{
          var gdir2 = new google.maps.Directions();
          google.maps.Event.addListener(gdir2, "load", function () {
                        handleLoad_dist(sid,gdir2,lf,qty);
          });
          gdir2.load("from: "+from+" to: "+to, {getSteps: true});
}


function handleLoad_dist(item_sid,gdir2,lf,qty) {
                        var info=gdir2.getDistance().html;
                        //alert(info);
                        miles=info.split("&nbsp;");
                        distance=0;
                        distance=miles[0];
                        // Remove commas that come in thousands of miles from google
                        distance=distance.replace(",",'');
                        
                        // Update the compute area
                        //$("#compute_"+item_sid).css('background-color','yellow');
                        
                        var cost_per_mile=2.8;
                        var supplier_load_factor=1;
                        var unit_cost_per_mile=0;
                        unit_cost_per_mile=(lf*cost_per_mile).toFixed(4);
                        var unit_freight_cost=0;
                        unit_freight_cost=((distance*unit_cost_per_mile));
                        var percent_full_load=0;
                        percent_full_load=(lf*qty*100).toFixed(2);
                        
                        var shipping_individual=(unit_freight_cost*qty);
                        // Here Peter
                        shipping=shipping+formatRound(unit_freight_cost*qty);
                        //shipping=(unit_freight_cost*qty);
                        
                        var compute_data= ' Unit Load: <b>' + lf +
                        '</b> X ' + formatCurrency(cost_per_mile) +
                        ' = ' + (lf*cost_per_mile).toFixed(4) +
                        ' Miles:' + distance +
                        ' Freight Cost Per Unit: <b>' + formatCurrency(unit_freight_cost) +
                        '</b> Total Freight Cost: <b>' + formatCurrency(unit_freight_cost*qty) +
                        '</b> Percent: ' + percent_full_load +'%' +
                        '';
                        
                        
                        var frtinfo=formatCurrency(unit_freight_cost*qty)+'<br>'+percent_full_load+'%';
                        $("#frtinfo_"+item_sid).html(frtinfo);
                        $("#shipping_"+item_sid).val(shipping_individual);
                        
                        //$("#compute_"+item_sid).html(compute_data);
                        
                        var elem=document.getElementById("shipping_"+item_sid);
                        if(elem!=null)
                        {
                        elem.value=shipping_individual;
                        }
                        get_shipping();
                        get_grand_total();
                        
}

function get_shipping()
{
	$("#shipping").html("<h4>Shipping <font size=-2>(estimated only)</font>: <font color=Black>" + formatCurrency(shipping) + "</font></h4>");
}



function get_tax()
{
        tax=0;
	if(tax_exempt==true)
	{
		tax=0;
	}
	else
	{
		tax=(total*.0475);
	}
	$("#tax").html("<h4>Tax <font size=-2>(4.75%)</font>: <font color=Black>" + formatCurrency(tax) + "</font></h4>");

}

function get_grand_total()
{
	//var gtotal=total+shipping+tax;
	var gtotal=formatFloat(total)+formatFloat(shipping)+formatFloat(tax);
    
	$("#gtotal").html("<h2><font color=Black>Total: " + formatCurrency(gtotal) + "</font></h2>");

}

function remove_item(obj)
{
        if(confirm('Are you sure you want to delete this item?'))
        {
	    for(i=0;i<orders.length;i++)
		{
			if(orders[i].SID==obj)
			{
		                item_qty=$("#qty_"+obj).val(0);
		                calculate();
			}
		}
        var urlvars=getUrlVars();
        var orderid=urlvars['orderid'];
		$.post('ajax_data_collection.php',{SID: obj, DELETE: true, ORDER_NUM: orderid});
	        $("#"+obj).html("");
		$("#"+obj).hide();
	get_tax();
	get_grand_total();
    //window.location.reload();
        }
        else{
        }
}

function get_miles(to,from)
{
		$.post('ajax_distance.php&to=',{SID: obj});
                        
}

function show_quoteit()
{
	$("#quoteit").html("<input title='This button updates your current Order but DOES NOT submit it to Plant Source IT for Fullfillment' type=submit name=submitit value='Save Order' id='submitit'>&nbsp;<input title='This button sends your request to Plant Source IT for Fullfillment' type=submit name=submitit value='Submit Order'> <a href='orders' style='text-decoration: none;'><img src=fireworks_source/modify.png border=0 align=absmiddle>Orders</a>");
}
function show_printit()
{
	$("#quoteit").html("<input type=button name=printit title='This button sends your quote to your local Printer' value='print-it!' onClick='window.print();'>");
}

function clear_txt()
{
	$("#suggest").val('');
	$("#helptxt").html('');
    // check to ensure zip code is filled in to Delivery area
    var zippie=$("#order_zipcode").val();
    if(zippie=='')
    {
                        $("#order_zipcode").val(zipcode);
    }
}

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);
}


function formatFloat(num) {
            num=parseFloat(num,2);
            var result=Math.round(num*100)/100;
            return result;
}

function formatRound(num)
{
            var result=Math.round(num*100)/100;
            return result;
}



function add_new_plant(obj,qty)
{
                        var url='ajax_add_plant.php?sid='+obj;
                       $.post(url,function(data) {
                        var tmp=eval('('+data+')');
                        plants.push(tmp);
                        add_plant_to_order(obj,qty);
			calculate();
                       });
}

function update_orders()
{
            calculate();
            setTimeout('update_orders_submit()',3000);
}

function update_orders_submit()
{
    $(document).ready(function () {
                        $("#submitit").click();
                        });
}


function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}
