﻿var selectedStoreNumber = -1;
//This being a template site for both party and diamond, the specific listings of the rental classes will be different.
//this variable is detectible in the specific user control that is rendered out and we need to look for that and know which type of rental
//class we are using.
var pageMode = "";
var chosenTimeUnit = "";
function Page_Window_Load(e) {
    $("#lnkPostZipCode").click(function(e) { startZipCodeClicked(e); });

    $(".backLink").click(function(e) { resetInteraction(e); });
    //get our page mode
    pageMode = $("#tblVariants").attr("rel");
    if (typeof(pageMode) == 'undefined')
        pageMode = $("#tblBundleVariants").attr("rel");
    //alert(pageMode);
    $("#tbZipCode").keydown(
	function(e) {
	    if (e.keyCode == 13) {
	        $("#lnkPostZipCode").click();
	    }

	});
    var thumbnailDiv = $("div[id$='pnlThumbnails']");
    $("a", thumbnailDiv).click(
	function(e) {

	    largeImagePopUp(e);
	    e.preventDefault();
	});
    $("a", thumbnailDiv).hover(
	 function(e) {
	     var newSrc = $("img", this).attr("src");
	     newSrc = newSrc.replace(/tiny/, "medium");
	     $("img[id$='imgProductImage']").attr("src", newSrc);
	 });
    $("a[id$='viewLargerImage']").click(
	 function(e) {
	     largeImagePopUp(e);
	     e.preventDefault();
	 });

    if (pageMode == "toolMode") {
        //in tool mode we have a mutually exclusive requirement.  We cannot allow them to have a single bid request that 
        //has multiple time units in it because the checkout interface doesn't support that.  Therefore I have to check the key pressed event
        //for each of the quantity textboxes
        $("input[id$='tbQty']").blur(function(e) {
            //this is the input
            var qtyVal = parseInt(this.value);
            //if this has a numeric value in it now,
            if ((qtyVal > 0) && (qtyVal != NaN)) {
                //if we don't have a chosen time unit, then we are choosing our first one right now.
                if (chosenTimeUnit == "") {
                    //the server renders the class name being the actual time unit the qty belongs too.
                    chosenTimeUnit = this.className;
                    //iterate through all our inputs and disable any that don't have this class name
                    $("input[id$='tbQty']").each(function() {
                        //Note: now this is the input being iterated through, not the input that had the key pressed.
                        if (this.className != chosenTimeUnit) {
                            //disable the textbox.
                            this.disabled = true;
                            //reset the value in them as a precaution
                            this.value = "0";
                        }
                    });
                } //end of if chosenTimeUnit==""
                /*because any offending form elements are disabled, we don't have to do anything in this case
                if the quantity is 1 or greater because we are adding an acceptible value on an acceptible time unit
                */
            } //end of if that checks qty >0  and ! NaN
            else {//if we are setting this item to 0, then we need to see if we need to enable the other time variants
                //if it was NaN then we clear the value to 0.
                this.value = "0";

                var total = 0;
                //iterate through all inputs of this class and get a total.  If it is zero then we enable everything again
                $("input." + chosenTimeUnit).each(function() {
                    var val = parseInt(this.value);
                    if (val == NaN) {
                        val = 0;
                    }
                    total += val;
                });
                if (total <= 0) {
                    //enable all the text boxes
                    //$("input[id$='tbQty']").enable();
                    $("input[id$='tbQty']").each(function() {
                        this.disabled = false;
                    });
                    chosenTimeUnit = "";
                }
            }
        }); //end of blur function
    }

    var initialResultsJSON = $("input[name='hdnStartAlertResults']").val();
    if (initialResultsJSON) {
        $("#rentalClasses").removeClass("hidden");
        $("#bundleControl").removeClass("hidden");
        $("#stores").addClass("hidden");
        $("#start").addClass("hidden");
        ReceiveServerData(initialResultsJSON);

    }
}

function largeImagePopUp(e) {

    var tgt = e.srcElement || e.target;
    var targetURL = "";
    if (tgt.nodeName == "A") {
        targetURL = tgt.href;
    }
    else {
        targetURL = tgt.parentNode.href;
    }
    window.open(targetURL, "help", "directories=no,location=no,menubar=no,toolbar=no,width=515px,height=705px,scrollbars=no,resizable=no");
    cancelEventDefault(e);
}

function resetInteraction(e) {
    selectedStoreNumber = -1;
    e.preventDefault();
    resetDomElements();

}
function resetDomElements() {
    $("#start").removeClass("hidden");
    $("#loading").addClass("hidden");
    $("#stores").addClass("hidden");
    $("#noStores").addClass("hidden");
    $("#rentalClasses").addClass("hidden");
    // $("#topNewSearch").addClass("hidden");
    $("#error").addClass("hidden");
    $(".add-holder").addClass("hidden");
    //reset the chosen time unit
    chosenTimeUnit = "";
    //reset all the textboxes values
    $("input[id$='tbQty']").val("");
    $("input[id$='tbQty']").each(function() { this.disabled = false; });
}


function startZipCodeClicked(e) {
    var zipCode = document.getElementById("tbZipCode").value;
    var distanceDD = document.getElementById("ddDistance");
    var distance = distanceDD.options[distanceDD.selectedIndex].value;
    if ((distance) && (zipCode)) {
        var jsonRequest = "{zipCode:" + zipCode + ",distance:" + distance + "}";
        $.ajax({
            type: "POST",
            url: "ProductDetails.aspx/GetStores",
            data: jsonRequest,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) { handleStoreResults(msg) },
            fail: function(msg) { handleStoreError(msg) },
            error: function(msg) { handleStoreError(msg) }
        });
        $("#start").addClass("hidden");
        $("#loading").removeClass("hidden");
    }
    e.preventDefault();



}
function handleStoreResults(msg) {
    if (msg.d) {
        eval(msg.d);
    }
    else {
        eval(msg);
    }
    if (results) {
        if (results.length > 0) {
            //stores are returned so we unhide the stores list and hide the loading screen
            $("#stores").removeClass("hidden");
            $("#loading").addClass("hidden");
            //first go through and clear out anything after the first li to reset from any previous searches
            //first li is always preserved so we have a template in our markup for easy editing of this look and feel
            $(".storeLi:gt(0)").remove();


            for (var i = 0; i < results.length; i++) {
                var useLi;
                if (i == 0) {
                    //first time here we want to just change the values
                    useLi = $(".storeLi:last");
                }
                else {
                    //for second and on we want to clone that first one and let it serve as our template	
                    useLi = $(".storeLi:last").clone();
                }
                if (useLi) {
                    //so long as our template li that is in our markup has elements with the class names used here, we can populate our data
                    //into the template
                    $(".name", useLi).html(results[i].Name);
                    $(".phone", useLi).html(results[i].Phone);
                    $(".distance", useLi).html(results[i].Distance);
                    $(".address", useLi).html(results[i].Address);
                    if (results[i].Address2.length > 0) {
                        $(".address2", useLi).html(results[i].Address2);
                    }
                    else {
                        $(".address2Holder", useLi).addClass("hidden");
                    }

                    $(".city", useLi).html(results[i].City);
                    $(".state", useLi).html(results[i].State);
                    $(".zip", useLi).html(results[i].Zip);
                    //use rel instead of the jquery .data because the this inside click is a dom element and it is simplest to just
                    //use the already existing dom element properties.  Seeing that rel was designed to store one bit of useful data it works out all right.
                    $(".selectBtn", useLi).attr("rel", results[i].AlertNum);
                    $(".selectBtn", useLi).click(
					function(e) {

					    var storeNum = this.attributes["rel"].value;
					    //GetStoreAvailability(storeNum);
					    selectedStoreNumber = storeNum;
					    $("#rentalClasses").removeClass("hidden");
					    $("#stores").addClass("hidden");

					    //show our top link to allow them to start a search over
					    $("#topNewSearch").removeClass("hidden");
					    var rentalClassesTable = $("#tblVariants")
					    $("#bundleControl").removeClass("hidden");
					    //hide all loaded class items in the table
					    $(".loaded", rentalClassesTable).addClass("hidden");
					    //show all loading class items in the table
					    $(".loading", rentalClassesTable).removeClass("hidden");

					    if (pageMode == "partyMode") {
					        //iterate through each of our rental classes and call alert to get its data.
					        //$("tr",rentalClassesTable).each(function(){GetAlertVariantDataParty(this)});
					        var rentalClassCollection = "";
					        $("tr", rentalClassesTable).each(function() {
					            //also rehide each row because we have a new store, and a row that was shown previously may not be available in the new
					            //store so we want to hide them all and let the results show the ones that are available.
					            $(this).addClass('hidden');
					            var classCollection = this.attributes["rel"].value;
					            rentalClassCollection += "," + classCollection.substring(1);
					        });
					        GetAlertVariantDataParty(rentalClassCollection)
					        //$("tr", rentalClassesTable).each(function() { GetAlertVariantDataParty(this) });
					        //GetAlertVariantDataParty(this)
					        e.preventDefault();
					        //show our top link to allow them to start a search over
					        $("#topNewSearch").removeClass("hidden");
					        // $(".add-holder").removeClass("hidden");
					        if ($("#tblBundleVariants").length > 0) {
					            $(".add-holder").removeClass("hidden");
					            $("#tblBundleVariants").append("<input type='hidden' id='storeNumber' name='storeNumber' value='" + selectedStoreNumber + "'/>");
					        }
					    }
					    else if (pageMode == "toolMode") {
					        //The control for tool mode renders out N rows for each variation where N is the number
					        //of different time units they rent by.  The last one in each type has a class LastInGroup
					        var toolClassCollection = "";
					        $(".LastInGroup", rentalClassesTable).each(function() {
					            //also rehide each row because we have a new store, and a row that was shown previously may not be available in the new
					            //store so we want to hide them all and let the results show the ones that are available.
					            $(this).addClass('hidden');
					            toolClassCollection += "," + this.className.split(' ')[0].trim();
					        });
					        if ($("#tblBundleVariants").length > 0) {
					            $(".add-holder").removeClass("hidden");
					            $("#tblBundleVariants").append("<input type='hidden' id='storeNumber' name='storeNumber' value='" + selectedStoreNumber + "'/>");
					        }
					        GetAlertVariantDataParty(toolClassCollection);
					        //show our top link to allow them to start a search over
					        e.preventDefault();

					        $("#topNewSearch").removeClass("hidden");
					        //$(".add-holder").removeClass("hidden");
					    }


					});
                }
                if (i != 0) {
                    //if we aren't using the first one we have a clone stored in useLi that is currently not in the dom
                    //so we insert it after the last one.
                    $(useLi).insertAfter(".storeLi:last");
                }
            }
        }
        else {
            //no stores available so we show the no stores and hide the loading screen
            $("#noStores").removeClass("hidden");
            $("#loading").addClass("hidden");
            $("#bundleControl").removeClass("hidden");

        }
    }
    else {
        //no stores available so we show the no stores and hide the loading screen
        alert("no results");
        $("#noStores").removeClass("hidden");
    }
}

function handleStoreError(msg) {
    $("#error").removeClass("hidden");
}


/************** End of the store code **************/


/************** Alert processing code **************/
function GetAlertVariantDataTool(tableRow) {
    //for tool the rel is the hourly style the class is AlertNumber and LastInGroup class on the row
    //that has this function called for it.
    var className = tableRow.className;
    var alertNumber = className.split(' ')[0].trim();
    CallAlert(alertNumber);

}

function GetAlertVariantDataParty(rentalClassCollection) {
    CallAlert(rentalClassCollection);

}


function CallAlert(alertNumber) {
    if ((alertNumber) && (selectedStoreNumber != -1)) {
        //	var jsonRequest = "{zipCode:"+zipCode+",distance:"+distance+"}";
        //        var jsonRequest = "{storeNumber:'" + selectedStoreNumber + "',alertNumber:'" + alertNumber + "', pageMode:'" + pageMode + "'}";
        //        $.ajax({
        //            type: "POST",
        //            url: "ProductDetails.aspx/GetAlertPricing",
        //            data: jsonRequest,
        //            contentType: "application/json; charset=utf-8",
        //            dataType: "json",
        //            success: function(msg) { handleAlertResult(msg) },
        //            fail: function(msg) { handleAlertError(msg) },
        //            error: function(msg) { handleAlertError(msg) }
        //        });

        //call server
        CallServer("GetAlertPricing:storeNumber=" + selectedStoreNumber + "&alertNumber=" + alertNumber + "&pageMode=" + pageMode);
    }
}
function ReceiveServerData(msg) {    
    if (msg.length > 0) {
        eval(msg);
        if (alertObject) {
            $(".add-holder").removeClass("hidden");
        }
        switch (pageMode) {
            case "toolMode":
                {
                    PopulateToolModeResult(alertObject);
                    break;
                }
            case "partyMode":
                {                    
                    PopulatePartyModeResult(alertObject);
                    break;
                }

        }
    }
}
function PopulateToolModeResult(alertObject) {

    var resutlsLength = alertObject.results.length;
    for (var i = 0; i < resutlsLength; i++) {

        var thisRentalClass = alertObject.results[i];
        selectedStoreNumber = thisRentalClass.Location;
        var productNumber = thisRentalClass.RentalClass;


        //^= is the starts with.  The server renders each row out with the alert number as the first class name
        //the space before the single quote is important.  Otherwise L166 and L1666 would cause problems for eachother
        var classRows = $("tr[class^='" + productNumber + " ']").each(function() { populateToolRow(this, thisRentalClass) });

    }


}
function populateToolRow(tableRow, thisRentalClass) {

    var timeUnit = tableRow.attributes["rel"].value;
    var priceVal = -1;
    if (thisRentalClass[timeUnit]) {
        priceVal = thisRentalClass[timeUnit];
    }
    //priceVal 0 or lower means it isn't actually offered at that time unit
    //if we do that then styling out the seperators will require some jquery and it
    //is out of scope for this iteration.
    //if(priceVal>0)
    {
        //make our dom node a jquery object
        var jqueryRow = $(tableRow);
        jqueryRow.removeClass("hidden");
        //hide loading
        $(".loading", jqueryRow).addClass("hidden");
        $(".priceHolder", jqueryRow).html("$" + priceVal);
        //show our loaded content
        $(".loaded", jqueryRow).removeClass("hidden");
    }

}

function PopulatePartyModeResult(alertObject) {
    //if we don't have the daily rate then the alert service didn't find a result.
    //if(alertObject.Daily)

    //for(var i=0; i<alertObject.results.length;i++)
    var resutlsLength = alertObject.results.length;

    //foreach(var thisRentalClass in alertObject.results)
    for (var i = 0; i < resutlsLength; i++) {

        var thisRentalClass = alertObject.results[i];
        selectedStoreNumber = thisRentalClass.Location;

        var productNumber = thisRentalClass.RentalClass;
        var productType = thisRentalClass.ProductType;

        //the party mode renders each table row with the rel='<alertNumber>';
        productNumber = productNumber.trim();
        var productRow = $("tr[rel='" + productType + productNumber + "']");
        //show our product row now that we have one
        $("tr[rel='" + productType + productNumber + "']").removeClass("hidden");

        //hide the loading content and show the loaded content
        $(".loaded", productRow).removeClass("hidden");
        $(".loading", productRow).addClass("hidden");

        //set the price on the span with the rel=<alertNumber> on it.
        if (thisRentalClass.Price != "0.00") {
            $("span[rel='" + productNumber + "']").html("$" + thisRentalClass.Price);
        }
        else {
            $("span[rel='" + productNumber + "']").html("$" + thisRentalClass.Daily);
        }

    };


}
function handleAlertError(msg) {
    //alert("error:"+msg);
}

/********* End of Alert Processing Code ***********/

/********* Custom Validator Function.
** Also serializes the choices and populates a hidden field hdnUserChoices.
** That makes it easier for the system to access the choices in a central location.*/
function ValidateAndSerializeChoices(source, arguments) {

    //args.IsValid = false;
    //arguments.IsValid;
    switch (pageMode) {
        case "toolMode":
            {
                arguments.IsValid = SerializeTooModeChoices();
                break;
            }
        case "partyMode":
            {
                arguments.IsValid = SerailizePartyModeChoices();
                break;
            }

    }
}
//Serializes the choices to xml and puts it into the hidden field hdnUserChoices.
//returns true under the following conditions:
//1.  There is at least one item with a qty greater than 0
//2.  There are no items with a non-numeric value in the qty textbox
function SerializeTooModeChoices() {
    var count = 0;
    var error = false;
    var serializedResults = "&lt;Choices storeNum='" + selectedStoreNumber + "'&gt;";
    $(".rentalClassRow").each(
	function() {
	    //if we already have an error, there is no point in doing additional processing.
	    if (!error) {
	        //turn this tr dom element into a jquery object
	        var thisRow = $(this);
	        //time unit is the rel attribute for this row
	        var timeUnit = this.attributes["rel"].value;
	        //rentak class is the first class assigned to this row
	        var rentalClass = this.className;
	        if (rentalClass) {
	            rentalClass = rentalClass.split(' ')[0].trim();
	        }
	        else {
	            error = true;
	        }
	        var qtyVal = $("input[id$='tbQty']", thisRow).val();
	        if (qtyVal == "") {
	            qtyVal = "0";
	        }
	        //get the value out of our quantity input in this row
	        var qty = parseInt(qtyVal);

	        if ((qty == NaN) || (qty < 0)) {
	            error = true;
	        }
	        count += qty;
	        var price = $(".priceHolder", thisRow).html();
	        var idVal = $("input[id$='hdnVariantID']", thisRow).val();
	        var retailVal = $("input[id$='hdnIsRetail']").val();
	        var addString = "&lt;TimeVariant&gt;&lt;ID&gt;" + idVal + "&lt;/ID&gt;&lt;IsRetail&gt;" + retailVal + "&lt;/IsRetail&gt;&lt;RentalClass&gt;" + rentalClass + "&lt;/RentalClass&gt;&lt;TimeUnit&gt;" + timeUnit + "&lt;/TimeUnit&gt;&lt;Qty&gt;" + qty + "&lt;/Qty&gt;&lt;Price&gt;" + price + "&lt;/Price&gt;&lt;/TimeVariant&gt;";
	        //var addString = "&lt;TimeVariant&gt;&lt;ID&gt;" + idVal + "&lt;/ID&gt;&lt;RentalClass&gt;" + rentalClass + "&lt;/RentalClass&gt;&lt;TimeUnit&gt;" + timeUnit + "&lt;/TimeUnit&gt;&lt;Qty&gt;" + qty + "&lt;/Qty&gt;&lt;Price&gt;" + price + "&lt;/Price&gt;&lt;/TimeVariant&gt;";
	        //only add xml for the ones that we have selected
	        if (qty != 0) {
	            serializedResults += addString;
	        }
	    }
	});
    if (count <= 0) {
        error = true;
    }
    serializedResults += "&lt;/Choices&gt;";
    if (!error) {
        $("input[id$='hdnUserChoices']").val(serializedResults);
    }
    else {
        $("input[id$='hdnUserChoices']").val("ERROR");
    }
    return !error;

}
//Serializes the choices to xml and puts it into the hidden field hdnUserChoices.
//returns true under the following conditions:
//1.  There is at least one item with a qty greater than 0
//2.  There are no items with a non-numeric value in the qty textbox
function SerailizePartyModeChoices() {
    var count = 0;
    var error = false;
    var serializedResults = "&lt;Choices storeNum='" + selectedStoreNumber + "'&gt;";
    $(".rentalClassRow").each(
	function() {
	    if (!error) {
	        //change the table row dom element to a jquery object;
	        var thisRow = $(this);
	        var rentalClass = this.attributes["rel"].value;
	        var qtyVal = $("input[id$='tbQty']", thisRow).val();
	        if (qtyVal == "") {
	            qtyVal = "0";
	        }
	        //get the value out of our quantity input in this row
	        var qty = parseInt(qtyVal);

	        if ((qty == NaN) || (qty < 0)) {
	            error = true;
	        }

	        var timeUnit;
	        var unitAndClass = this.attributes["rel"].value;
	        var unitString = unitAndClass.substring(0, 1);
	        //time unit is the rel attribute for this row
	        if (unitString == "R") {
	            timeUnit = "ServerSideKnows"

	        }
	        else {
	            timeUnit = "Price"
	        }

	        var price = $(".price", thisRow).html();

	        var idVal = $("input[id$='hdnVariantID']", thisRow).val();
	        var retailVal = $("input[id$='hdnIsRetail']").val();
	        var addString = "&lt;TimeVariant&gt;&lt;ID&gt;" + idVal + "&lt;/ID&gt;&lt;IsRetail&gt;" + retailVal + "&lt;/IsRetail&gt;&lt;RentalClass&gt;" + rentalClass + "&lt;/RentalClass&gt;&lt;TimeUnit&gt;" + timeUnit + "&lt;/TimeUnit&gt;&lt;Qty&gt;" + qty + "&lt;/Qty&gt;&lt;Price&gt;" + price + "&lt;/Price&gt;&lt;/TimeVariant&gt;";
	        //var addString = "&lt;TimeVariant&gt;&lt;ID&gt;" + idVal + "&lt;/ID&gt;&lt;RentalClass&gt;" + rentalClass + "&lt;/RentalClass&gt;&lt;TimeUnit&gt;" + timeUnit + "&lt;/TimeUnit&gt;&lt;Qty&gt;" + qty + "&lt;/Qty&gt;&lt;Price&gt;" + price + "&lt;/Price&gt;&lt;/TimeVariant&gt;";
	        //only add xml for the ones that we have selected
	        if (qty != 0) {
	            serializedResults += addString;
	        }
	        count += qty;
	    }

	});
    if (count <= 0) {
        error = true;
    }
    serializedResults += "&lt;/Choices&gt;";
    if (!error) {
        $("input[id$='hdnUserChoices']").val(serializedResults);
    }
    else {
        $("input[id$='hdnUserChoices']").val("ERROR");
    }
    return !error;
}
/******* End of custom validator related code **************/
