/**
 *  Javascript functions for the support section.
 */
/**
 *	This sets up the details for changing the states for US, Canada and Mexico.
 */
var states_list = {
	US: [
		{code: "AL", name: "Alabama"},
		{code: "AK", name: "Alaska"},
		{code: "AZ", name: "Arizona"},
		{code: "AR", name: "Arkansas"},
		{code: "CA", name: "California"},
		{code: "CO", name: "Colorado"},
		{code: "CT", name: "Connecticut"},
		{code: "DE", name: "Delaware"},
		{code: "FL", name: "Florida"},
		{code: "GA", name: "Georgia"},
		{code: "HI", name: "Hawaii"},
		{code: "ID", name: "Idaho"},
		{code: "IL", name: "Illinois"},
		{code: "IN", name: "Indiana"},
		{code: "IA", name: "Iowa"},
		{code: "KS", name: "Kansas"},
		{code: "KY", name: "Kentucky"},
		{code: "LA", name: "Louisiana"},
		{code: "ME", name: "Maine"},
		{code: "MD", name: "Maryland"},
		{code: "MA", name: "Massachusetts"},
		{code: "MI", name: "Michigan"},
		{code: "MN", name: "Minnesota"},
		{code: "MS", name: "Mississippi"},
		{code: "MO", name: "Missouri"},
		{code: "MT", name: "Montana"},
		{code: "NE", name: "Nebraska"},
		{code: "NV", name: "Nevada"},
		{code: "NH", name: "New Hampshire"},
		{code: "NJ", name: "New Jersey"},
		{code: "NM", name: "New Mexico"},
		{code: "NY", name: "New York"},
		{code: "NC", name: "North Carolina"},
		{code: "ND", name: "North Dakota"},
		{code: "OH", name: "Ohio"},
		{code: "OK", name: "Oklahoma"},
		{code: "OR", name: "Oregon"},
		{code: "PA", name: "Pennsylvania"},
		{code: "RI", name: "Rhode Island"},
		{code: "SC", name: "South Carolina"},
		{code: "SD", name: "South Dakota"},
		{code: "TN", name: "Tennessee"},
		{code: "TX", name: "Texas"},
		{code: "UT", name: "Utah"},
		{code: "VT", name: "Vermont"},
		{code: "VA", name: "Virginia"},
		{code: "WI", name: "Wisconsin"},
		{code: "WA", name: "Washington"},
		{code: "DC", name: "Washington D.C."},
		{code: "WV", name: "West Virginia"},
		{code: "WY", name: "Wyoming"}
	],
	CA: [
		{code: "AB", name: "Alberta"},
		{code: "BC", name: "British Columbia"},
		{code: "MB", name: "Manitoba"},
		{code: "NB", name: "New Brunswick"},
		{code: "NL", name: "Newfoundland"},
		{code: "NT", name: "Northwest Territories"},
		{code: "NS", name: "Nova Scotia"},
		{code: "NU", name: "Nunavut"},
		{code: "ON", name: "Ontario"},
		{code: "PE", name: "Prince Edward Island"},
		{code: "QC", name: "Quebec"},
		{code: "SK", name: "Saskatchewan"},
		{code: "YT", name: "Yukon Territory"}
		 ],
	MX: [
		{code: "AG", name: "Aguascalientes"},
		{code: "BC", name: "Baja California"},
		{code: "BS", name: "Baja California Sur"},
		{code: "CM", name: "Campeche"},
		{code: "CS", name: "Chiapas"},
		{code: "CH", name: "Chihuahua"},
		{code: "CO", name: "Coahuila de Zaragoza"},
		{code: "CL", name: "Colima"},
		{code: "DF", name: "Distrito Federal"},
		{code: "DG", name: "Durango"},
		{code: "GT", name: "Guanajuato"},
		{code: "GR", name: "Guerrero"},
		{code: "HG", name: "Hidalgo"},
		{code: "JA", name: "Jalisco"},
		{code: "ME", name: "Mexico"},
		{code: "MI", name: "Michoacan de Ocampo"},
		{code: "MO", name: "Morelos"},
		{code: "NA", name: "Nayarit"},
		{code: "NL", name: "Nuevo Leon"},
		{code: "OA", name: "Oaxaca"},
		{code: "PB", name: "Puebla"},
		{code: "QE", name: "Queretaro Arteaga"},
		{code: "QR", name: "Quintana Roo"},
		{code: "SL", name: "San Luis Potosi"},
		{code: "SI", name: "Sinaloa"},
		{code: "SO", name: "Sonora"},
		{code: "TB", name: "Tabasco"},
		{code: "TM", name: "Tamaulipas"},
		{code: "TL", name: "Tlaxcala"},
		{code: "VE", name: "Veracruz Llave"},
		{code: "YU", name: "Yucatan"},
		{code: "ZA", name: "Zacatecas"}
	],
	RO: [
		{code: "AB", name: "Alba"},
		{code: "AR", name: "Arad"},
		{code: "AG", name: "Arges"},
		{code: "BC", name: "Bacau"},
		{code: "BH", name: "Bihor"},
		{code: "BN", name: "Bistrita-Nasaud"},
		{code: "BT", name: "Botosani"},
		{code: "BR", name: "Braila"},
		{code: "BV", name: "Brasov"},
		{code: "BU", name: "Bucuresti"},
		{code: "BZ", name: "Buzau"},
		{code: "CL", name: "Calarasi"},
		{code: "CS", name: "Caras-Severin"},
		{code: "CJ", name: "Cluj"},
		{code: "CT", name: "Constanta"},
		{code: "CV", name: "Covasna"},
		{code: "DB", name: "Dambovita"},
		{code: "DJ", name: "Dolj"},
		{code: "GL", name: "Galati"},
		{code: "GR", name: "Giurgiu"},
		{code: "GJ", name: "Gorj"},
		{code: "HR", name: "Harghita"},
		{code: "HD", name: "Hunedoara"},
		{code: "IL", name: "Ialomita"},
		{code: "IS", name: "Iasi"},
		{code: "MM", name: "Maramures"},
		{code: "MH", name: "Mehedinti"},
		{code: "MS", name: "Mures"},
		{code: "NT", name: "Neamt"},
		{code: "OT", name: "Olt"},
		{code: "PH", name: "Prahova"},
		{code: "Salaj", name: "SJ"},
		{code: "Satu Mare", name: "SM"},
		{code: "SB", name: "Sibiu"},
		{code: "SV", name: "Suceava"},
		{code: "TR", name: "Teleorman"},
		{code: "TM", name: "Timis"},
		{code: "TL", name: "Tulcea"},
		{code: "VL", name: "Valcea"},
		{code: "VS", name: "Vaslui"},
		{code: "VN", name: "Vrancea"}
	],
	UP: [
		{code: "KR", name: "Avtonomna Respublika Krym"},
		{code: "CK", name: "Cherkas'ka Oblast'"},
		{code: "CH", name: "Chernihivs'ka Oblast'"},
		{code: "CV", name: "Chernivets'ka Oblast'"},
		{code: "DP", name: "Dnipropetrovs'ka Oblast'"},
		{code: "DT", name: "Donets'ka Oblast'"},
		{code: "IF", name: "Ivano-Frankivs'ka Oblast'"},
		{code: "KK", name: "Kharkivs'ka Oblast'"},
		{code: "KS", name: "Khersons'ka Oblast'"},
		{code: "KM", name: "Khmel'nyts'ka Oblast'"},
		{code: "KH", name: "Kirovohrads'ka Oblast'"},
		{code: "KV", name: "Kyyivs'ka Oblast'"},
		{code: "LV", name: "L'vivs'ka Oblast'"},
		{code: "LH", name: "Luhans'ka Oblast'"},
		{code: "KC", name: "Misto Kyyiv"},
		{code: "SC", name: "Misto Sevastopol"},
		{code: "MY", name: "Mykolayivs'ka Oblast'"},
		{code: "OD", name: "Odes'ka Oblast'"},
		{code: "PL", name: "Poltavs'ka Oblast'"},
		{code: "RV", name: "Rivnens'ka Oblast'"},
		{code: "SM", name: "Sums'ka Oblast'"},
		{code: "TP", name: "Ternopil's'ka Oblast'"},
		{code: "VI", name: "Vinnyts'ka Oblast'"},
		{code: "VO", name: "Volyns'ka Oblast'"},
		{code: "ZK", name: "Zakarpats'ka Oblast'"},
		{code: "ZP", name: "Zaporiz'ka Oblast'"},
		{code: "ZT", name: "Zhytomyrs'ka Oblast'"}
	]
};


/**
 *  This function controls the forms and validation.
 *
 *  Requirements:
 *      Forms MUST have an ID set.
 *
 *      Form fields can have the following classes for validation:
 *          required - A value is required in the field
 *
 *      Forms can reply with the following details:
 *          success - True or false
 *          message - A message to display (shown if 'success' is true)
 *          error - An error to display (shown if 'success' is false)
 *          redirect - The page URL to redirect to on success
 */
Forms = function () {

    var valid_form;

    /**
     *  Set the forms to Ajax submit
     */
    function makeAjaxForms () {
        $("form.ajaxSubmit").each (function (i, el) {
            $(this).submit (function (e) {
                e.preventDefault ();

                // Disable the form fields
                // $("#" + el.id + " :input").attr ("disabled", true);
                // var starting_submit_value = $("#" + el.id + " :submit").attr ("value");

                // Is the form valid?
                var valid_form = true;
                var el_name = "";
                var separator = "";
                var field_values = "";

                $("#" + el.id + " :input").each (function (i, field_el) {
                    // Check each field to see if it is valid;
                    var valid_field;

                    if ($(field_el).is (".required")) {
                        valid_field = validateRequired (field_el);
                    } // if ()

                    field_values = field_values + separator + field_el.name + "=" + field_el.value;
                    separator = "&";
                });

                if (valid_form == true) {
                    var url = $(this).attr ("action");
                    var values = $(this).serialize ();

                    submitForm (this, url, field_values);
                } // if ()
                else {
                    $("#" + el.id + " :input").attr ("disabled", false);
                } // else
            });
        });
    } // makeAjaxForms ()

    /**
     *  This function sets up the subscription update fields to update with the
     *  correct pricing.
     */
    function setUpdateFields () {
        $("#sub_qty_field").keyup (function () {
            var qty = parseInt ($(this).attr ("value"));
            var price = parseFloat ($("#sub_price_container").text ());
            var delivery = parseFloat ($("#sub_delivery_container").text ());

            if (isNaN (qty) || qty < 1) {
                qty = 1;
            } // if ()

            var sub_total = parseFloat ((qty * price));
            var total = (sub_total + delivery);
            total = parseFloat (total).toFixed (2);

            $("#sub_qty_container").text (qty);
            $("#sub_subtotal_container").text (sub_total.toFixed (2));
            $("#sub_total_container").text (total);
        });
    } // setUpdateFields ()

    /**
     *  This function submits the form values and processes the result.
     */
    function submitForm (form, url, values) {
        // Lets submit!
        $.post (url + "/format/json", values, function (response) {
            if (response.success == true) {
                handleSuccess (response);
            } // if ()
            else {
                handleFailure (response);
            } // else

            // Enable the form fields
            $("#" + form.id + " :input").attr ("disabled", false);
        }, "json");
    } // submitForm ()

    /**
     *  This function handles the AJAX success.
     */
    function handleSuccess (response) {
        // Do we have a message to display?
        if (response.message != undefined && response.message.length > 0) {
            alert (response.message);
        } // if ()

        // Are we redirecting?
        if (response.redirect != undefined && response.redirect.length > 0) {
            window.location = getBaseUrl () + response.redirect
        } // if ()
    } // handleSuccess ()

    /**
     *  This function handles the AJAX failure.
     */
    function handleFailure (response) {
        var msg = response.error;

        if (msg.length == 0) {
            msg = "Your request could not be completed.";
        } // if ()

        alert (msg);

        // Are we redirecting?
        if (response.redirect != undefined && response.redirect.length > 0) {
            window.location = getBaseUrl () + response.redirect
        } // if ()
    } // handleFailure ()

    /**
     *  Validate that the value is required
     */
    function validateRequired (field) {
        if (field.value.length == 0) {
            valid_form = false;
            $(field).addClass ("invalid");
        } // if ()
        else {
            $(field).removeClass ("invalid");
        } // else
    } // validateRequired ()

    /**
     *  This gets the base value from the head of the document.
     */
    function getBaseUrl () {
        var base = "";

        if ($("base") != undefined) {
            base = $("base").attr ("href");
        } // if ()

        return base;
    } // getBaseUrl ()

    /**
     *  Set public values/functions.
     */
    return {
        makeAjaxForms:makeAjaxForms,
        setUpdateFields: setUpdateFields,
        getBaseUrl: getBaseUrl
    };

} ();


Links = function () {

    /**
     *  Add a warning message to the 'cancel' links.
     */
    function addCancelWarning () {
        $(".cancel_subscription_link").click (function (e) {
            e.preventDefault ();

            var response = confirm ("Are you sure that you want to cancel this subscription?\n\nClick 'OK' to continue, or 'Cancel' to stop.");

            if (response == true) {
                window.location = Forms.getBaseUrl () + $(this).attr ("href");
            } // if ()
        });
    } // addCancelWarning ()

    /**
     *  Sets the 'log out' link as an Ajax call.
     */
    function setLogout () {
        $("#logout_menu_link").click (function (e) {
            e.preventDefault ();

            var response = confirm ("Do you want to log out of the support system?");

            if (response == true) {
                var base = Forms.getBaseUrl ();

                $.post (base + "recovery/support/logoutprocess/format/json", {}, function () {
                    // All we want to do is re-direct...
                    window.location = base + "recovery/support";
                }, "json");
            } // if ()
        });
    } // setlogout ()

    return {
        addCancelWarning: addCancelWarning,
        setLogout: setLogout
    };

} ();

PaymentForm = function () {

    var cc_format_visa = [4, 4, 4, 4];
	var cc_format_amex = [4, 6, 5];

	var cc_format = cc_format_visa;

    function setCc (type) {
        if (type == "Amex") {
			cc_format = cc_format_amex;
		} // if ()
		else {
			cc_format = cc_format_visa;
		} // else

        PaymentForm.formatCc ();
    } // setCc ()

    function formatCc () {
        var cc_input = $("#cc_number");

		var cc_val = cc_input.val ();
		cc_val = cc_val.replace (/[^0-9]/g, "");
		var formatted = "";
		var tmp;

		for (var i = 0; i < cc_format.length; i++) {
			if (i > 0 && cc_val.length > 0) {
				formatted = formatted + " ";
			} // if ()

			tmp = cc_val.substring (0, cc_format [i]);
			cc_val = cc_val.substring (cc_format [i]);

			formatted = formatted + tmp;
		} // for ()

		cc_input.val (formatted);
    } // function formatCc ()

    return {
        setCc: setCc,
        formatCc: formatCc
    };

} ();



UpdateForm = function () {

    var cc_format_visa = [4, 4, 4, 4];
	var cc_format_amex = [4, 6, 5];

	var cc_format = cc_format_visa;

    function updateDisplay () {
        var product_id = $("#product_id_select").val ();
        var product = null;

        for (var i = 0; i < products.length; i++) {
            if (product_id == products [i].id) {
                product = products [i];
            } // if ()
        } // for ()

        var months = parseFloat ($("#choose_months").val ());
/*
        if (months < 1) {
            months = 1;
        } // if ()
*/
		if (months == 0) {
			var item_price = parseFloat (product.price_per_item_order);
			var delivery_price = parseFloat (product.ship_price_order);
		} // if ()
		else {
			var item_price = parseFloat (product.price_per_item_autoship);
			var delivery_price = parseFloat (product.ship_price_autoship);
		} // else


        var item_price_discount = item_price;
        var qty = parseInt (product.ship_qty);

        var delivery_price_discount = delivery_price;

        // Do we have a coupon?
        if (coupon != null) {
			if (coupon.discount_amount_item > 0) {
				item_price_discount = parseFloat (item_price) - parseFloat (coupon.discount_amount_item);
			} // if ()

			if (coupon.discount_amount_total > 0) {
				discount_total_amount = coupon.discount_amount_total;
			} // if ()

			if (coupon.discount_amount_percent > 0) {
				discount_total_percent = 100 - parseFloat (coupon.discount_amount_percent);
			} // if ()

			if (coupon.discount_shipping != undefined && coupon.discount_shipping.length > 0) {
				delivery_price_discount = parseFloat (coupon.discount_shipping);
			} // if ()

			$("#top_total_full").css ("display", "inline");
		} // if ()
        else {
            $("#top_total_full").css ("display", "none");
        } // else

        // Update the totals
        var items_total = item_price * qty;
        var total = items_total + delivery_price;
        var discount_total = item_price_discount * qty + delivery_price_discount;

        $("#checkout-item-price-auto").html ("$" + items_total.toFixed (2));

        $("#item-delivery-total-auto").html ("$" + delivery_price.toFixed (2));

        var price = "$" + discount_total.toFixed (2);
        document.getElementById ("top_total_discount").innerHTML = "";

        $("#top_total_full").text ("$" + total.toFixed (2));
        $("#top_total_discount").text (price);

        if (parseInt ($("#choose_months").val ()) > 0) {
            // show 'every month'
            var s = "";
            var months = "";

            if (parseInt ($("#choose_months").val ()) > 1) {
                s = "s";
                months = " "  + $("#choose_months").val () + " ";
            } // if ()

            $("#display_period_area").html ("&nbsp;&nbsp;every" + months + " month" + s);
        } // if ()
        else {
            // Show 'once-off'
            $("#display_period_area").html ("&nbsp;&nbsp;once off");
        } // else

        // Set the hidden form values
        $("#item_id").val (product.id);
        $("#item_qty").val (product.ship_qty);
        $("#item_price").val (product.item_price);
        $("#item_delivery").val (product.ship_price);
    } // updateDisplay ()

    function checkCoupon () {
        var data = {
			coupon: $("#coupon").val ()
		};

		var button_area = $("#coupon_button_area");
		var checking_area = $("#coupon_check_area");

		button_area.css ("display", "none");
		checking_area.css ("display", "inline");

        if (data.coupon.length > 0) {
            // Check the voucher...
            $.post ("recovery/buy/checkcoupon/format/json", data, function (data) {
                if (data.success == true) {
                    // alert ("Found a voucher!");

                    // checking_area.css ("display", "none");
					if (data.first_order == "No") {
						if (data.bound_product != undefined) {
							var product_select = $("#product_id_select");

							product_select.val (data.bound_product);
							product_select.change ();
							product_select.attr ("disabled", "disabled");
						} // if ()

						coupon = {
							discount_amount_total: data.discount_amount_total,
							discount_amount_percent: data.discount_amount_percent,
							discount_amount_item: data.discount_amount_item,
							discount_shipping: data.discount_shipping
						};

						UpdateForm.updateDisplay ();
					} // if ()
					else {
						alert ("This coupon is not valid for your order.");
					} // else
                } // if ()
                else {
                    var msg = data.message;

                    alert (msg);
                } // else

                button_area.css ("display", "inline");
                checking_area.css ("display", "none");
            }, "json");
        } // if ()
        else {
            // Remove the voucher...
            coupon = null;
            $("#product_id_select").removeAttr ("disabled");
            UpdateForm.updateDisplay ();

            button_area.css ("display", "inline");
            checking_area.css ("display", "none");
        } // else
    } // checkCoupon ()

    function setCc (type) {
        if (type == "Amex") {
			cc_format = cc_format_amex;
		} // if ()
		else {
			cc_format = cc_format_visa;
		} // else

        UpdateForm.formatCc ();
    } // setCc ()

    function formatCc () {
        var cc_input = $("#CardNumber");

		var cc_val = cc_input.val ();
		cc_val = cc_val.replace (/[^0-9]/g, "");
		var formatted = "";
		var tmp;

		for (var i = 0; i < cc_format.length; i++) {
			if (i > 0 && cc_val.length > 0) {
				formatted = formatted + " ";
			} // if ()

			tmp = cc_val.substring (0, cc_format [i]);
			cc_val = cc_val.substring (cc_format [i]);

			formatted = formatted + tmp;
		} // for ()

		cc_input.val (formatted);
    } // function formatCc ()

    return {
        updateDisplay: updateDisplay,
        checkCoupon: checkCoupon,
        setCc: setCc,
        formatCc: formatCc
    };

} ();

DeliveryDetailsForm = function () {

    function setStates (field_id, country_code) {
        var state_select = $("#state_select_" + field_id);
		var list = states_list [country_code];

		if (list.length > 0) {
			state_select.empty ();
			state_select.append ("<option value=\"\">Please Select</option>\n");
			var item;

			for (var i = 0; i < list.length; i++) {
				item = list [i];
				state_select.append ("<option value=\"" + item.code + "\">" + item.name + "</option>\n");
			} // for ()
		} // if ()




    } // setStates ()

    return {
        setStates: setStates
    };

} ();



// Start the system going...
$(document).ready (function () {
    // Set up the forms
    Forms.makeAjaxForms ();
    Forms.setUpdateFields ();

    // Set up the links
    Links.addCancelWarning ();
    Links.setLogout ();




    $("#product_id_select").change (function () {
        UpdateForm.updateDisplay ();
    });

    $("#choose_months").change (function () {
        UpdateForm.updateDisplay ();
    });

    $("#codeSubmit").click (function (e) {
        e.preventDefault ();

        UpdateForm.checkCoupon ()
    });

    $("#card_type_select").change (function () {
        UpdateForm.setCc ($(this).val ());
    });

    $("#CardNumber").keyup (function () {
        UpdateForm.formatCc ();
    });

    $("#cc_visa").click (function (e) {
        UpdateForm.setCc ("Visa");
        $("#card_type_select").val ("Visa");
    });

    $("#cc_master").click (function (e) {
        UpdateForm.setCc ("Mastercard");
        $("#card_type_select").val ("Mastercard");
    });

    $("#cc_amex").click (function (e) {
        UpdateForm.setCc ("Amex");
        $("#card_type_select").val ("Amex");
    });

    $("#cc_type").change (function () {
        PaymentForm.setCc ($(this).val ());
        PaymentForm.formatCc ();
    });

    $("#cc_number").keyup (function () {
        PaymentForm.formatCc ();
    });

    $(".country_select").change (function () {
        var id = $(this).attr ("id");
        var code = $(this).val ();

        id = id.substring (id.lastIndexOf ("_") + 1);

        DeliveryDetailsForm.setStates (id, code);
    });
});

