// This script file and all the functions herein are for the purpose of dynamically 
// calculating screen totals
// RMS Apr/06

function updateStatusColor() {

    // only needed for FF
    if (navigator.appName == "Netscape") {
        selectedStatus = document.getElementById('ddlOrderStatus').value;

        switch (selectedStatus) {
            case "Pending" : newColor="blue" ; break;
            case "OutToCustomer" : newColor="green" ; break;
            case "Canceled" : newColor="red" ; break;
            case "Returned" : newColor="orange" ; break;
            default : newColor = "black"; break;
        }
        
        document.getElementById('ddlOrderStatus').style.color = newColor;
   }
}

function doCalc(){
//	window.alert(document.getElementById('lblPrice').getAttribute('id'));
//	document.getElementById('lblPrice').innerHTML = "your text here"; 
	if (document.getElementById('txtPickupDate').value.length > 0){
		if(isGoodDate(document.getElementById('txtPickupDate').value)){
			if (document.getElementById('txtDropOffDate').value.length > 0){
			if(isGoodDate(document.getElementById('txtDropOffDate').value)){
					calcPrice();
				}
			}
		}		
	}
}

function setDropTime(){
	//var puTime = document.getElementById('ddlPickupTime').options[document.getElementById('ddlPickupTime').selectedIndex].innerHTML;
	//document.getElementById('lblDropoffTime').innerHTML = puTime;
	document.getElementById('ddlDropoffTime').selectedIndex = document.getElementById('ddlPickupTime').selectedIndex;
	doCalc();
}


function calcPrice(){
	// TOs show no price info but still need to see if return date needs to be
	// adjusted
//debugger
	var daysNeeded = calcDays();    
	if (document.getElementById('ddlDropoffTime').selectedIndex > document.getElementById('ddlPickupTime').selectedIndex){
		daysNeeded = daysNeeded + 1;
	}		
	if (daysNeeded < 0){
		daysNeeded = 0;
	}
	if(document.getElementById('hiddenDaysNeeded')!=undefined){
		document.getElementById('hiddenDaysNeeded').value=daysNeeded;
		document.getElementById('lblDueBackDateTime').value = "Will be reset on Save"
	}
	
	if(document.getElementById('hiddenOrdSourceType')!=undefined){
		if(document.getElementById('hiddenOrdSourceType').value=='TO'){
			return;
		}
	}
	
	var daysNeeded = calcDays(); 
    var dblPrice = 0.0;
    var dblDropCharge = 0.0;
    var dblPST = 0.0;
    var dblGST = 0.0;
    var dblTotal = 0.0;
    var dblWeekRate = 0.0;
    var dblAdditionalDays = 0.0;

	if (document.getElementById('ddlDropoffTime').selectedIndex > document.getElementById('ddlPickupTime').selectedIndex && 
	    document.getElementById('txtPickupDate').value != document.getElementById('txtDropOffDate').value) {
		daysNeeded = daysNeeded + 1;
	}
	
	if (daysNeeded < 0){
		daysNeeded = 0;
	}
	if(daysNeeded < 7){
		dblPrice = ratesArray[daysNeeded];
		if(document.getElementById('lblPrice')!=undefined){
			document.getElementById('lblPrice').innerHTML = formatCurrency(dblPrice);
        }
        if(document.getElementById('HiddenPrice')!=undefined){
			document.getElementById('HiddenPrice').value = formatCurrency(dblPrice);
		}
        if(document.getElementById('txtPrice')!=undefined){
			document.getElementById('txtPrice').value = formatDecimal(dblPrice, true, 2);
		}
    }else{
		// old way
        /*dblWeekRate = ratesArray[6];
        weeksNeeded = parseInt(daysNeeded/7);
        dblPrice = dblWeekRate * weeksNeeded;
        daysNeeded = (daysNeeded - (weeksNeeded * 7)) % 7;
        if(daysNeeded >= 0){
			dblPrice = dblPrice + ratesArray[daysNeeded];
        }*/
        
        // new way
        dblWeekRate = ratesArray[6];
        dblAdditionalDays = ratesArray[7];
        daysNeeded = daysNeeded - 6;
        dblPrice = dblWeekRate + (daysNeeded * dblAdditionalDays);        
        
		if(document.getElementById('lblPrice')!=undefined){
	        document.getElementById('lblPrice').innerHTML = formatCurrency(dblPrice);
		}
        if(document.getElementById('HiddenPrice')!=undefined){
			document.getElementById('HiddenPrice').value = formatCurrency(dblPrice);
		}
        if(document.getElementById('txtPrice')!=undefined){
			document.getElementById('txtPrice').value = formatDecimal(dblPrice, true, 2);
		}
    }
	
    
    if (document.getElementById('ddlPickup')[document.getElementById('ddlPickup').selectedIndex].value == document.getElementById('ddlDropOff')[document.getElementById('ddlDropOff').selectedIndex].value){
		if(document.getElementById('lblDropCharge')!=undefined){
			document.getElementById('lblDropCharge').innerHTML = formatCurrency(0);
	    }
		if(document.getElementById('HiddenDropCharge')!=undefined){
	        document.getElementById('HiddenDropCharge').value = formatCurrency(0);
	    }
		if(document.getElementById('txtDropCharge')!=undefined){
	        document.getElementById('txtDropCharge').value = formatDecimal(0, true, 2);
	    }
    } else {
		if(document.getElementById('lblDropCharge')!=undefined){
	        document.getElementById('lblDropCharge').innerHTML = formatCurrency(10);
		}
		if(document.getElementById('HiddenDropCharge')!=undefined){
	        document.getElementById('HiddenDropCharge').value = formatCurrency(10);
	    }
		if(document.getElementById('txtDropCharge')!=undefined){
	        document.getElementById('txtDropCharge').value = formatDecimal(10, true, 2);
	    }
        dblDropCharge = 10.0;
    }
	var hiddenCtrlName = 'SA_' + document.getElementById('ddlPickup').options[ document.getElementById('ddlPickup').selectedIndex].value;
	var PSTValue = document.Form1.elements[hiddenCtrlName].value;
    dblPST = (dblPrice + dblDropCharge) * PSTValue / 100
	if(document.getElementById('lblPST')!=undefined){
	    document.getElementById('lblPST').innerHTML = formatCurrency(dblPST)
    }
	if(document.getElementById('HiddenPST')!=undefined){
	    document.getElementById('HiddenPST').value = formatCurrency(dblPST)
    }
	if(document.getElementById('txtPST')!=undefined){
	    document.getElementById('txtPST').value = formatDecimal(dblPST, true, 2);
    }

	if(document.getElementById('txtPrice')!=undefined){
		// we are on the admin order detail screen, carry on
		doDetailCalc();    
	} else {
		// this calc used on the order screen
		dblGST = (dblPrice + dblDropCharge) * 0.05
		if(document.getElementById('lblGST')!=undefined){
			document.getElementById('lblGST').innerHTML = formatCurrency(dblGST)
		}
		if(document.getElementById('HiddenGST')!=undefined){
			document.getElementById('HiddenGST').value = formatCurrency(dblGST)
		}
		if(document.getElementById('txtGST')!=undefined){
			document.getElementById('txtGST').value = formatDecimal(dblGST, true, 2);
		}
		
		dblTotal = dblPrice + dblDropCharge + dblPST + dblGST
		if(document.getElementById('lblTotal')!=undefined){
			document.getElementById('lblTotal').innerHTML = formatCurrency(dblTotal)
			if(document.getElementById('txtPaymentReceived')!=undefined){
				var paid = parseFloat(document.getElementById('txtPaymentReceived').value) + 
										parseFloat(document.getElementById('txtPayment2').value) + 
										parseFloat(document.getElementById('txtPayment3').value) +
										parseFloat(document.getElementById('txtPayment4').value);
				var balDue = dblTotal - paid;
				document.getElementById('lblBalance').innerHTML = formatDecimal(balDue, true, 2);
				document.getElementById('hiddenBalance').value = formatDecimal(balDue, true, 2);
				document.getElementById('txtPaymentAmount').value = formatDecimal(balDue, true, 2); 
			}
		}
		if(document.getElementById('HiddenTotal')!=undefined){
			document.getElementById('HiddenTotal').value = formatCurrency(dblTotal)
		}
		if(document.getElementById('txtTotal')!=undefined){
			document.getElementById('txtTotal').value = formatDecimal(dblTotal, true, 2);
		}
		
	}

 }


function calcDays(){
//debugger
  var date1 = document.getElementById('txtPickupDate').value;
  var date2 = document.getElementById('txtDropOffDate').value;
  date1 = date1.split("/");
  date2 = date2.split("/");
  var sDate = new Date(date1[0]+"/"+date1[1]+"/"+date1[2]);
  var eDate = new Date(date2[0]+"/"+date2[1]+"/"+date2[2]);
  var daysApart = Math.abs(Math.round((sDate-eDate)/86400000));
  //document.getElementById('diffDays').lastChild.data = daysApart;
  if(daysApart > 0){
	daysApart = daysApart-1;
  }
  return daysApart;
}

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isGoodDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

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 formatDecimal(argvalue, addzero, decimaln) {
  var numOfDecimal = (decimaln == null) ? 2 : decimaln;
  var number = 1;

  number = Math.pow(10, numOfDecimal);

  argvalue = Math.round(parseFloat(argvalue) * number) / number;
  // If you're using IE3.x, you will get error with the following line.
  // argvalue = argvalue.toString();
  // It works fine in IE4.
  argvalue = "" + argvalue;

  if (argvalue.indexOf(".") == 0)
    argvalue = "0" + argvalue;

  if (addzero == true) {
    if (argvalue.indexOf(".") == -1)
      argvalue = argvalue + ".";

    while ((argvalue.indexOf(".") + 1) > (argvalue.length - numOfDecimal))
      argvalue = argvalue + "0";
  }

  return argvalue;
}

function doDetailCalc(){

/*	if(document.getElementById('hiddenOrdSourceType')!=undefined){
		if(document.getElementById('hiddenOrdSourceType').value=='TO'){
			// TOs show no price info
			return;
		}
	}
*/	
	var dblPrice = 0.00
	var dblDropCharge = 0.00
	var dblAdditionalCharges = 0.00
	var dblLateCharges = 0.00
	var dblPST = 0.00
	  
    if(document.getElementById('txtPrice')!=undefined){
	    dblPrice = parseFloat(document.getElementById('txtPrice').value);
	}
    if(document.getElementById('lblPrice')!=undefined){
	    dblPrice = parseFloat(document.getElementById('lblPrice').innerHTML.replace("$", ""));
	}

    if(document.getElementById('txtDropCharge')!=undefined){
		dblDropCharge = parseFloat(document.getElementById('txtDropCharge').value);
	}
    if(document.getElementById('lblDropCharge')!=undefined){
		dblDropCharge = parseFloat(document.getElementById('lblDropCharge').innerHTML.replace("$", ""));
	}
		
    if(document.getElementById('txtAdditionalCharges')!=undefined){
		dblAdditionalCharges = parseFloat(document.getElementById('txtAdditionalCharges').value);
	}
    if(document.getElementById('lblAdditionalCharges')!=undefined){
		dblAdditionalCharges = parseFloat(document.getElementById('lblAdditionalCharges').innerHTML.replace("$", ""));
	}	
	
    if(document.getElementById('txtLateCharges')!=undefined){
	    dblLateCharges = parseFloat(document.getElementById('txtLateCharges').value);
	}    
    if(document.getElementById('lblLateCharges')!=undefined){
	    dblLateCharges = parseFloat(document.getElementById('lblLateCharges').innerHTML.replace("$", ""));
	}	    
	
	// note from Rick: 'additional charges should not be subject to PST'
    if(document.getElementById('txtPST')!=undefined){
	    dblPST = parseFloat(document.getElementById('txtPST').value);
    }
    if(document.getElementById('lblPST')!=undefined){
	    dblPST = parseFloat(document.getElementById('lblPST').innerHTML.replace("$", ""));
    }
    
    //var dblGST = parseFloat(document.getElementById('txtGST').value);
	var dblGST = (dblPrice + dblDropCharge + dblAdditionalCharges + dblLateCharges) * 0.05
    if(document.getElementById('txtGST')!=undefined){
	    document.getElementById('txtGST').value = formatCurrency(dblGST);
    }
    if(document.getElementById('lblGST')!=undefined){
	    document.getElementById('lblGST').innerHTML = formatCurrency(dblGST);
    }

    var dblTotal = dblPrice + dblDropCharge + dblAdditionalCharges + dblLateCharges + dblPST + dblGST
    document.getElementById('hiddenTotal').value = dblTotal;

	document.getElementById('lblTotal').innerHTML = formatCurrency(dblTotal)
	var dblPayment1 = 0.00
	var dblPayment2 = 0.00
	var dblPayment3 = 0.00
	var dblPayment4 = 0.00
	if(document.getElementById('txtPaymentReceived').value!=''){
		dblPayment1 = parseFloat(document.getElementById('txtPaymentReceived').value);
		}
	if(document.getElementById('txtPayment2').value!=''){
		dblPayment2 = parseFloat(document.getElementById('txtPayment2').value);
		}
	if(document.getElementById('txtPayment3').value!=''){
		dblPayment3 = parseFloat(document.getElementById('txtPayment3').value);
		}
	if(document.getElementById('txtPayment4').value!=''){
		dblPayment4 = parseFloat(document.getElementById('txtPayment4').value);
		}
	var dblBalance = dblTotal - dblPayment1 - dblPayment2 - dblPayment3 - dblPayment4;
	dblBalance = Math.round(dblBalance*100)/100  
	document.getElementById('lblBalance').innerHTML = formatCurrency(dblBalance)
	document.getElementById('hiddenBalance').value = formatCurrency(dblBalance);
	document.getElementById('txtPaymentAmount').value = formatCurrency(dblBalance)

	if(dblBalance == 0){
		document.getElementById('lblPaymentStatus').innerHTML = 'Accepted';
		document.getElementById('hiddenPaymentStatus').value = 'Accepted';				
	} else {
		document.getElementById('lblPaymentStatus').innerHTML = 'Pending';
		document.getElementById('hiddenPaymentStatus').value = 'Pending';
	}			
}

function doDetailCalc2(){

	// SA can only change payment received
	var total = parseFloat((document.getElementById('lblTotal').innerHTML).replace('$',''));
	var dblPayment1 = 0.00
	var dblPayment2 = 0.00
	var dblPayment3 = 0.00
	var dblPayment4 = 0.00
	if(document.getElementById('txtPaymentReceived').value!=''){
		dblPayment1 = parseFloat(document.getElementById('txtPaymentReceived').value);
		}
	if(document.getElementById('txtPayment2').value!=''){
		dblPayment2 = parseFloat(document.getElementById('txtPayment2').value);
		}
	if(document.getElementById('txtPayment3').value!=''){
		dblPayment3 = parseFloat(document.getElementById('txtPayment3').value);
		}
	if(document.getElementById('txtPayment4').value!=''){
		dblPayment4 = parseFloat(document.getElementById('txtPayment4').value);
		}
	var dblBalance = dblTotal - dblPayment1 - dblPayment2 - dblPayment3 - dblPayment4;
		
	document.getElementById('lblBalance').innerHTML = formatCurrency(dblBalance)
	document.getElementById('hiddenBalance').value = formatCurrency(dblBalance);
	document.getElementById('txtPaymentAmount').value = formatCurrency(dblBalance)
	
	if(dblBalance == 0){
		document.getElementById('lblPaymentStatus').innerHTML = 'Accepted';
		document.getElementById('hiddenPaymentStatus').value = 'Accepted';				
	} else {
		document.getElementById('lblPaymentStatus').innerHTML = 'Pending';
		document.getElementById('hiddenPaymentStatus').value = 'Pending';
	}			
}