﻿
(function() {
    function InitializeProductForm() {
        LoadProducts();
        $('#cmbProducts').change(function() {
            LoadChainStyles();
        });
        $('#cmbChainStyles').change(function() {
            LoadChainLengths();
        });
        $('#cmbAccountImages').change(function() {
            OnAccountImageChange();
        });
        LoadAccountImages();
        WireInscriptionCheck();
        WireEmailPhotoCheck();
        WireMailPhotoCheck();
        WireUploadButtonClick();
        StyleError();
        $('#btnReset').click(function() {
            ResetSelections();
        });
    };
    function LoadProducts() {
        var jSelect = $('#cmbProducts');
        var select = jSelect[0];
        $.ajax({
            type: 'GET',
            url: 'services/clientservices.axd',
            data: 'method=GetProducts',
            dataType: 'json',
            success: function(data) {
                PopulateSelect(select, data);
                StyleProducts();
                LoadChainStyles();
            },
            error: function(xhttp, status, msg) {
                ToError(select);
            }
        });
    };
    function LoadChainStyles() {
        var productId = GetProductId();
        var select = $('#cmbChainStyles')[0];
        if (typeof productId == 'number' && !isNaN(productId)) {
            ToLoading(select);
            $.ajax({
                type: 'GET',
                url: 'services/clientservices.axd',
                data: 'method=GetChainStyles&productClassId=' + productId,
                dataType: 'json',
                success: function(data) {
                    PopulateSelect(select, data);
                    SetProductMessage();
                    LoadChainLengths();
                },
                error: function(xhttp, status, err) {
                    ToError(select);
                }
            });
        } else {
            ToError(select);
        }
    };
    function LoadChainLengths() {
        var chainStyleId = GetChainStyleId();
        var select = $('#cmbChainLengths')[0];
        if (typeof chainStyleId == 'number' && !isNaN(chainStyleId)) {
            ToLoading(select);
            $.ajax({
                type: 'GET',
                url: 'services/clientservices.axd',
                data: 'method=GetChainLengths&chainStyleId=' + chainStyleId,
                dataType: 'json',
                success: function(data) {
                    PopulateSelect(select, data);
                },
                error: function(xhttp, status, err) {
                    ToError(select);
                }
            });
        } else {
            ToError(select);
        }
    };
    function LoadAccountImages() {
        $.ajax({
            type: 'GET',
            url: 'services/clientservices.axd',
            data: 'method=GetAccountImages&thumbSize=100',
            dataType: 'json',
            success: function(data) {
                PopulateAccountImages(data);
            },
            error: function(xhttp, status, err) {
                ShowStatus('Error loading account images.', null, true, true);
            }
        });
    };
    function StyleProducts() {
        var select = $('#cmbProducts')[0];
        for (var i = 0; i < select.options.length; i++) {
            if ((i % 6) > 2) {
                $(select.options[i]).removeClass();
                $(select.options[i]).addClass('option-alternate');
            }
        }
    };
    function PopulateChainStyles(data) {
        var jSelect = $('#cmbChainStyles');
        jSelect.empty();
        for (var id in data) {
            jSelect.append('<option value="' + id + '">' + data[id] + '</option>');
        }
        var select = jSelect[0];
        if (select.options.length == 0) {
            ToNone(select);
            $('#txtProductMessage').text('Chains are not included with sterling orders.');
        } else {
            $('#txtProductMessage').text('Don\'t forget to choose chainstyle and length.');
            select.disabled = false;
            select.selectedIndex = 0;
        }
    };
    function PopulateChainLengths(data) {
        var jSelect = $('#cmbChainLengths');
        jSelect.empty();
        for (var id in data) {
            jSelect.append('<option value="' + id + '">' + data[id] + '</option>');
        }
        var select = jSelect[0];
        if (select.options.length == 0) {
            ToNone(select);
        } else {
            select.disabled = false;
            select.selectedIndex = 0;
        }
    };
    function SetProductMessage(hasChainStyles) {
        if ($('#cmbProducts')[0].selectedIndex % 3 == 2) {
            ShowStatus('Chains are not included with sterling orders.', null, true, true);
        }
    };
    function GetProductId() {
        var select = $('#cmbProducts')[0];
        return parseInt(select.options[select.selectedIndex].value);
    };
    function GetChainStyleId() {
        var select = $('#cmbChainStyles')[0];
        return parseInt(select.options[select.selectedIndex].value);
    };
    function PopulateSelect(select, data) {
        select.options.length = 0;
        for (var id in data) {
            var option = document.createElement('option');
            option.value = id;
            option.text = data[id];
            AddOption(select, option);
        }
        if (select.options.length == 0) {
            ToNone(select);
        } else {
            select.disabled = false;
            select.selectedIndex = 0;
        }
    };
    function PopulateAccountImages(data) {
        if (data.length > 0) {
            var panel = $('#pnlImageOptions');
            panel.empty();
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                var html = '<img'
                    + ' class="image-option"'
                    + ' src="ViewImage.aspx?imageId=' + obj.id + '"'
                    + ' width="' + obj.width + '"'
                    + ' height="' + obj.height + '"'
                    + ' onclick="llw.SelectImage(this,' + obj.id + ');" />';
                if ((i > 0) && ((i % 2) == 0)) {
                    html += '<br />';
                }
                panel.append(html);
            }
            $('#lnkImageOptions').click(function() {
                $('#pnlImageOptions').toggle('fast');
            });
        }
        else {
            ShowStatus('To select from uploaded photos, <a href="Login.aspx">log in</a>.', false, false);
            $('#lnkImageOptions').hide();
        }
    };
    function SelectImage(img, id) {
        $('#hfImageId')[0].value = id;
        ShowStatus('Updating Thumb...');
        var target = $('#imgProductImage')[0];
        target.src = img.src;
        target.width = img.width;
        target.height = img.height;
        target.onload = ShowImageLoadedStatus;
        $('#pnlImageOptions').hide('fast');
    };
    function OnAccountImageChange() {
        var select = $('#cmbAccountImages')[0];
        var selected = select.options[select.selectedIndex];
        var arry = selected.value.split(',');
        var img = $('#imgProductImage')[0];
        img.src = 'ViewImage.aspx?imageId=' + arry[0];
        img.width = arry[1];
        img.height = arry[2];
    };
    function AddOption(select, option) {
        if ($.browser.msie) {
            select.add(option);
        } else {
            select.add(option, null);
        }
    };
    function ToLoading(select) {
        PopulateSelect(select, { 0: 'Loading...' });
        select.disabled = true;
    };
    function ToNone(select) {
        PopulateSelect(select, { 0: 'None' });
        select.disabled = true;
    };
    function ToError(select) {
        PopulateSelect(select, { 0: 'Error' });
        select.disabled = true;
    };
    function ResetSelections() {
        $('#cmbProducts')[0].selectedIndex = 0;
        LoadChainStyles();
        $('#cmbGender')[0].selectedIndex = 0;
        $('#chkEmailPhoto')[0].checked = false;
        $('#chkMailPhoto')[0].checked = false;
        OnMailPhotoChecked();
        $('#txtInscription')[0].value = '';
        $('#chkNoInscription')[0].checked = false;
        OnNoInscriptionChecked();
        $('#cmbFontStyles')[0].selectedIndex = 0;
    };
    function WireInscriptionCheck() {
        $('#chkNoInscription').one('click', OnNoInscriptionChecked);
    };
    function OnNoInscriptionChecked() {
        var checked = $('#chkNoInscription')[0].checked;
        if (checked) {
            $('#pnlInscription').fadeTo('fast', 0.2, WireInscriptionCheck);
            $('#pnlInscription input').each(function() {
                DisableControl(this, true);
            });
        } else {
            $('#pnlInscription').fadeTo('fast', 1.0, WireInscriptionCheck);
            $('#pnlInscription input').each(function() {
                DisableControl(this, false);
            });
        }
    };
    function WireEmailPhotoCheck() {
        $('#chkEmailPhoto').one('click', OnEmailPhotoChecked);
    };
    function WireMailPhotoCheck() {
        $('#chkMailPhoto').one('click', OnMailPhotoChecked);
    };
    function OnEmailPhotoChecked() {
        var checked = $('#chkEmailPhoto')[0].checked;
        if (checked) {
            $('.image-panel').fadeTo('fast', 0.2, WireEmailPhotoCheck);
            $('.image-panel input').each(function() {
                DisableControl(this, true);
            });
            $('#chkMailPhoto')[0].checked = false;
        } else {
            $('.image-panel').fadeTo('fast', 1.0, WireEmailPhotoCheck);
            $('.image-panel input').each(function() {
                DisableControl(this, false);
            });
        }
    };
    function OnMailPhotoChecked() {
        var checked = $('#chkMailPhoto')[0].checked;
        if (checked) {
            $('.image-panel').fadeTo('fast', 0.2, WireMailPhotoCheck);
            $('.image-panel input').each(function() {
                DisableControl(this, true);
            });
            $('#chkEmailPhoto')[0].checked = false;
        } else {
            $('.image-panel').fadeTo('fast', 1.0, WireMailPhotoCheck);
            $('.image-panel input').each(function() {
                DisableControl(this, false);
            });
        }
    };
    function ProcessSubmit(btn) {
        var $button = $(btn);
        var button = $button[0];
        button.disabled = true;
        button.value = 'Submitting...';
        var error = Validate();
        if (!error) {
            button.form.submit();
        }
        else {
            ShowStatus(error, function() {
                button.disabled = false;
                button.value = 'Add To Cart';
            }, true, true);
        }
    };
    function DisableControl(jCtrl, disabled) {
        var ctrl = $(jCtrl)[0];
        if (ctrl && typeof ctrl.disabled != 'undefined') {
            ctrl.disabled = disabled;
        }
    };
    function Validate() {
        if ($('#txtInscription')[0].value == '' && !$('#chkNoInscription')[0].checked) {
            return 'Please enter inscription or check \'No Inscription\'';
        }
        if (parseInt($('#hfImageId')[0].value) < 0 && !$('#chkEmailPhoto')[0].checked && !$('#chkMailPhoto')[0].checked) {
            return 'Please upload a photo or check either \'Will Email Photo\' or \'Will Mail Photo\' box.';
        }
        if ($('#cmbGender')[0].selectedIndex == 0) {
            return 'Please select gender of product recipient.';
        }
        return '';
    };
    function StyleError() {
        $('#txtErrors').fadeTo('fast', 0.01);
    };
    function WireUploadButtonClick() {
        window.imageUploadObject = $('#btnUpload').upload({
            name: 'file',
            method: 'post',
            autoSubmit: true,
            enctype: 'multipart/form-data',
            action: 'services/clientservices.axd?method=uploadimage',
            onSubmit: function() {
                ShowStatus('Uploading file...', null, false, false);
            },
            onComplete: function(data) {
                var arry = data.split(',');
                var isError = data.indexOf('Error:') >= 0;
                if (!isError && arry && arry.length == 3) {
                    $('#hfImageId')[0].value = arry[0];
                    var img = $('#imgProductImage')[0];
                    img.src = 'ViewImage.aspx?imageId=' + arry[0];
                    img.width = arry[1];
                    img.height = arry[2];
                    img.onload = ShowImageLoadedStatus;
                    ShowStatus('Your file was uploaded successfully. Thumb is updating...', null, false, false);
                    window.imageUploadObject.set({ action: 'services/clientservices.axd?method=uploadimage&imageId=' + $('#hfImageId')[0].value });
                }
                else {
                    ShowStatus(data, null, true, true);
                }
            }
        });
    };
    function ShowImageLoadedStatus() {
        ShowStatus('Thumb is updated.', null, false, true);
    };
    function ShowStatus(message, callback, isError, animate) {
        if (isError) {
            ToClass('#txtStatus', 'form-message');
        } else {
            ToClass('#txtStatus', 'form-label');
        }
        if (animate) {
            $('#pnlStatus').fadeTo('fast', 0.1, function() {
                $('#txtStatus').html(message);
                $('#pnlStatus').fadeTo('slow', 1.0, function() {
                    if (callback) {
                        callback();
                    }
                });
            });
        } else {
            $('#txtStatus').html(message);
            $('#pnlStatus').fadeTo('fast', 1.0);
        }
    };
    function ToClass(element, newClass) {
        var jElement = $(element);
        jElement.removeClass();
        jElement.addClass(newClass);
    };
    /**************** Runtime **********************/
    if (typeof window.llw == 'undefined') {
        window.llw = {};
    }
    window.llw.ProcessSubmit = ProcessSubmit;
    window.llw.SelectImage = SelectImage;

    $(function() {
        InitializeProductForm();
    });
})();
