﻿var COLOR_INDEX = 0;
var SIZE_INDEX = 1;
var CABIN_INDEX = 2;
var SORT_INDEX = 3;
var haveColors;
var haveSizes;
var haveCabins;
var recipients;
function AjaxFailed(result) {
    if (result.d.ErrorId == -10) { // user correctable
        alert(result.d.ErrorMsg);
    }
    else {
        alert("Oops! An error has occured. Please try your request again. " + result.d.ErrorMsg);
    }
    document.location = document.location;
};
$(document).ready(function() {
    // jQuery Validate
    $("#aspnetForm").validate({
        errorClass: "msproductformerror"
    });
    // inventory
    haveColors = haveInventoryAttribute(COLOR_INDEX);
    haveSizes = haveInventoryAttribute(SIZE_INDEX);
    haveCabins = haveInventoryAttribute(CABIN_INDEX);
    if (haveColors) {
        showColors();
    }
    if (haveSizes) {
        showSizes();
    }
    if (haveCabins) {
        showCabins();
    }
    if (inStock) {
        $('#lblStockStatus').text('In Stock');
        $('#lblStockStatus').addClass('inStock');
        $('#AddToCart').show();
    }
    else {
        $('#lblStockStatus').text('Out of Stock');
        $('#lblStockStatus').addClass('outOfStock');
        $('#DivQty').hide();
        $('#AddToCart').hide();
    }
    $('#loadingInventory').hide();
});
function haveInventoryAttribute(index) {
    if ((inventory == undefined) || (inventory == null))
    { return false; }
    for (var i = 0; i < inventory.length; i++) {
        if (inventory[i][index].length > 0) {
            return true;
        }
    }
    return false;
};
function showColors() {
    if (!haveColors) { return; }
    var colorToAdd;
    var colors = [];
    var colorCount = 0;
    for (var row in inventory.sort(sortColors)) {
        // no duplicates
        if (colorToAdd != inventory[row][COLOR_INDEX]) {
            colorToAdd = inventory[row][COLOR_INDEX];
            colors[colorCount++] = colorToAdd;
        }
    }
    if (colorCount > 0) {
        if (colorCount < 4) {
            // show as radio
            $('#lblColor').html('<label for="color">Colors:</label>');
            var radio = '';
            for (var colorIndex = 0; colorIndex < colorCount; colorIndex++)
            {
                radio += '<input type="radio" id="colorAttrib';
                radio += colors[colorIndex];
                radio += '" name="color" value="';
                radio += colors[colorIndex];
                radio += '">';
                radio += colors[colorIndex];
                radio += '</input>';
            }
            radio += '<br /><br />';
            $('#colorList').html(radio);
            // default is the first
            $('#colorList').children(' :first').attr('checked', true);
            // watch for changes
            $('#colorList :radio').click(showSizes);
        }
        else {
            // show as drop down
            $('#lblColor').html('<label for="color">Colors:</label>');
            var combo = '<select id="color" name="color">';
            for (var colorIndex = 0; colorIndex < colorCount; colorIndex++) {
                combo += '<option value="';
                combo += colors[colorIndex];
                combo += '">';
                combo += colors[colorIndex];
                combo += '</option>';
            }
            combo += '</select><br /><br />';
            $('#colorList').html(combo);
            $('#color').change(showSizes);
        }
    }
    else {
        $('#attribColor').hide();
    }
};
function showSizes() {
    if (!haveSizes) { return; }
    var sizeToAdd;
    var sizes = [];
    var sizeCount = 0;
    for (var row in inventory.sort(sortSizes)) {
        if (!haveColors) {
            // add all unique sizes
            // no duplicates
            if (sizeToAdd != inventory[row][SIZE_INDEX]) {
                sizeToAdd = inventory[row][SIZE_INDEX];
                sizes[sizeCount++] = sizeToAdd;
            }
        }
        else {
            // we are only looking for sizes for a certain color
            // check for the drop down value
            var currentColor = $('#color').val();
            // if none, try the radiobox
            if (currentColor == undefined) {
                currentColor = $("input[name='color']:checked").val();
            }
            if (inventory[row][COLOR_INDEX] == currentColor) {
                if (sizeToAdd != inventory[row][SIZE_INDEX]) {
                    sizeToAdd = inventory[row][SIZE_INDEX];
                    sizes[sizeCount++] = sizeToAdd;
                }
            }
        }
    }
    if (sizeCount > 0) {
        if (sizeCount < 4) {
            // show as radio
            $('#lblSize').html('<label for="size">Sizes:</label>');
            var radio = '';
            for (var sizeIndex = 0; sizeIndex < sizeCount; sizeIndex++) {
                radio += '<input type="radio" id="sizeAttrib';
                radio += sizes[sizeIndex];
                radio += '" name="size" value="';
                radio += sizes[sizeIndex];
                radio += '">';
                radio += sizes[sizeIndex];
                radio += '</input>';
            }
            radio += '<br /><br />';
            $('#sizeList').html(radio);
            // default is the first
            $('#sizeList').children(' :first').attr('checked', true);
            // watch for changes
            $('#sizeList :radio').click(showCabins);
        }
        else {
            // show as drop down
            $('#lblSize').html('<label for="size">Sizes:</label>');
            var combo = '<select id="size" name="size">';
            for (var sizeIndex = 0; sizeIndex < sizeCount; sizeIndex++) {
                combo += '<option value="';
                combo += sizes[sizeIndex];
                combo += '">';
                combo += sizes[sizeIndex];
                combo += '</option>';
            }
            combo += '</select><br /><br />';
            $('#sizeList').html(combo);
            $('#size').change(showCabins);
        }
    }
    else {
        $('#attribSize').hide();
    }
};
function showCabins() {
    if (!haveCabins) { return; }
    var cabinToAdd;
    var cabins = [];
    var cabinCount = 0;
    for (var row in inventory.sort(sortCabins)) {
        if ((haveColors) && (haveSizes)) {
            // we are only looking for cabins for a certain color
            // check for the drop down value
            var currentColor = $('#color').val();
            // if none, try the radiobox
            if (currentColor == undefined) {
                currentColor = $("input[name='color']:checked").val();
            }
            // we are only looking for cabins for a certain size
            // check for the drop down value
            var currentSize = $('#size').val();
            // if none, try the radiobox
            if (currentSize == undefined) {
                currentSize = $("input[name='size']:checked").val();
            }
            if ((inventory[row][COLOR_INDEX] == currentColor) && (inventory[row][SIZE_INDEX] == currentSize)) {
                if (cabinToAdd != inventory[row][CABIN_INDEX]) {
                    cabinToAdd = inventory[row][CABIN_INDEX];
                    cabins[cabinCount++] = cabinToAdd;
                }
            }   
        }
        else if (haveColors) {
            // we are only looking for cabins for a certain color
            // check for the drop down value
            var currentColor = $('#color').val();
            // if none, try the radiobox
            if (currentColor == undefined) {
                currentColor = $("input[name='color']:checked").val();
            }
            if (inventory[row][COLOR_INDEX] == currentColor) {
                if (cabinToAdd != inventory[row][CABIN_INDEX]) {
                    cabinToAdd = inventory[row][CABIN_INDEX];
                    cabins[cabinCount++] = cabinToAdd;
                }
            }
        }
        else if (haveSizes) {
            // we are only looking for cabins for a certain size
            // check for the drop down value
            var currentSize = $('#size').val();
            // if none, try the radiobox
            if (currentSize == undefined) {
                currentSize = $("input[name='size']:checked").val();
            }
            if (inventory[row][SIZE_INDEX] == currentSize) {
                if (cabinToAdd != inventory[row][CABIN_INDEX]) {
                    cabinToAdd = inventory[row][CABIN_INDEX];
                    cabins[cabinCount++] = cabinToAdd;
                }
            }
        }
        else {
            // add all unique cabins
            // no duplicates
            if (cabinToAdd != inventory[row][CABIN_INDEX]) {
                cabinToAdd = inventory[row][CABIN_INDEX];
                cabins[cabinCount++] = cabinToAdd;
            }
        }
    }
    if (cabinCount > 0) {
        if (cabinCount < 4) {
            // show as radio
            $('#lblCabin').html('<label for="cabin">Cabins:</label>');
            var radio = '';
            for (var cabinIndex = 0; cabinIndex < cabinCount; cabinIndex++) {
                radio += '<input type="radio" id="cabinAttrib';
                radio += cabins[cabinIndex];
                radio += '" name="cabin" value="';
                radio += cabins[cabinIndex];
                radio += '" />';
                radio += cabins[cabinIndex];
                radio += '</input>';
            }
            radio += '<br /><br />';
            $('#cabinList').html(radio);
            // default is the first
            $('#cabinList').children(' :first').attr('checked', true);
        }
        else {
            // show as drop down
            $('#lblCabin').html('<label for="cabin">Cabins:</label>');
            var combo = '<select id="cabin" name="cabin">';
            for (var cabinIndex = 0; cabinIndex < cabinCount; cabinIndex++) {
                combo += '<option value="';
                combo += cabins[cabinIndex];
                combo += '">';
                combo += cabins[cabinIndex];
                combo += '</option>';
            }
            combo += '</select><br /><br />';
            $('#cabinList').html(combo);
        }
    }
    else {
        $('#attribCabin').hide();
    }
};
function sortColors(a, b) {
    if (a[COLOR_INDEX] == b[COLOR_INDEX]) {
        return 0;
    }
    else if (a[COLOR_INDEX] > b[COLOR_INDEX]) {
        return 1;
    }
    else {
        return -1;
    }
}
function sortSizes(a, b) {
    if (a[SORT_INDEX] > b[SORT_INDEX])
        return 1;
    else
        return -1;
}
function sortCabins(a, b) {
    if (a[SORT_INDEX] > b[SORT_INDEX])
        return 1;
    else
        return -1;
}
// TermList for other camper/counselors
$(document).ready(function() {
    if (ShipOut == 0) {
        ValidateInCampAdd();
        // watch for term selection changes
        // refresh delivery days
        $('#TermList :radio').click(function() {
            GetDeliveryDates(Branch, $("input[name='rTerm']:checked").val());
        });
        // if logged in show recipient list
        if (account_id != null) {
            $.ajax({
                type: "POST",
                url: "productservice.asmx/Recipients",
                contentType: "application/json; charset=utf-8",
                data: "{ RequestId: '', account_id: '" + account_id + "', branch: '" + Branch + "' }",
                dataType: "json",
                success: ShowRecipients,
                error: AjaxFailed
            });
        }
        else {
            $('#DivCamperNameOther').hide();
            // select the first term in the list
            $('#TermList').find('input:first').attr('checked', true);
            GetDeliveryDates(Branch, $("input[name='rTerm']:checked").val());
            ValidateCamperNameAdd();
        }
    }
    else {
        ValidateShipOutAdd();
    }
});
function GetDeliveryDates(branch, term) {
    $('#DateList').html("Checking Dates for <br />" + term + ". <img alt='...' src='../images/ajax-loader.gif' /><br /><br />");
    $.ajax({
        type: "POST",
        url: "productservice.asmx/DeliveryDates",
        contentType: "application/json; charset=utf-8",
        data: "{ RequestId: '', branch: '" + branch + "', term: '" + term + "' }",
        dataType: "json",
        success: ShowDeliveryDates,
        error: AjaxFailed
    });
    $("#hTerm").val(term);
    $('#AddToCart').hide();
}
function ShowDeliveryDates(result) {
    if (result.d.ErrorId == 0) {
        var comboDDate;
        if (result.d.DeliveryDates.length > 0) {
            // show as drop down
            comboDDate = '<select id="DeliveryDate" name="DeliveryDate">';
            if ($('#ctl00_PageContent_lblProductHeading').text() == 'Cabin Bus Photo Card') {
                result.d.DeliveryDates.splice(0, (result.d.DeliveryDates.length - 1));
            }
            for (var dateIndex = 0; dateIndex < result.d.DeliveryDates.length; dateIndex++) {
                comboDDate += '<option value="';
                comboDDate += result.d.DeliveryDates[dateIndex].DateString;
                comboDDate += '">';
                comboDDate += result.d.DeliveryDates[dateIndex].DateDesc;
                comboDDate += '</option>';
            }
            comboDDate += '</select><br /><br />';
            $('#AddToCart').show();
        }
        else { // no delivery dates
            if (result.d.term != "undefined") {
                comboDDate = '<span class="error">Delivery has ended for ' + result.d.term + '.</span>';
            }
            else { // no term at all
                comboDDate = '<span class="error">Delivery has ended for the summer.</span>';
            }
        }
        $('#DateList').html(comboDDate);
    }
    else {
        alert("Oops! An error has occured. Please try your request again. " + result.d.ErrorMsg);
        document.location = document.location;
    }
}
function ShowRecipients(result) {
    if (result.d.ErrorId == 0) {
        recipients = result.d.Recipients;
        var ComboR = '<select id="camper_name" name="camper_name"><option value="other">Other Camper/Counselor</option>';
        for (var recIndex = 0; recIndex < recipients.length; recIndex++) {
            ComboR += '<option value="';
            ComboR += recipients[recIndex].person_id;
            ComboR += '"';
            if (recIndex == 0)
                ComboR += " selected ";
            ComboR += '>';
            ComboR += recipients[recIndex].name;
            ComboR += '</option>';
        }
        ComboR += '</select><br /><br />';
        $('#NameInput').html(ComboR);
        $('#camper_name').change(RecipientChanged);
        RecipientChanged();
    }
    else {
        alert("Oops! An error has occured. Please try your request again. " + result.d.ErrorMsg);
        document.location = document.location;
    }
}
function RecipientChanged() {
    var recipientId = $('#camper_name').val();
    if (recipientId == "other") {
        $('#TermInfo,#DivCamperNameOther').show();
        ValidateCamperNameOtherAdd();
        $('#TermList').find('input:first').attr('checked', true);
        GetDeliveryDates(Branch, $("input[name='rTerm']:checked").val());
    }
    else {
        $('#TermInfo,#DivCamperNameOther').hide();
        $("#camper_name_other").rules("remove");
        for (var recIndex = 0; recIndex < recipients.length; recIndex++) {
            if (recipients[recIndex].person_id == recipientId) {
                GetDeliveryDates(recipients[recIndex].branch, recipients[recIndex].term_branch);
            }
        }
    }
}
function ValidateInCampAdd() {
    $("#txtFrom").rules("add", {
        required: true,
        messages: {
        required: "Please enter a message or who the gift is from."
        }
    });
}
function ValidateCamperNameAdd() {
    $("#camper_name").rules("add", {
        required: true,
        messages: {
            required: "Please enter who the item is for."
        }
    });
}
function ValidateCamperNameOtherAdd() {
    $("#camper_name_other").rules("add", {
        required: true,
        messages: {
            required: "Please enter who the item is for."
        }
    });
}
function ValidateShipOutAdd() {
    $("#ctl00_PageContent_txtQty").rules("add", {
        required: true,
        digits: true,
        min: 1,
        messages: {
                digits: "Please enter how many you would like to purchase.",
                required: "Please enter how many you would like to purchase.",
                min: "Please enter how many you would like to purchase."
        }
    });
}
