/* START PREQUAL OVERLAYS FUNCTIONS */
function openPrequal(href) {
    $.ajax({
        type: "POST",
        url: "/index/prequal/do/is-prequaled",
        dataType: "json",
        async: false,
        success: function(response) {
            var set_href = false;
            if(href) {
                if(response.prequaled == 1) {
                    goToURL(href);
                    return false;
                } else {
                    set_href = true;
                }
            }
            $.ajax({
                type: "POST",
                url: "/index/prequal/do/show",
                dataType: "json",
                async: false,
                success: function(response){
                    // check the session timeout
                    if (response.timeout) {
                        goToURL(response.redirect);
                        return false;
                    }
                    resetValues();
                    var overlay = $("#overlays").find("#" + response.div);
                    if(set_href) {
                        $("#continue-link").attr("href", href);
                        //To populate the overlay for compare plans
                        if (href == '#compare-plans-clear-overlay') {
                            $("#continue-link").click( function() {
                                var overlay = $("#overlays").find("#" + href);
                                CLEAR.utils.OverlayController.show(overlay);
                                comparePlans(document.getElementById('plannumber').value);
                            });
                        }
                    }
                    CLEAR.utils.OverlayController.show(overlay);
                    sendOmnitureTracking('index:' + response.div, 6);
                }
            });
        }
    });
    
    return false;
}

function submitPrequal(id, latlong) {
    //get the form object
    var form = $("#" + id).parents('form:first');
    
    var error = false;
    var message = '';
        
    if(typeof(latlong) == 'undefined') {
        //get the address and the zip code
        var data = { 
            address: $("input[name=street-address]", form).val(), 
            zip: $("input[name=zip-code]", form).val()
        };
        
        var email = $("input[name=email-address]", form).val();
        
        if(typeof(email) != 'undefined') {
            data.email = $("input[name=email-address]", form).val();
            data.insider = $("input[name=clear-insider]", form).is(":checked");
        }
        
        //validate input
        if(!data.address) {
            error = true;
            message += "<br />Please enter your Address.";
        }

        if(!data.zip || !data.zip.match(/[0-9]{5}/)) {
            error = true;
            message += "<br />Please enter a valid Zip Code.";
        }
        
        if(data.insider) {
            if(!data.email) {
                error = true;
                message += "<br />Please enter your E-mail Address or uncheck the Sign up for CLEAR insider checkbox.";
            }
        }
        
        if(data.email) {
            if(!data.email.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)) {
                error = true;
                message += "<br />Please enter a valid E-mail Address.";
            }
        }
        
        $("#" + id + "-message").html(message);
        $("#" + id + "-suggestions").html("");
    } else {
        var data = {
            lat: $("input[name=lat]", form).val(),
            lng: $("input[name=lng]", form).val()
        };
    }
    
    if(!error) {
        $.ajax({
            type: "POST",
            url: "/index/prequal/do/prequal",
            data: data,
            dataType: "json",
            success: function(response){
                // check the session timeout
                if (response.timeout) {
                    goToURL(response.redirect);
                    return false;
                }
                //if we need to switch div, show the appropriate one
                var overlay = $("#overlays").find("#" + response.div);
                if(overlay.length > 0) {
                    //following code changes compare plans widget links after prequal         
                    var prequaled_links = document.getElementById("prequaled");
                    var doprequal_links = document.getElementById("doprequal");
                    if (doprequal_links) {
                        doprequal_links.style.display = "none";
                        if (prequaled_links) {
                            prequaled_links.style.display = "block";
                        }    
                    }
                    //End of code for compare plans
                    //resetValues();
                    var overlay = $("#overlays").find("#" + response.div);
                    CLEAR.utils.OverlayController.show(overlay);
                    //$("#" + response.div + " .ui-formulate-button, input").formulate();
                }
                if(response.success) {
                    if(response.network == 1) {
                        $("input[name=address]").val(data.address);
                        $("input[name=zip]").val(data.zip);
                        sendOmnitureTracking('index:' + response.div, 7, 'n|' + $("input[name=zip-code]", form).val() + '|' + $("input[name=street-address]", form).val());
                    } else if (response.network == 2){
                        sendOmnitureTracking('index:' + response.div, 7, 'y|' + $("input[name=zip-code]", form).val() + '|' + $("input[name=street-address]", form).val());
                    }
                    if(response.affected) {
                        var affected = '';
                        jQuery.each(response.affected, function(key, val) {
                            affected += '<li>' + val + '</li>';
                        });
                        
                        $("#prequal-affected-items").html(affected);
                        $("#prequal-affected").show();
                        var overlay = $("#overlays").find("#change-address-overlay");
                        CLEAR.utils.OverlayController.redraw(overlay);
                        $("#prequal-affected input").formulate();
                    }
                } else {
                    sendOmnitureTracking('index:edit-results-overlay', 7, 'n|' + $("input[name=zip-code]", form).val() + '|' + $("input[name=street-address]", form).val());
                    sendOmnitureTracking('index:edit-results-overlay', 6, '');
                    if(response.suggestions) {
                        var suggestions = '<br />';
                        jQuery.each(response.suggestions, function(key, val) {
                            suggestions += '<p><label>';
                            suggestions += '<input type="radio" name="suggestion" value="' + val.address + '|' + val.zip + '" />';
                            suggestions += val.address + ', ' + val.city + ', ' + val.state + ' ' + val.zip;
                            suggestions += '</label></p>';
                        });
                        
                        $("#" + id + "-message").html(response.message);
                        $("#" + id + "-suggestions").html(suggestions);
                        $("input[name=suggestion]").click(function() {
                            var address = $(this).val().split("|");
                            useSuggestion(address[0], address[1]);
                        });
                        $("#" + id + "-suggestions input:radio").formulate();
                    } else {
                        //geocode failure
                        $("#" + id + "-message").html(response.message);
                    }
                }
            }
        });
    }
    
    return false;
}

function checkInsider(id) {
    var form = $("#" + id).parents('form:first');
    if(!$("input[name=clear-insider]", form).is(":checked")) {
        $("input[name=clear-insider]", form).attr("checked", "checked");
        // required for jquery 1.3.2 and IE 8.0 bug //
        document.getElementById("clear-insider").setAttribute("checked", "checked");
        //**//
        $("input[name=clear-insider]", form).formulate();
        
    }
    
}

function resetValues() {
    $("input[name=street-address]").val("");
    $("input[name=zip-code]").val("");
    $("input[name=email-address]").val("");
    $("input[name=clear-insider]").removeAttr("checked");
    $(".message, .suggestions").html("");
    $("#prequal-affected").hide();
}

function hideChangeAddress() {
    $("#prequal-affected").hide();
}

function useSuggestion(address, zip) {
    $("input[name=street-address]").val(address);
    $("input[name=zip-code]").val(zip);
}

function changeAddress() {
    var submitted = $("input[name=change-address-radio]:checked").val();
    if(submitted == 1) {
        var overlay = $("#overlays").find("#change-address-overlay");
        CLEAR.utils.OverlayController.hide(overlay);
        return false;
    } else if(submitted == 2) {
        //@TODO: force prequal change
        var address = { address: $("#change-address-address").val(), zip: $("#change-address-zip").val() };
        
        $.ajax({
            type: "POST",
            url: "/index/prequal/do/force",
            data: address,
            dataType: "json",
            success: function(response){
                // check the session timeout
                if (response.timeout) {
                    goToURL(response.redirect);
                    return false;
                }
                //if we need to switch div, show the appropriate one
                var overlay = $("#overlays").find("#" + response.div);
                if(overlay.length > 0) {
                    resetValues();
                    var overlay = $("#overlays").find("#" + response.div);
                    CLEAR.utils.OverlayController.show(overlay);
                    //$("#" + response.div + " .ui-formulate-button, input").formulate();
                }
            }
        });
        
        return false;
    }
    
    return false;
}

function editResults() {
    var submitted = $("input[name=edit-results-radio]:checked").val();
    if(submitted == 1) {
        var overlay = $("#overlays").find("#edit-results-overlay");
        CLEAR.utils.OverlayController.hide(overlay);
        return false;
    } else if(submitted == 0) {
        return true;
    }
    
    return false;
}
/* END PREQUAL OVERLAY FUNCTIONS */

function changeCustomerType(customer_type) {
    var mandatory = document.getElementById('business_name_option');
    var DOB = document.getElementById('dob_field');
    var business = document.getElementById('business_plan');
    var business_confirm = document.getElementById('business_plan_confirm');
    var credit_ssn  =   document.getElementById('credit_check_ssn');
    var credit_confirm  =   document.getElementById('credit_check_confirm');    
    
    if (customer_type == '2') {   // business customer
        mandatory.style.display = '';
        if(DOB) DOB.style.display = 'none';
        if(business) business.innerHTML = "* Tax ID";
        if(business_confirm) business_confirm.innerHTML = "* Tax ID Confirm";
        if(credit_ssn) credit_ssn.maxLength = 9;
        if(credit_confirm) credit_confirm.maxLength = 9;
    } else {
        mandatory.style.display = 'none';
        if(DOB) DOB.style.display = '';
        $("#credit_check_dob_month").formulate();
        $("#credit_check_dob_day").formulate();
        $("#credit_check_dob_year").formulate();
        if(business) business.innerHTML = "* Social Security Number:";
        if(business_confirm) business_confirm.innerHTML = "* Social Security Number Confirm:";
        if(credit_ssn) credit_ssn.maxLength = 4;
        if(credit_confirm) credit_confirm.maxLength = 4;
    }
}

function useBillingAsShipping(is_checked) {
    var shipping = new Array();
    shipping[0] = document.getElementById('shipping_address_1');
    shipping[1] = document.getElementById('shipping_address_2');
    shipping[2] = document.getElementById('shipping_city');
    shipping[3] = document.getElementById('shipping_state');
    shipping[4] = document.getElementById('shipping_zipcode');
    if (is_checked == true) {
        shipping[0].value = document.getElementById('billing_address_1').value;
        shipping[1].value = document.getElementById('billing_address_2').value;
        shipping[2].value = document.getElementById('billing_city').value;
        document.getElementById('shipping_state').options[document.getElementById('billing_state').selectedIndex].selected = true;
        $("#shipping_state").change();
        shipping[4].value = document.getElementById('billing_zipcode').value;
    } else {
        for (var i=0; i<shipping.length; i++) {
            shipping[i].value = '';
        }
        document.getElementById('shipping_state').options[0].selected = true;
        $("#shipping_state").change();
    }
   
}
$("#same_shipping_address").click(function(){
  
  if(!$("#same_shipping_address").attr('checked'))
    useBillingAsShipping(1);
  else
    useBillingAsShipping(0);
  
});

function changeShippingAddress() {
    document.getElementById('shipping_address_1').readOnly = false;
    document.getElementById('shipping_address_2').readOnly = false;
    document.getElementById('shipping_city').readOnly = false;
    document.getElementById('shipping_state').readOnly = false;
    document.getElementById('shipping_zipcode').readOnly = false;
}

function shippingAddressSuggestion(suggestion) {
    
      var address = suggestion.split('|');
      document.customer_info.shipping_address_1.value = address[0];
      document.customer_info.shipping_address_2.value = '';
      document.customer_info.shipping_city.value = address[1];
      document.customer_info.shipping_zipcode.value = address[3];
      $("#shipping_state").val(address[2]);
      $("#shipping_state").change();
}

$("input[name=suggestion_data]").click(function(){
    shippingAddressSuggestion($(this).val());
});

function setAutoprovisionOption(checked) {
    var set_autoprovision = document.getElementById('set_autoprovision');
    var autoprovision_option = document.getElementById('autoprovision_option');
    var email = document.getElementById('email_address');
    var confirm_email = document.getElementById('confirm_email_address');

    if (checked) {
        var account_name = document.getElementById('account_name').value;
        if (account_name) {
            autoprovision_option.style.display = '';
            email.value = confirm_email.value = account_name + "@clear.com";
            email.readOnly = confirm_email.readOnly = true;
            $("#set_autoprovision_error").html("");
        } else {
            $("#set_autoprovision").removeAttr("checked");
            $("#set_autoprovision").formulate();
            $("#set_autoprovision_error").css('color', '#ff0000');
            $("#set_autoprovision_error").html("  Please enter Clear Username first.");
        }
    } else {
        autoprovision_option.style.display = 'none';
        email.value = confirm_email.value = '';
        email.readOnly = confirm_email.readOnly = false;
    }
}

function showUseExistingSection(select) {
     if (select == 1) {
         document.getElementById("existing_phone_section").style.display = "";
         document.getElementById('existing_phone_section_authorization').style.display = "";
         document.getElementById("existing_phone_number").focus();
         document.getElementById("is_wireless").checked = false;
         $("#existing_phone_number").formulate();
         $("#carrier").formulate();
         $("#billing_phone_number").formulate();
         if ($("#is_wireless")) {
            $("#is_wireless").formulate();
         }
         $("#authorization_name").formulate();
     } else {
         document.getElementById("existing_phone_section").style.display = "none";
         document.getElementById('existing_phone_section_iswireless').style.display = "none";
         document.getElementById('existing_phone_section_authorization').style.display = "none";
     }
}

function toggle_wireless_fields(isChecked) {
    var is_wireless = document.getElementById('is_wireless');
    var existing_phone_section_iswireless = document.getElementById('existing_phone_section_iswireless');
    if (!isChecked) {
        existing_phone_section_iswireless.style.display = '';
        $("#wireless_acct_num").formulate();
        $("#wireless_cust_ssn").formulate();
    } else {
        existing_phone_section_iswireless.style.display = 'none';
    }
}

function changeContractTerm(element, filter_str, page_path) {
    var radios = $("input[name=" + $(element).attr("name") + "]");
    showBusyOverlay();
    
    $.ajax({
        type: "POST",
        url: "/shop/services/change-contract-term",
        dataType: "json",
        data: { contract_term_id: $(element).val(), filter: filter_str },
        success: function(response) {
            hideBusyOverlay();
            // check the session timeout
            if (response.timeout) {
                goToURL(response.redirect);
                return false;
            }
            if (response.success) {
                //submit page load event and reset tracking plan variables
                var tracking_js = refreshPlansArray(page_path, response.product_info, response.package_ids, response.voip_product_info);
                
                //load the data into the plans div
                $("#plans").html(response.html + tracking_js);
                
                //bind the click ajax events to newly shown buttons
                ajaxReady();
                
                //bind the click ajax event for newly shown buttons - omniture
                refreshPlansButton();

                //formulate the buttons
                $("input[name=add-plan-to-cart]").formulate();
                $("input:checkbox").formulate();
            } else {
                $("#generic-overlay-heading").html('Wait!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();
            }
        }
    });

    return false;
}

function submitDevice(id, own_gear, mac) {
    if(!own_gear) {
        var purchase_type_id = $("input[name='" + id + "']:checked").val();
        if(!purchase_type_id) {
            $("#generic-overlay-heading").html('Wait!');
            $("#generic-overlay-message").html('Please select the purchase option for the device.');
            $("#generic-overlay-link").click();
            return false;
        }
        device_data = { device_id: id, purchase_type: purchase_type_id };
    } else {
        var purchase_type_id = 3;
        device_data = { device_id: id, purchase_type: purchase_type_id, mac: mac };
        if ($("#sku").val()) {
            sendOmnitureTracking('devices:mac-id-validation', 1, ';' + id + ':' + $("#sku").html() + checkPurchaseType(purchase_type_id));
        } else {
            sendOmnitureTracking('devices:mac-id-validation', 1, ';' + id + ':' + $("select[name=device] option:selected").html() + checkPurchaseType(purchase_type_id));
        }
    }
    
    $.post("/shop/devices/add", device_data,
        function(data){
            // check the session timeout
            if (data.timeout) {
                goToURL(data.redirect);
                return false;
            }
            if(data.success) {
                goToURL(data.redirect);
                $("#cart_widget").load("/ajax/cart", function() {
                    $("#view-cart-button").formulate();
                });
            } else {
                if(data.devices_exist) {
                    //show the plan exists overlay
                    $("#generic-overlay-heading").html('Wait!');
                    $("#generic-overlay-message").html('In order to select the new Device please remove your existing selection from the Cart first.');
                    $("#generic-overlay-link").click();
                } else {
                    //show the device incompatible overlay
                    $("#generic-overlay-heading").html('Oops!');
                    $("#generic-overlay-message").html('This device option is not available with the service plan in your Cart. Please select another device option, or remove your service plan from the Cart to use this device option.');
                    $("#generic-overlay-link").click();
                }
            }
        }, "json"
    );
    
    return false;
}

function getDevices() {
    //remove previous response (if any)
    $("#remove-devices-message").html('');
    
    //now get the list of the devices from the controller
    $.ajax({
        type: "POST",
        url: "/shop/devices/get-devices-in-cart",
        dataType: "json",
        data: "",
        success: function(response){
            // check the session timeout
            if (response.timeout) {
                goToURL(response.redirect);
                return false;
            }
            
            var content = '<form>';
            var number = 0;
            jQuery.each(response.devices, function(key, val) {
                number++;
            });
            
            if(number > 1 || response.qty > 1) {
                jQuery.each(response.devices, function(key, val) {
                    content += '<p><label for="' + key + '"><input id="' + key + '" type="radio" name="remove-device" onclick="return false;" value="' + key + '" />' + val + '</label></p>';
                    if(response.qty > 1) {
                        content += '<p><label for="' + key + '"><input id="' + key + '" type="radio" name="remove-device" onclick="return false;" value="' + key + '" />' + val + '</label></p>';
                    }
                });
                
                content += '<p><label for="all"><input id="all" type="radio" name="remove-device" onclick="return false;" value="" />Remove all Devices</label></p>';
            } else {
                jQuery.each(response.devices, function(key, val) {
                    content += '<p><label for="' + key + '"><input id="' + key + '" type="radio" checked="checked" name="remove-device" onclick="return false;" value="' + key + '" />' + val + '</label></p>';
                });
            }
            content += '</form>';
            $("#remove-devices-response").html(content);
            $("input[name=remove-device]").formulate();
        }
    });
}

function validateMac(sku, device_name) {
    //send omniture tracking
    sendOmnitureTracking('devices:mac-id-validation', '');

    //@TODO: load devices from the web catalog
    if(!sku) {
        $.post("/shop/devices/get-devices", false,
            function(data) {
                // check the session timeout
                if (data.timeout) {
                    goToUrl(data.redirect);
                    return false;
                }
                if(data.success) {
                    var devices = '<option selected="selected" value="">Device Name</option>';
                    jQuery.each(data.devices, function(key, val) {
                        devices += '<option value="' + val.device_id + '">' + val.device_name + '</option>';
                    });
                    $("#device").html(devices);
                    $("#device select").formulate();
                    
                    $("#mac-address-identify").show();
                    
                    $("#sku").val(sku);
                    //var overlay = $("#overlays").find("#mac-address-overlay");
                    //CLEAR.utils.OverlayController.show(overlay);
                    $("#mac-address-overlay-link").click();
        
                } else if(data.div) {
                    var overlay = $("#overlays").find("#" + data.div);
                    CLEAR.utils.OverlayController.show(overlay);
                    return false;
                }
            }, "json"
        );
    } else {
        $("#sku").val(sku);
        $("#sku").html(device_name);
        
        //var overlay = $("#overlays").find("#mac-address-overlay");
        //CLEAR.utils.OverlayController.show(overlay);
        $("#mac-address-overlay-link").click();
    }
}

function submitOwnGear() {
    //remove previous response
    $("#enter-mac-response").html("");
    
    //if called with known device, SKU will be set to this field; if called from inside the cart device is unknown so we will get the SKU from the drop-down boxes
    var sku = $("#sku").val();
    
    var error = false;
    var message = '';
    
    if(!sku) {
        //get the data
        var device_data = { sku: $("select[name=device] option:selected").val(), mac: $("#mac-address").val() };
               
        //validate input
        if(!device_data.sku) {
            error = true;
            message += "<br />Please select the Name of your Device.";
        }
    } else {
        var device_data = { sku: sku, mac: $("#mac-address").val() };
    }
    
    if(!device_data.mac || !device_data.mac.match(/[0-9a-fA-F]{12}/)) {
        error = true;
        message += "<br />Please enter the 12 hex digit MAC Address.";
    }
    
    //show error message (if any)
    $("#enter-mac-response").html(message);

    //if no errors procced with mac validation
    if(!error) {
        $.post("/shop/devices/mac-validation", device_data,
            function(data){
                // check the session timeout
                if (data.timeout) {
                    goToURL(data.redirect);
                    return false;
                }
                if(data.success) {
                    //validation has passed, let's add the device to the cart
                    submitDevice(data.device.equipment_id, true, device_data.mac);
                } else {
                    if(data.devices_exist) {
                        //show the plan exists overlay
                        $("#generic-overlay-heading").html('Wait!');
                        $("#generic-overlay-message").html('In order to select the new Device please remove your existing selection from the Cart first.');
                        $("#generic-overlay-link").click();
                    } else {
                        //show the device incompatible overlay
                        $("#enter-mac-response").html(data.message);
                    }
                }
            }, "json"
        );
    }
    
    return false;
}

function removePlan() {
    var page = location.pathname.split('/');
    $.post('/shop/services/remove', true,
        function(data){
            // check the session timeout
            if (data.timeout) {
                goToURL(data.redirect);
                return false;
            }
            if(data.success) {
                $("#generic-overlay-heading").html('Great!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();

                // redirect when clicking the close button
                $("#generic-overlay-close").click(function() {
                    if (page[page.length-1] == 'cart-details') {
                        //reload the current page
                        goToURL(window.location);
                    } else {
                        goToURL(data.redirect);
                        $("#cart_widget").load("/ajax/cart", function() {
                            $("#view-cart-button").formulate();
                        });
                    }
                });
            } else {
                $("#generic-overlay-heading").html('Oops!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();
            }
        }, "json"
    );
    
    return false;
}

function removeDevice() {
    var id = $('input[name=remove-device]:checked').val();
    if(typeof(id) == 'undefined') {
        $("#remove-devices-message").html('Please select the Gear you would like removed.');
        return false;
    } else if(id) {
        path = '/shop/devices/remove/id/' + id;
    } else {
        path = '/shop/devices/remove';
    }
    var page = location.pathname.split('/');
    $.post(path, true,
        function(data){
            // check the session timeout
            if (data.timeout) {
                goToURL(data.redirect);
                return false;
            }
            if(data.success) {
                $("#generic-overlay-heading").html('Great!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();

                // redirect when clicking the close button
                $("#generic-overlay-close").click(function() {
                    if (page[page.length-1] == 'cart-details') {
                        location.reload();
                    } else {
                        goToURL(data.redirect);
                        $("#cart_widget").load("/ajax/cart", function() {
                            $("#view-cart-button").formulate();
                        });
                    }
                });
            } else {
                $("#generic-overlay-heading").html('Wait!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();
            }
        }, "json"
    );
    
    return false;
}

function removeFeatureOverlay(id, name) {
    $('#remove-features-and-accessories-id').val(id);
    $('#remove-features-and-accessories-name').val(name);
    $('#remove-features-and-accessories-title').html('Click here to remove your '+name);
}

// to remove feature or accessory from the cart details page (through the "remove" link)
function removeFeature() {
    var data = { feature_id: $("#remove-features-and-accessories-id").val()};
    var page = location.pathname.split("/");
    $.post("/shop/devices/removefeature", data,
        function(data){
            if(data.success) {
                $("#generic-overlay-heading").html('Great!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();
                $("#generic-overlay-close").click(function() {
                    location.reload();
                });
            } else {
                $("#generic-overlay-heading").html('Oops!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();
            }
        }, "json"
    );
}

// to add/remove feature or accessory from the overlay
function submitFeature(id, action, type) {
    var add;
    type = (type!=undefined)? type : '';
    
    if (action == 'add' || action == 'add_cart_details' || action == false) {
       add = 1; // accessory page
    }
    var page = location.pathname.split('/');
    if (add) {
        $("input:[name='chkBoxFeatures']").disable();
        $("#close-view-features-and-accessories-overlay").hide();
        $("#view-features-and-accessories-error").html("Adding...");
        if (action == 'add_cart_details') {
            showBusyOverlay();
        }
        $.post("/shop/devices/addfeature", { feature_id: id, type: type},
            function(data){
                $("input:[name='chkBoxFeatures']").enable();
                $("#close-view-features-and-accessories-overlay").show();
                // check the session timeout
                if (data.timeout) {
                    goToURL(data.redirect);
                    return false;
                }
                $("#view-features-and-accessories-error").html(data.message);
                if(data.success) {
                    // send omniture tracking
                    if ($("#alacarte-display-name-"+id).val() != undefined) {
                        sendOmnitureTracking('devices:alacartes', 1, ';' + id + ':' + $("#alacarte-display-name-"+id).val());
                    } else if ($("#upsell_"+id).val() != undefined) {
                        sendOmnitureTracking('devices:cart-details', 1, ';' + id + ':' + $("#upsell_"+id).val());
                    }
                    if (action == 'add_cart_details') {
                        hideBusyOverlay();
                        location.reload();
                        return false;
                    } else if (page[page.length-1] == 'confirmation' || page[page.length-1] == 'cart-details') {
                        $("#view-features-and-accessories-overlay-close").click(function() {
                            location.reload();
                        });
                    } else {
                        $("#cart_widget").load("/ajax/cart", function() {
                            $("#view-cart-button").formulate();
                        });
                        if (page[page.length-1] == 'order') {
                            $.post("/shop/order/get-balance", '',
                                function(data) {
                                    if (data.success) {
                                        $("#balance").html(data.balance);
                                    }
                                }, "json"
                            );
                        }
                    }
                } else {
                    if (action == 'add') {
                        $("#add-features-and-accessories-title").html(data.title);
                        $("#add-features-and-accessories-response").html(data.message);
                        var overlay = $("#overlays").find("#add-features-and-accessories-overlay");
                        CLEAR.utils.OverlayController.redraw(overlay);
                        CLEAR.utils.OverlayController.show(overlay);
                    }
                    $("#edit-" + id).attr("checked", false);
                    $("#edit-" + id).formulate();
                    if (action == 'add_cart_details') {
                        hideBusyOverlay();
                    }
                }
            }, "json"
        );
    } else {
        $("input:[name='chkBoxFeatures']").disable();
        $("#close-view-features-and-accessories-overlay").hide();
        $("#view-features-and-accessories-error").html("Removing...");
        $.post("/shop/devices/removefeature", { feature_id: id, type: type},
            function(data){
                $("input:[name='chkBoxFeatures']").enable();
                $("#close-view-features-and-accessories-overlay").show();
                // check the session timeout
                if (data.timeout) {
                    goToURL(data.redirect);
                    return false;
                }
                $("#view-features-and-accessories-error").html(data.message);
                if(data.success) {
                    // send omniture tracking
                    if ($("#alacarte-display-name-"+id).val() != undefined) {
                        sendOmnitureTracking('devices:alacartes', 2, ';' + id + ':' + $("#alacarte-display-name-"+id).val());
                    }
                    if (page[page.length-1] == 'confirmation' || page[page.length-1] == 'cart-details') {
                        $("#view-features-and-accessories-overlay-close").click(function() {
                            location.reload();
                        });
                    } else {
                        $("#cart_widget").load("/ajax/cart", function() {
                            $("#view-cart-button").formulate();
                        });
                        if (page[page.length-1] == 'order') {
                            $.post("/shop/order/get-balance", '',
                                function(data) {
                                    if (data.success) {
                                        $("#balance").html(data.balance);
                                    }
                                }, "json"
                            );
                        }
                    }
                } else {
                    $("#edit-" + id).attr("checked", false);
                    $("#edit-" + id).formulate();
                }
            }, "json"
        );
    }
    
    return false;
}

function viewAlacarte() {
    $("#view-features-and-accessories-error").html("");
    $("#view-features-and-accessories-response").html("Loading...");
    $.post("/shop/devices/alacartes", true,
        function(data){
            // check the session timeout
            if (data.timeout) {
                goToURL(data.redirect);
                return false;
            }
            $("#view-features-and-accessories-response").html(data.message);
            if(data.success) {
                $("#add-features-and-accessories-form input").formulate();
                $("input[name='chkBoxFeatures']").bind("click", function(){
                    var id = $(this).attr("id").split('-');
                    return submitFeature($(this).val(), $(this).attr("checked"), id[2]);
                });
                // send omniture tracking
                sendOmnitureTracking('devices:alacartes', '', data.products);
            }
        }, "json"
    );
    
    return false;
}

function voipUpsell(checked) {
    if (checked) {
        var action = "/shop/order/add-voip-upsell";
    } else {
        var action = "/shop/order/remove-voip-upsell";
    }

    $.post(action, true,
        function(data){
            // check the session timeout
            if (data.timeout) {
                goToURL(data.redirect);
                return false;
            }
            if(data.success) {
                location.reload();
            } else {
                $("#generic-overlay-heading").html('Wait!');
                $("#generic-overlay-message").html(data.message);
                $("#generic-overlay-link").click();
            }
        }, "json"
    );

    return false;
}

function removeVoip() {
}

CLEAR.queue(function() {
    $(document).ready(function() {
        ajaxReady();
        $(".prequal-link").click(function(event) {
            
            var planid = $(this).attr("id");    //To capture the plan id to populate the compare plan overlay
            if (planid) { 
                if (document.getElementById('plannumber')) {
                    document.getElementById('plannumber').value = planid;
                }
            }    
            event.preventDefault();
            openPrequal($(this).attr("href"));
            return false;
        });
        
        //added the logic for IE so the prequal forms can be submitted by clicking the ENTER key
        $("form[name=prequal-form] input, form[name=mac-address-form] input").live('keypress', function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                $(this).parents('form').find('input:submit').click();
                return false;
            } else {
                return true;
            }
        });
    });
});

function ajaxReady() {
    //disable buttons during AJAX call to prevent multiple submission
    $(document).bind("ajaxStart", function(){
        $("input:submit").disable();
        //$("input:submit").formulate();
    }).bind("ajaxStop", function(){
        $("input:submit").enable();
        //$("input:submit").formulate();
    });
        

    $("input[name='add-plan-to-cart']").click(function(e){
        e.preventDefault();
        //CLEAR.utils.SpinnerController.show($(this));

        var data;
        if ($("#add_voip_" + $(this).attr("id")).attr('checked')) {
            data = { offer_id: $(this).attr("id"), voip: 1 }; 
        } else {
            data = { offer_id: $(this).attr("id") }; 
        }
        $.ajax({
            type: "POST",
            url: "/shop/services/add",
            dataType: "json",
            data: data,
            success: function(response){
                //CLEAR.utils.SpinnerController.hide();
                // check the session timeout
                if (response.timeout) {
                    goToURL(response.redirect);
                    return false;
                }
                if(response.success) {
                    // send omniture tracking
                    if (response.product_info != undefined) {
                        sendOmnitureTracking(page_path, 1, response.product_info);
                    }
                    
                    goToURL(response.redirect);
                    $("#cart_widget").load("/ajax/cart", function() {
                        $("#view-cart-button").formulate();
                    });
                } else {
                    if(response.plan_exists) {
                    //show the plan exists overlay
                    $("#generic-overlay-heading").html('Wait!');
                    $("#generic-overlay-message").html('In order to select the new Service please remove your existing selection from the Cart first.');
                    $("#generic-overlay-link").click();
                } else {
                    //show the device incompatible overlay
                    $("#generic-overlay-heading").html('Oops!');
                    $("#generic-overlay-message").html('This service plan option is not available with the device in your Cart. Please select another service plan option, or remove your device from the Cart to use this service plan option.');
                    $("#generic-overlay-link").click();
                }
                }
            }
        });
        
        return false;
    });

    $("input[name='add-device-to-cart']").bind("click", function(){
        return submitDevice($(this).attr("id"));
    });

    $("input[name='add-accessory-to-cart']").bind("click", function(){
        return submitFeature($(this).attr("id"), 'add');
    });

    $("input[name='add_clearspot']").bind("click", function(){
        return submitFeature($(this).val(), 'add_cart_details');
    });

    $("input[name='add_voip']").bind("click", function(){
        return voipUpsell(!$(this).attr("checked"));
    });
}

function goToURL(href) {
    window.location = href;
    showBusyOverlay();              
}

function showBusyOverlay() {
    var overlay = $("#overlays").find("#busy-overlay");
    CLEAR.utils.OverlayController.show(overlay);
}

function hideBusyOverlay() {
    var overlay = $("#overlays").find("#busy-overlay");
    CLEAR.utils.OverlayController.hide(overlay);  
}

function comparePlans(plantype) {
    $("#compare-plans-clear-overlay-error").html("");
    $("#compare-plans-clear-overlay-response").html("Loading...");
    $.post("/services/compare", {plan : plantype},
        function(data){
            // check the session timeout
            if (data.timeout) {
                goToURL(data.redirect);
                return false;
            }
            $("#compare-plans-clear-overlay-response").html(data.message);
            if(data.success) {
                    $("#compare-plans-clear-overlay-response").html(data.compares);
            }
        }, "json"
    );
    
    return false;
}




