// *********************************************************************************************
// Shipdate Functions
// *********************************************************************************************      

// Filter shipdate input
function ShipDateTextBoxKeyPress(e)
{
	var keynum = GetKeyNumFromEvent(e);
	var keychar = GetKeyChar(keynum);
//	return IsNumeric(keychar) || keychar == '/' || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            
	return IsNumericKey(keynum) || keychar == '/' || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            	
}

// *********************************************************************************************
// Pallets Functions
// *********************************************************************************************      

// Filter pallets input
function PalletsTextBoxKeyPress(e)
{
	var keynum = GetKeyNumFromEvent(e);
//	var keychar = GetKeyChar(keynum);
//	return IsNumeric(keychar) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            
	return IsNumericKey(keynum) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            	
}

// *********************************************************************************************
// List (Locations, Line Items) Functions
// *********************************************************************************************

function AddLocationClick()
{
	// Validate the location
	if (!IsValidLocationFormat("tbLocationPostalCode","tbLocationCity","selLocationState"))
	{
		return;
	}

	var tbLocationPostalCode = document.getElementById("tbLocationPostalCode");
	var tbLocationCity = document.getElementById("tbLocationCity");
	var selLocationState = document.getElementById("selLocationState");
	var ddlSites = document.getElementById("ddlSites");

	// Get the currently selected postal code, city, and state
	var postalCode = tbLocationPostalCode.value;
	var city = tbLocationCity.value;
	var stateAndCountry = selLocationState.options[selLocationState.selectedIndex].value;

	stateAndCountryArray = stateAndCountry.split(",");

	postalCode = trim(postalCode);
	city = trim(city);
	var state = trim(stateAndCountryArray[0]);
	var country = trim(stateAndCountryArray[1]);

	var selLocationList = document.getElementById("selLocationList");

	// This is an arbitrary limit. StarRate can theoretically take an unlimited number of locations, but more than 50 is totally impractical.
	if (selLocationList.options.length == 50)
	{
		alert("You have hit the limit of 50 locations. If you really need to add more, please contact Tranzact.");
		return;
	}

	// Add it to the location list
	selLocationList.options[selLocationList.options.length] = new Option(postalCode + " " + city + ", " + state + " (" + country + ")", postalCode + "," + city + "," + state + "," + country);

	// Clear the input controls
	tbLocationPostalCode.value = "";
	tbLocationCity.value = "";
	selLocationState.selectedIndex = 0;
	if (ddlSites) 
	{
	    ddlSites.selectedIndex = 0;
	}
}

function AddLineItemClick()
{
	// Validate the line item
	if (!IsValidLineItem("tbWeight", "selClass", "tbPieces"))
	{
		return;
	}

	var tbWeight = document.getElementById("tbWeight");
	var selClass = document.getElementById("selClass");
	var defaultClass = document.getElementById("defaultClass");
	var tbPieces = document.getElementById("tbPieces");

	// Get the current weight, class, and pieces
	var weight;
	var shipclass;
	var pieces; 

	weight = trim(tbWeight.value);
	if (selClass) 
	{
	    shipclass = trim(selClass.options[selClass.selectedIndex].value);
	}
	else if (defaultClass) 
	{
	    shipclass = trim(defaultClass.value);    
	}
	else 
	{
	    shipclass = "";
	}
	if (tbPieces)
	{
		pieces = trim(tbPieces.value);
	}
	else
	{
		pieces = "";
	}

	var selLineItemList = document.getElementById("selLineItemList");

	// This is an arbitrary limit. StarRate can theoretically take an unlimited number of locations, but more than 50 is totally impractical.
	if (selLineItemList.options.length == 50)
	{
		alert("You have hit the limit of 50 line items. If you really need to add more, please contact Tranzact.");
		return;
	}

	// Add it to the line item list
	var weightdisplay;
	var shipclassdisplay;
	var piecesdisplay;

	weightdisplay = weight + " lbs.";
	if (shipclass != "")
	{
		shipclassdisplay = "class " + shipclass;
	}
	else
	{
		shipclassdisplay = "default class";
	}
	if (pieces != "" && pieces > 1)
	{
		piecesdisplay = pieces + " pieces";
	}
	else
	{
		piecesdisplay = "1 piece";
	}

	var displaytext = weightdisplay + ", " + shipclassdisplay + ", " + piecesdisplay;
	selLineItemList.options[selLineItemList.options.length] = new Option(displaytext, weight + "," + shipclass + "," + pieces);

	// Clear the input controls
	var foundDefault = false;
	tbWeight.value = "";
	if (selClass) {
	    //selClass.selectedIndex = 0;
	    for (var i = 0; i < selClass.length; i++) {
	        if (selClass.options[i].defaultSelected) { // look for an item with "selected" attribute
	            selClass.selectedIndex = i;
	            foundDefault = true;
	        }
	        if (!foundDefault) {
	            selClass.selectedIndex = 0;
	        }
	    }
    }
	if (tbPieces) {
	    tbPieces.value = "";
	}
}

function ClearAllClick(id)
{
	document.getElementById(id).options.length = 0;
}

function DeleteSelectedClick(id)
{
	var selList = document.getElementById(id);
	var selectedCount = 0;

	// Find out how many items are selected
	for (var i = 0; i < selList.options.length; i++)
	{
		if (selList.options[i].selected)
		{
			selectedCount++;
		}
	}

	// Delete the selected items 
	// Each deletion compresses the array and screws up the count so we have to do a new loop for each.
	for (var j = 0; j < selectedCount; j++)
	{
		for (var k = 0; k < selList.options.length; k++)
		{
			if (selList.options[k].selected)
			{
				// Delete the item and start another loop
				selList.options[k] = null;
				break;
			}
		}
	}
}

// Filter weight input
function WeightKeyPress(e)
{
	var keynum = GetKeyNumFromEvent(e);
	var keychar = GetKeyChar(keynum);
//	return IsNumeric(keychar) || keychar == '.'  || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            
	return IsNumericKey(keynum) || keychar == '.'  || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            	
}

// Filter pieces input
function PiecesKeyPress(e)
{
	var keynum = GetKeyNumFromEvent(e);
//	var keychar = GetKeyChar(keynum);
//	return IsNumeric(keychar) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            
	return IsNumericKey(keynum) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;            	
}

function SettingsOnChange()
{
    // Get the new setting id
    var ddlSettings = document.getElementById("ddlSettings");
    var valueArray = ddlSettings.options[ddlSettings.selectedIndex].value.split("^");
	var newSettingsId = valueArray[0];
	
	// Clear the document
	document.close();
	document.open();
	document.write("<html><head><title>StarRate</title></head><strong>Loading...</strong></html>");
	
	var altCookieName = readCookieSubkey("StarRateSettings","AlternateCookieName");
	
	if (altCookieName == "")
	{
	    // Send to settings form to recreate page
        window.location = "SettingsForm.aspx?id=" + newSettingsId;
    }
    else
    {
        // Vendor Site - Send to login form to relogin with preselected id
        window.location = "LoginForm.aspx?login=" + readCookieSubkey("StarRateSettings","Login") + "&id=" + newSettingsId;
    }
}

function NewShipment()
{
    document.getElementById("form1").reset();
    var temp = document.getElementById("selLineItemList");
    if (temp != null)
    {
        ClearAllClick("selLineItemList");
    }
    temp = document.getElementById("selLocationList");
    if (temp != null)
    {
        ClearAllClick("selLocationList");
    }
    document.getElementById("results").innerHTML = "";
}

function ddlOriginSitesOnChange()
{
    // If the individual postal code, city, and state controls exist. Populate them with the drop down selection.
    if (document.getElementById("tbOriginPostalCode") != null)
    {
        var ddlOriginSites = document.getElementById("ddlOriginSites");
        var record = ddlOriginSites.options[ddlOriginSites.selectedIndex].value.split(",");
        
        if (record[0] != "")
        {
            document.getElementById("tbOriginPostalCode").value = record[0];
            document.getElementById("tbOriginCity").value = record[1].toUpperCase();
            var stateAndCountry = record[2] + "," + record[3]
            var stateSelect = document.getElementById("selOriginState");
	        for (i = 0; i < stateSelect.options.length; i++)
	        {
		        if (stateSelect.options[i].value == stateAndCountry)
		        {
			        stateSelect.options[i].selected = true;
			        break;
		        }
	        }
	    }
	    else
	    {
	        document.getElementById("tbOriginPostalCode").value = "";
	        document.getElementById("tbOriginCity").value = "";
	        document.getElementById("selOriginState").options[0].selected = true;
	    }
    }
}

function ddlDestinationSitesOnChange()
{
    // If the individual postal code, city, and state controls exist. Populate them with the drop down selection.
    if (document.getElementById("tbDestinationPostalCode") != null)
    {
        var ddlDestinationSites = document.getElementById("ddlDestinationSites");
        var record = ddlDestinationSites.options[ddlDestinationSites.selectedIndex].value.split(",");

        if (record[0] != "")
        {
            document.getElementById("tbDestinationPostalCode").value = record[0];
            document.getElementById("tbDestinationCity").value = record[1].toUpperCase();
            var stateAndCountry = record[2] + "," + record[3]
            var stateSelect = document.getElementById("selDestinationState");
	        for (i = 0; i < stateSelect.options.length; i++)
	        {
		        if (stateSelect.options[i].value == stateAndCountry)
		        {
			        stateSelect.options[i].selected = true;
			        break;
		        }
	        }
	    }
	    else
	    {
	        document.getElementById("tbDestinationPostalCode").value = "";
	        document.getElementById("tbDestinationCity").value = "";
	        document.getElementById("selDestinationState").options[0].selected = true;
	    }
    }
}

function ddlSitesOnChange() {
    var ddlSites = document.getElementById("ddlSites");
    var record = ddlSites.options[ddlSites.selectedIndex].value.split(",");

    if (record[0] != "") {
        document.getElementById("tbLocationPostalCode").value = record[0];
        document.getElementById("tbLocationCity").value = record[1].toUpperCase();
        var stateAndCountry = record[2] + "," + record[3]
        var stateSelect = document.getElementById("selLocationState");
        for (i = 0; i < stateSelect.options.length; i++) {
            if (stateSelect.options[i].value == stateAndCountry) {
                stateSelect.options[i].selected = true;
                break;
            }
        }
    }
    else {
        document.getElementById("tbLocationPostalCode").value = "";
        document.getElementById("tbLocationCity").value = "";
        document.getElementById("selLocationState").options[0].selected = true;
    }
}

// Filter bill id input
function BillIdTextBoxKeyPress(e) {
    var keynum = GetKeyNumFromEvent(e);
    return IsNumericKey(keynum) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9;
}

function LookupBillIdClick() {
    var billId = document.getElementById("tbBillId").value;

    //alert("Lookup Bill ID = " + billId);

    // Call the lookup function
    if (billId != null && billId != "") {
        StarRate.SRWebServiceProxy.TokenLookupBillId(billId, OnBillIdSuccess, OnFailure);
    }
}

function OnBillIdSuccess(results) {
    //alert(results);

    //NOTE : need to add division
    //NOTE : need to code for multiple equipment codes        

    // Clear the form
    NewShipment();

    if (results.substr(0, 9) == "Exception") {
        alert(results);
        return;
    } 

    // Create the shipment array from the results
    // 4 sections - Bill Info, Shipment Route, Line Items, Accessorials
    var shipmentArray = results.split("\n");

    // ***** Bill Info *****
    var billInfoArray = shipmentArray[0].split(",");

    // Client Code
    if (billInfoArray[0] != readCookieSubkey("StarRateSettings", "clientCode")) {
        alert("WARNING: Client code on bill (" + billInfoArray[0] + ") does not match client code on page (" + readCookieSubkey("StarRateSettings", "clientCode") + ").");
    }

    // Division
    //billInfoArray[1];

    // Scac
    var ddlCarriers = document.getElementById("ddlCarriers");
    var carrierArray;
    if (ddlCarriers != null) {
        for (var i = 0; i < ddlCarriers.length; i++) {
            carrierArray = ddlCarriers[i].value.split(",");
            if (carrierArray[0] == billInfoArray[2]) {
                ddlCarriers.selectedIndex = i;
                break;
            }
        }
    }

    // Ship Date
	var shipDateTextBox = document.getElementById("tbShipDate");
	if (shipDateTextBox != null) {
	    shipDateTextBox.value = billInfoArray[3];
	}
	
    // Equipment
    var currentEquipmentCode = 1;
    var cbEquipment;
	while ((cbEquipment = document.getElementById("cbEquipment" + currentEquipmentCode)) != null) {
	    if (cbEquipment.value == billInfoArray[4]) {
	        cbEquipment.checked = true;
	    }
	    currentEquipmentCode++;
	}
    
    // Pallets
	var palletsTextBox = document.getElementById("tbPallets");
	if (palletsTextBox != null) {
	    palletsTextBox.value = billInfoArray[5];
	}

	// ***** Shipment Route *****
	var selLocationList = document.getElementById("selLocationList");
	var shipmentRouteArray = shipmentArray[1].split(";");
	var currentLocation;
	if (selLocationList != null) {
	    for (var i = 0; i < shipmentRouteArray.length; i++) {
	        currentLocation = shipmentRouteArray[i].split(",");
	        selLocationList.options[selLocationList.options.length] = new Option(currentLocation[0] + " " + currentLocation[1] + ", " + currentLocation[2] + " (" + currentLocation[3] + ")", currentLocation[0] + "," + currentLocation[1] + "," + currentLocation[2] + "," + currentLocation[3]);
	    }
	}

	// ***** Line Items *****
	var selLineItemList = document.getElementById("selLineItemList");
	var lineItemsArray = shipmentArray[2].split(";");
	var currentLineItem;
	var weightdisplay;
	var shipclassdisplay;
	var piecesdisplay;
	var displaytext;
	if (selLineItemList != null) {
	    for (var i = 0; i < lineItemsArray.length; i++) {
	        currentLineItem = lineItemsArray[i].split(",");

	        weightdisplay = currentLineItem[0] + " lbs.";
	        if (currentLineItem[1] != "") {
	            shipclassdisplay = "class " + currentLineItem[1];
	        }
	        else {
	            shipclassdisplay = "default class";
	        }
	        if (currentLineItem[2] != "" && currentLineItem[2] > 1) {
	            piecesdisplay = currentLineItem[2] + " pieces";
	        }
	        else {
	            piecesdisplay = "1 piece";
	        }

	        displaytext = weightdisplay + ", " + shipclassdisplay + ", " + piecesdisplay;
	        selLineItemList.options[selLineItemList.options.length] = new Option(displaytext, currentLineItem[0] + "," + currentLineItem[1] + "," + currentLineItem[2]);
	    }
	}

	// ***** Accessorials *****
	//if (shipmentArray.length > 2) {
	    var accessorialsArray = shipmentArray[3].split(",");
	    var currentAddOn = 1;
	    var cbAddOn;
	    while ((cbAddOn = document.getElementById("cbAddOn" + currentAddOn)) != null) {
	        for (var i = 0; i < accessorialsArray.length; i++) {
	            if (cbAddOn.value == accessorialsArray[i]) {
	                cbAddOn.checked = true;
	            }
	        }
	        currentAddOn++;
	    }
	//}
}

