﻿/// <reference path="lib/jquery-1.3.2.js" />

var CCI; if (!CCI) { CCI = {}; }
if (!CCI.Pages) { CCI.Pages = {}; }
if (!CCI.Pages.Cart) { CCI.Pages.Cart = {}; }

var ServerProperties;
var BoundData;

CCI.Pages.Cart.PlanDetailInit = function() {
    $('.ratePlanDetailLink').each(function(i, e) {
        $e = $(e);
        $e.colorbox({ width: '60%', title: $e.attr("colorBoxTitle") });
    });
}

CCI.Pages.Cart.JoinAARP = function() {
    $("#AARP_in").fadeOut();
    $("#AARP_join").fadeIn();
    $("#aarp_lookupMessage").fadeOut();
    $("#Cart_CheckoutInfo_MemberId").val("");
}

CCI.Pages.Cart.InAARP = function() {
    $("#AARP_in").fadeIn();
    $("#AARP_join").fadeOut();
    $("input[name='Cart.CheckoutInfo.JoinPartner']:checked").attr('checked', false);
}

CCI.Pages.Cart.ShowAttnLine = function() {
    $("#Address_AttnInput_Button").fadeOut("slow", function() {
        $("#Address_AttnInput").fadeIn();
    });
    
}

CCI.Pages.Cart.PaymentChanged = function() {
    $cards = $('#CreditCardSection');
    if ($('#Cart_CheckoutInfo_PaymentType').val() == 2) {
        $cards.fadeIn("slow");
    } else if ($cards.is(":visible")) {
        $cards.fadeOut("slow");
    }
}

CCI.Pages.Cart.LookupAARP = function() {
    $("#aarp_lookupMessage").fadeIn();
}

CCI.Pages.Cart.ChangePartner = function() {
    var p = $("input[name='Cart.PartnerType']:checked").val();
    $(".partnerDisplay").hide();
    $(".partnerDisplay_" + p).show();
    CCI.Utility.RenderPartial("choosePlan", "UpdatePlanForPartner", "Cart", null, $("#pageForm").serialize(), function() {
        CCI.Pages.Cart.PlanDetailInit();
        BoundData.Bound();
    });
}

CCI.Pages.Cart.HidePartnerID = function(vis) {
    if (vis) {
        $(".memberIDInput").fadeIn("slow");
    } else {
        $(".memberIDInput").fadeOut("slow");
    }
}

CCI.Pages.Cart.PhoneDetails_Click = function(selector, id) {
    CCI.Utility.RenderPartial("Modal_Tmp", 'PhoneDetails', 'Info', id, null, function() {
        var params = { open: true, inline: true, href: '#Modal_Tmp', maxWidth: '680px', width: '100%', maxHeight: '580px', height: '95%' };
        params.title = "" + ServerProperties.ColorBoxTitle;
        $(selector).colorbox(params);
    });
    return false;
}

CCI.Pages.Cart.$ColorSelector = null;
CCI.Pages.Cart.PhoneSelect_Click = function(event) {
    if (CCI.Pages.Cart.$ColorSelector != null) { CCI.Pages.Cart.PhoneSelect_Close(); }
    CCI.Pages.Cart.$ColorSelector = $(this).siblings(".colorSelect");
    CCI.Pages.Cart.$ColorSelector.fadeIn();
    CCI.Pages.Cart.$ColorSelector.find("input[type='radio']").click(CCI.Pages.Cart.PhoneSelect_Close);
    CCI.Pages.Cart.Bind();
    event.stopPropagation();
}

CCI.Pages.Cart.PhoneSelect_Close = function(event) {
    if (event == undefined ||
        (CCI.Pages.Cart.$ColorSelector
            && !$(event.target).is(".colorSelect")
            && $(event.target).parents(".colorSelect").length == 0)) {
        CCI.Pages.Cart.$ColorSelector.fadeOut();
        CCI.Pages.Cart.$ColorSelector = null;
    }
}

CCI.Pages.Cart.Bind = function() {
    if (BoundData.Cart) {
        var cart = BoundData.Cart;
        var numLines = $.count(cart.Lines);
        var maxLines = CCI.Pages.Cart.GetMaxLines();

        if (numLines == maxLines) {
            $(".jsLink-CCI_Pages_Cart_AddLine").hide();
            $(".sepAddPhoneReset").hide();
            $(".jsLink-CCI_Pages_Cart_ActivateAddLine").addClass("disabled");
        } else {
            $(".jsLink-CCI_Pages_Cart_AddLine").removeClass("disabled").show();
            $(".sepAddPhoneReset").show();
            $(".jsLink-CCI_Pages_Cart_ActivateAddLine").removeClass("disabled");
        }

        $(".phoneSwatch").hide();
        $(".colorSelectTrigger:radio").attr("checked", false);
        var showPortingMessage = false;
        
        for (var i = 0; i < maxLines; i++) {
            if (cart.Lines && cart.Lines[i]) {
                var line = cart.Lines[i];

                $("#line_" + i).show();
                $(".phonecol_line_" + i).show();

                $(".jsBind-Lines_" + i + "_NameWDefault").html(line.Name ? line.Name :
                    ServerProperties && ServerProperties["Name" + i] ? ServerProperties["Name" + i] : "Phone");
                $(".jsBind-Lines_" + i + "_NameWParen").html(line.Name ? "(" + line.Name + ")" : "");

                if (line.PhoneID) {
                    $("#phoneSwatch_" + i + "_" + line.PhoneID).show(); 
                    $(".colorSelectTrigger_" + i + "_" + line.PhoneID + ":radio").attr("checked", true);                   
                    }

                showPortingMessage |= (line.Porting === "true");
                
            } else {
                $("#line_" + i).hide();
                $(".phonecol_line_" + i).hide();
            }
        }

        if (showPortingMessage) {
            if ($("#portingMessage").not(":visible")) {
                $("#portingMessage").fadeIn();
            }
        } else {
            if ($("#portingMessage").is(":visible")) {
                $("#portingMessage").fadeOut();
            }
        }
    }

    if (ServerProperties.ChangePlan) {
        CCI.Utility.RenderPartial("cartSummary", "UpdateMonthlySummary", "Account", null, $("#pageForm").serialize());
    } else {
        CCI.Utility.RenderPartial("cartSummary", "UpdateCartSummary", "Cart", null, $("#pageForm").serialize());
    }
}

CCI.Pages.Cart.GetMaxLines = function() {
    var maxLines = 3; // default to 3
    if (ServerProperties && ServerProperties.MaxLines) {
        maxLines = ServerProperties.MaxLines;
    }
    return maxLines
}

CCI.Pages.Cart.AddLine = function() {
    CCI.Pages.Cart.AddLineWithAction("PhoneAddLine");
}

CCI.Pages.Cart.ResetLines = function() {
    CCI.Pages.Cart.ResetLinesWithAction("PhoneResetLines");
}

CCI.Pages.Cart.AddLineWithAction = function(formAction) {
    var numLines = $.count(BoundData.Cart.Lines);
    var maxLines = CCI.Pages.Cart.GetMaxLines();
    if (numLines < maxLines) {
        CCI.Utility.FormAction(formAction, "Cart");
        BoundData.Cart.Lines[numLines] = {};
        BoundData.Bound();

        // When the UI adds a line, want to set the focus to the newly added (i.e. made visible) phone input box
        setTimeout(function() {
            var phoneInput = $("#Cart_Lines\\[" + numLines + "\\]_Name");
            if (phoneInput) {
                // Set the foucus and call the change event since setting focus via code does not trigger any events that a keyboard would cause
                // The change event needs to be called to allow the bound data store to behave correctly upon tabbing out of the newly focused text box
                phoneInput.focus();
                phoneInput.change();
            }
        }, 0);
    }
}


CCI.Pages.Cart.AddLineFocusHandler = function(numLines) {
    var phoneInput = $("#Cart_Lines\\[" + numLines + "\\]_Name");
    if (phoneInput.is(":visible")) {
        phoneInput.focus();
    } else {
        setTimeout(CCI.Pages.Cart.AddLineFocusHandler, 0);
    }
}

CCI.Pages.Cart.ResetLinesWithAction = function(formAction) {
    CCI.Utility.FormAction(formAction, "Cart");
    BoundData.Cart.Lines = [];
    BoundData.Cart.Lines[0] = {};
    BoundData.Bound();
}

CCI.Pages.Cart.CheckoutBind = function() {
    if (BoundData.Cart && BoundData.Cart.CheckoutInfo) {
        if (BoundData.Cart.CheckoutInfo.Referred === "true") {
            $("#referredDialog").fadeIn();
        } else {
            $("#referredDialog").fadeOut();
        }

        if (BoundData.Cart.CheckoutInfo.POBox === "true") {
            $("#AddressLine1").hide();
            $("#POBoxLine1").show();
        } else {
            $("#AddressLine1").show();
            $("#POBoxLine1").hide();
        }
    }
}

CCI.Pages.Cart.InProcessSave = {}
CCI.Pages.Cart.InProcessSave.Save = function() {
    CCI.Pages.Cart.InProcessSave.Clear();
    CCI.Pages.Cart.InProcessSave.Timeout = setTimeout(
        function() {
            CCI.Utility.Action("SaveCart", "Cart", $("#pageForm").serialize()); 
        }, 1500);
}

CCI.Pages.Cart.InProcessSave.Timeout = null;
CCI.Pages.Cart.InProcessSave.Clear = function() {
    if (CCI.Pages.Cart.InProcessSave.Timeout) {
        clearTimeout(CCI.Pages.Cart.InProcessSave.Timeout);
    } 
}

CCI.Pages.Cart.OnSubmit = function() {
    var params = $("#pageForm").serialize();
    
    if (CCI.Validation && CCI.Validation.CurrentErrors){
        for(var i = 0; i < CCI.Validation.CurrentErrors.length; i++){
            params += "&" + escape("ClientSideErrors[" + i + "]") + "=" + escape(CCI.Validation.CurrentErrors[i]);
        }
    }

    CCI.Utility.Action("SaveCart", "Cart", params);
}

CCI.Pages.Cart.Init = function() {
    BoundData.OnBound.push(CCI.Pages.Cart.Bind);
    CCI.Pages.Cart.Bind();
}

CCI.Pages.Cart.PlanInit = function() {
    CCI.Pages.Cart.Init();
    CCI.Pages.Cart.PlanDetailInit();
    CCI.Map.Init();
    $("input[name='Cart.PartnerType']").click(CCI.Pages.Cart.ChangePartner);
}

CCI.Pages.Cart.PhonesInit = function() {
    CCI.Pages.Cart.Init();
    CCI.Pages.Info.SetupComparisonChart();
    CCI.Pages.Info.PhoneColorSwapping();
    CCI.Pages.Info.PhoneImageSwapping();
    $('.phoneSelectRB').removeAttr('disabled');
    $(".phoneSelect input[type='radio']").click(CCI.Pages.Cart.PhoneSelect_Click);
    $(document).click(CCI.Pages.Cart.PhoneSelect_Close);
}

CCI.Pages.Cart.CheckoutInitCommon = function() {
    CCI.Pages.Cart.Init();
    $('.creditCheckTerms').colorbox({ width: '40%', title: "Credit Check Terms" });
    $('.cciHelp').colorbox({ width: '70%' });
    $('.billingPref').colorbox({ width: '50%', title: "Billing Preferences" });
    $('.paymentPref').colorbox({ width: '50%', title: "Payment Preferences" });
    $('.whySSN').colorbox({ width: '40%', title: "Social Security Number" });
    $('.aarpHelp').colorbox({ width: '100%', maxWidth: "650px", title: "Where can I find my AARP Member ID number?" });

    var partialUrl = CCI.Utility.PathToAction("Privacy", "Home", null, true);
    $('.morePrivacyLink').colorbox({ width: '100%', maxWidth: "650px", height: '95%', maxHeight: "600px", title: "Privacy and Security", href: partialUrl });

    if (ServerProperties && ServerProperties.CheckoutInProcessSave && ServerProperties.CheckoutInProcessSave == "Full") {
        $("#pageForm input").change(CCI.Pages.Cart.InProcessSave.Save); 
    } else {
        $("#Cart_CheckoutInfo_FirstName, #Cart_CheckoutInfo_LastName, #Cart_CheckoutInfo_Email").change(CCI.Pages.Cart.InProcessSave.Save);
    }
        
    CCI.Validation.InvalidHandler = CCI.Pages.Cart.OnSubmit;

    $("#Cart_CheckoutInfo_NotAnAAAMember").change(function() {
        CCI.Pages.Cart.HidePartnerID(!$(this).is(":checked"));
    })

}

CCI.Pages.Cart.CheckoutInit = function() {
    CCI.Pages.Cart.CheckoutInitCommon();
    CCI.Pages.Cart.SetupDirectMailCode();    
    $('.ProductsOnlyOrderDetail').colorbox({ width: '50%', title: "Order Detail" });
    $('.orderDetails').live("click", function(event) {
        $(this).colorbox({ open: true, width: '70%', title: "Order Detail" });
        return false;
    });
    
    BoundData.OnBound.push(CCI.Pages.Cart.CheckoutBind);
}

CCI.Pages.Cart.ActivateCheckoutInit = function() {
    CCI.Pages.Cart.CheckoutInit();
    $("#Cart_CheckoutInfo_PaymentType").change(CCI.Pages.Cart.PaymentChanged)
}

CCI.Pages.Cart.PaymentViewChangeInit = function() {
    $("#useDifferentCard").click(function() {
        $("#newCard").show();
        $("#existingCard").hide();
        $("#Cart_CheckoutInfo_UseExistingCard").val(false);
        return false;
    });

    $("#useExistignCard").click(function() {
        $("#existingCard").show();
        $("#newCard").hide();
        $("#Cart_CheckoutInfo_UseExistingCard").val(true);
        return false;
    });
}

CCI.Pages.Cart.PortingInit = function() {
    $(".choosePortOption[value='true']").attr("checked", "checked");
    $(".choosePortOption").change(function() {
        $(".portingAccountInfo").fadeInOut($(".choosePortOption:checked").val() == "false");
    });
    $(".portingAccountInfo").showHide(!$(".choosePortOption:selected").val);
    $('.orderDetails').live("click", function(event) {
        $(this).colorbox({ open: true, width: '70%' });
        return false;
    });
}

CCI.Pages.Cart.ActivateInit = function() {
    CCI.Pages.Cart.Init();
}

CCI.Pages.Cart.ActivateChangePartner = function() {
    var p = $("input[name='Cart.PartnerType']:checked").val();
    $(".partnerDisplay").fadeOut();
    $(".partnerDisplay_" + p).fadeIn();
    CCI.Utility.RenderPartial("choosePlans", "UpdatePlanAndMessagePlanForPartner", "Cart", null, $("#pageForm").serialize(), function() {
        CCI.Pages.Cart.PlanDetailInit();
        BoundData.Bound();
    });
}

CCI.Pages.Cart.ActivateAddLine = function(e) {
    CCI.Pages.Cart.AddLineWithAction("ActivateAddLine");
}

CCI.Pages.Cart.ActivateResetLines = function() {
    CCI.Pages.Cart.ResetLinesWithAction("ActivateResetLines");
}

CCI.Pages.Cart.StartActivationPolling = function() {
    setTimeout(CCI.Pages.Cart.PollActivation, 2500);    
}

CCI.Pages.Cart.PollActivation = function() {
    CCI.Utility.Action("ActivateNow", "Cart", { id: 1, format: "Partial" }, function(res) {
        if (res === "1") {
            window.location.replace(CCI.Utility.PathToAction("Activated", "Cart"));
        } else if (res === "-1") {
            window.location.replace(CCI.Utility.PathToAction("ActivateError", "Cart"));
        } else {
            setTimeout(CCI.Pages.Cart.PollActivation, 2500);
        }
    });
}

CCI.Pages.Cart.SetupDirectMailCode = function() {
    var lsVal = $(".leadSourceSelector option:selected").text();
    if (lsVal.indexOf("Direct Mail") == -1) {
        $(".discountCode").hide();
    } else {
        $(".discountCode").show();
    }
    $(".leadSourceSelector").live("change", function() {
        var lsVal2 = $(".leadSourceSelector option:selected").text();
        if (lsVal2.indexOf("Direct Mail") != -1) {
            $(".discountCode").fadeIn("slow");
        } else {
            $(".discountCode").fadeOut("slow");
        }
    });
};


