﻿$(document).ready(function () {
    //Offer code
    $("#offerCode").keyup(function () {
        if ($(this).val().length > 3) {
            $.ajax({
                url: 'ajax.asp',
                data: 'feed=promocode&pc=' + $(this).val(),
                success: function (data) {
                    if (data.toString().toLowerCase() == "true") {
                        $("#offerCode").addClass("validCode");
                    }
                    else {
                        $("#offerCode").removeClass("validCode");
                    }
                }
            });
        }
    });

    $("a.basketRemove").live("click", function (e) {
        e.preventDefault();
        var newTotal
        newTotal = $("#basketValue").text().replace(/[^\d\.\-\ ]/g, '');
        newTotal = newTotal - $(this).closest("li").find("span").text().replace(/[^\d\.\-\ ]/g, '');
        $.get($(this).attr("href"));
        $(this).closest("li").slideUp("fast", function () {
            $(this).remove();
            if ($("#basketContainer ul li").length == 0) { $("#basketHeading").html("<p><strong>Your basket is currently empty.</strong></p>"); $("#btnCheckout").hide(); }
            $("#basketValue").text(newTotal.toFixed(2));
        });
    });

    $("#gradingNo,  #gradingYes").change(function () {
        if ($(this).val() == "Yes") {
            if ($("#frmGrading").is(":hidden")) { $("#frmGrading").slideDown(); }
            if ($("#frmSkipGrading").is(":visible")) { $("#frmSkipGrading").hide(); }
        }
        else {
            if ($("#frmGrading").is(":visible")) { $("#frmGrading").slideUp(); }
            if ($("#frmSkipGrading").is(":hidden")) { $("#frmSkipGrading").show(); }
            $("#btnSkipGrading").attr("src", "../graphics/pageimages/buttons/button_sellnow.gif").removeAttr("disabled").focus();
        }
    });

    $('#frmGrading').submit(function (event) {
        var hasErrors = false;

        $("#gradingQuestions input.tbReq, #gradingQuestions select").each(function () {
            if ($(this).val() == "") {
                alert('Please supply a response for the question: ' + $(this).closest("tr").find("td.gradingQuestion").text());
                hasErrors = true;
                event.preventDefault();
                $(this).focus();
                return false;
            }
        });

        if (hasErrors) { return false; }

        var radio_groups = {};
        $("#gradingQuestions input:radio").each(function () {
            radio_groups[this.name] = true;
        })

        for (group in radio_groups) {
            if_checked = !!$("#gradingQuestions input:radio[name=" + group + "]:checked").length
            if (!if_checked) {
                $("#gradingQuestions input:radio[name=" + group + "]").focus();
                alert('Please select a response for the question: ' + $("#gradingQuestions input:radio[name=" + group + "]").closest("tr").find("td.gradingQuestion").text());
                hasErrors = true;
                event.preventDefault();
                return false;
            }
        }
        if (hasErrors) { return false; }
        return true;
    });


    $("#gradingQuestions select, #gradingQuestions input:radio, #gradingQuestions input:checkbox").change(function () {
        calculateValue();
    });

    $("#gradingQuestions input.numericTb").keypress(function (e) {
        var key = e.charCode || e.keyCode || 0;
        var keychar = String.fromCharCode(key);
        if (((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode == 0) /* backspace, end, begin, top, bottom, right, left, del, tab */
                || (key >= 48 && key <= 57)) { /* 0-9 */
            return;
        } else {
            e.preventDefault();
        }
    });

    $('#gradingQuestions .helpIcon').each(function () {
        $(this).qtip({
            content: $(this).next('.gradingHelpText').html(),
            style: { name: 'blue', tip: true, background: '#FFF39F', color: '#005896', 'font-size': 12, 'font-family': 'Verdana, Arial, Helvetica, sans-serif', border: {
                width: 3,
                radius: 3,
                color: '#FFE000'
            }
            },
            show: 'mouseover',
            position: {
                corner: {
                    target: 'rightMiddle',
                    tooltip: 'leftMiddle'
                }
            }
        });
    });

    $("#phoneNameSearch, #rightbarfield").autocomplete({
        source: "ajax.asp?feed=autosuggest",
        minLength: 3,
        select: function (event, ui) {
            window.location = '/phoneSelected.asp?phoneID=' + ui.item.id;
        }

    });

    $("#phoneNameSearch").focus(function () {
        if ($(this).val() == "Enter phone model e.g. iPhone") {
            $(this).val("")
        }
    });

    $("a.hplViewOrder").click(function (event) {
        event.preventDefault();
        $(this).parents("tr").next(".orderDetailRow").toggle();
    });


    if ($("#ddlManufacturer, #ddlManufacturerRb").length) {
        loadDDLManufacturer(1);
    }

    $("#ddlManufacturer, #ddlManufacturerRb").change(function () {
        loadDDLModel(1, $(this).val());
    });

    $("#ddlModel, #ddlModelRb").change(function () {
        if ($(this).val() == "all") {
            window.location.href = "phoneModels.asp?c=" + $("#ddlManufacturer, #ddlManufacturerRb").val() + "&did=1";
            return false;
        }
        if ($(this).val() != "") {
            window.location.href = "phoneSelected.asp?phoneID=" + $(this).val();
            return false;
        }
    });
});

function loadDDLManufacturer(DeviceType) {
    $("#ddlManufacturer, #ddlManufacturerRb").empty();
    $.ajax({
        url: 'ajax.asp',
        data: 'feed=manufacturer&deviceType=' + DeviceType,
        success: function (data) {
            $("#ddlManufacturer, #ddlManufacturerRb").append(data);
        }
    });
}

function loadDDLModel(DeviceType, Manufacturer) {
    $("#ddlModel, #ddlModelRb").empty();
    $.ajax({
        url: 'ajax.asp',
        data: 'feed=model&deviceType=' + DeviceType + '&manufacturer=' + Manufacturer,
        success: function (data) {
            $("#ddlModel, #ddlModelRb").append(data);
            $("#ddlModel, #ddlModelRb").focus();
        }
    });
}
 function calculateValue() {

    var phoneValue = parseFloat($("#itemValue").val().replace(/[^\d\.-]/g, ''));
    var gradedValue = phoneValue;
    var arrGradings = new Array();
    var gradingPercentage = 0;

    $('#gradingQuestions input:checked, #gradingQuestions option:selected').each(function () {
        if ($(this).attr("rr") != "" && isNaN($(this).attr("rr")) == false) {
            arrGradings.push(parseInt($(this).attr("rr")));
        }
    });

    arrGradings.sort(sortDesc);
    if (arrGradings.length > 0) {
        gradingPercentage = arrGradings[0];
    }

    gradedValue = (gradingPercentage / 100) * phoneValue;
    gradedValue = phoneValue - gradedValue;
    if (gradedValue < 0) { gradedValue = 0; }
    $("#gradedValue").text(gradedValue.toFixed(2));
}

function sortDesc(a, b) { return (b - a); } 
