﻿/// <reference name="MicrosoftAjax.js"/>
function Delegate(f) {
    this.func = f;
}
Delegate.prototype.func = function() { }
Delegate.create = function(obj, func) {
    var f = function() {
        var target = arguments.callee.target;
        var func = arguments.callee.func;
        return func.apply(target, arguments);
    };

    f.target = obj;
    f.func = func;

    return f;
}

String.prototype.toUSD = function() {
    var num = this.replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

String.prototype.isEmail = function() {
    var regex = new RegExp("^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$");
    return regex.test(this);
}

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

var formatUSNumber = function (input) {
    var unformattedNumber = input.replace(/\D/g, "");
    var formattedNumber = unformattedNumber;

    try {
        //555
        if (unformattedNumber.length >= 3) {
            formattedNumber = unformattedNumber.substring(0, 3) + "-";
        }
        //555-5??
        if (unformattedNumber.length > 3 && unformattedNumber.length < 6)
            formattedNumber += unformattedNumber.substring(3, unformattedNumber.length);
        //555-555-5???
        if (unformattedNumber.length >= 6) {
            formattedNumber += unformattedNumber.substring(3, 6);
            formattedNumber += "-" + unformattedNumber.substring(6, unformattedNumber.length);
        }
    }
    catch (err) {
        formattedNumber = input;
        //alert("United States phone numbers must have exactly ten digits.");
        return input;
    }
    return formattedNumber;
}

var restrictToNumbersInput = function(e) {
    if (e) {
        var num = /[0-9]+/;
        var allowedKeyCodes = [8, 9, 35, 36, 46, 37, 38, 39, 40];
        var keyPressed = (e.charCode) ? String.fromCharCode(e.charCode) : String.fromCharCode(e.keyCode);
        if (keyPressed)
            keyPressed = keyPressed.toLowerCase();
        if ((e.ctrlKey || e.metaKey) && keyPressed == "v") {
            //could be pasting
            return true;
        }
        else
            if (!num.test(keyPressed) && allowedKeyCodes.indexOf(e.keyCode) < 0) {
            return false;
        }
        else
            return true;
    }
    else {
        trace("no event");
    }
}

//requires jQuery 1.2.6 or higher
function NopCommerce() { };


//Gift Card processing
NopCommerce.CurrentGiftCards = new Object();
NopCommerce.GiftCardBalanceView = function(containerElementId, cardNumberElementId, balanceElementId, closeElementId) {
    if (cardNumberElementId && balanceElementId && closeElementId) {
        this.cardNumberElement = $('#' + cardNumberElementId);
        this.balanceElement = $('#' + balanceElementId);
        this.closeElement = $('#' + closeElementId);
        this.containerElement = $('#' + containerElementId);
    }
    else {
        //containerElementId is assumed as the parent ID if the other params are null/undefined
        var parent = $('#' + containerElementId);
        if (parent) {
            this.generate(parent);
        }
    }

    if (this.cardNumberElement != null) {
        if (this.getCardNumber() != 0)
            NopCommerce.CurrentGiftCards[this.getCardNumber()] = this;
    }
}
NopCommerce.GiftCardBalanceView.prototype = {
    containerElement: null,
    cardNumberElement: null,
    balanceElement: null,
    closeElementContainer: null,
    closeElement: null,
    generate: function(parentToAppend) {
        //generate the container
        this.containerElement = $(document.createElement(NopCommerce.GiftCardBalanceView.TAG_CONTAINER));
        //css
        this.containerElement.addClass("card-balance-item");
        //generate the number
        this.cardNumberElement = $(document.createElement(NopCommerce.GiftCardBalanceView.TAG_TD));
        this.cardNumberElement.addClass("account-number");
        //generate the balance
        this.balanceElement = $(document.createElement(NopCommerce.GiftCardBalanceView.TAG_TD));
        this.balanceElement.addClass("card-balance");
        //generate the close
        this.closeElementContainer = $(document.createElement(NopCommerce.GiftCardBalanceView.TAG_TD));
        this.closeElement = $(document.createElement("a"));
        this.closeElement.addClass("closeLink");
        this.closeElementContainer.append(this.closeElement);

        parentToAppend.append(this.containerElement);
        //add together
        this.containerElement.append(this.cardNumberElement);
        this.containerElement.append(this.balanceElement);
        this.containerElement.append(this.closeElementContainer);

        this.closeElement.attr("href", "#");
        this.closeElement.text("Remove");
        this.closeElement.click(Delegate.create(this, this.close));
    },
    getCardNumber: function() {
        if (this.cardNumberElement != null)
            return Number(this.cardNumberElement.text().replace(/ /g, ''));
    },
    setCardNumber: function(val) {
        if (this.cardNumberElement != null) {
            NopCommerce.CurrentGiftCards[this.getCardNumber()] = null;
            //value length should be 19
            if (val.length == 19) {
                //format it
                val = val.substr(0, 6) + ' ' + val.substr(6, 6) + ' ' + val.substr(12, 7);
                this.cardNumberElement.text(val);
            }
            else {
                this.cardNumberElement.text(val);
            }
            NopCommerce.CurrentGiftCards[val.replace(/ /g, '')] = this;
        }
    },
    getBalance: function() {
        if (this.balanceElement != null) {
            return Number(this.balanceElement.text().replace(/\$|\,/g, ''));
        }
    },
    setBalance: function(val) {
        if (this.balanceElement != null)
            this.balanceElement.text(String(val).toUSD());
    },
    close: function(e) {
        try {
            var cardNumber = this.getCardNumber();
            NopCommerce.CurrentGiftCards[cardNumber] = null;
            var siblings = this.containerElement.siblings();
            if (this.containerElement)
                this.containerElement.remove();
            //rebuild the hidden field
            var cardsList = new Array();
            if (NopCommerce.GiftCardBalanceView.hiddenField) {
                var cards = NopCommerce.GiftCardBalanceView.hiddenField.val().split('|');
                for (var i = 0; i < cards.length; i++) {
                    if (cards[i].indexOf(cardNumber) >= 0)
                        cardsList.push(cards[i]);
                }
            }
            NopCommerce.GiftCardBalanceView.hiddenField.val(cardsList.join('|'));
            if (NopCommerce.GiftCardBalanceView.summaryContainer && siblings.length == 1)
                NopCommerce.GiftCardBalanceView.summaryContainer.hide();
        }
        catch (er) {
            //alert(er);
        }
        return false;
    }
}

NopCommerce.GiftCardBalanceView.getTotal = function() {
    var total = 0;
    for (var card in NopCommerce.CurrentGiftCards) {
        if (card.balance != null) {
            total += card.balance;
        }
    }
}
NopCommerce.GiftCardBalanceView.TAG_CONTAINER = "tr";
NopCommerce.GiftCardBalanceView.TAG_TD = "td";
NopCommerce.GiftCardBalanceView.VAR_COMMAND = "q";
NopCommerce.GiftCardBalanceView.VAR_CARDNUMBER = "c";
NopCommerce.GiftCardBalanceView.VAR_CVV = "v";
NopCommerce.GiftCardBalanceView.hiddenField = null;
NopCommerce.GiftCardBalanceView.container = null;
NopCommerce.GiftCardBalanceView.cardNumberField = null;
NopCommerce.GiftCardBalanceView.cardCVVField = null;
NopCommerce.GiftCardBalanceView.loadingGraphic = null;
NopCommerce.GiftCardBalanceView.errorMessagesContainer = null;
NopCommerce.GiftCardBalanceView.summaryContainer = null;
NopCommerce.GiftCardBalanceView.updateTotal = function(elementid) {
    var element = $('#' + elementid);
    if (element) {
        var total = NopCommerce.GiftCardBalanceView.getTotal();
        element.text(total.toString().toUSD());
    }
}
NopCommerce.GiftCardBalanceView.parseAll = function(hiddenFieldId, containerId) {
    NopCommerce.GiftCardBalanceView.hiddenField = $('#' + hiddenFieldId);
    if (NopCommerce.GiftCardBalanceView.hiddenField) {
        var cards = NopCommerce.GiftCardBalanceView.hiddenField.val().split('|');
        for (var i = 0; i < cards.length; i++) {
            var props = cards[i].split(';');
            if (props.length == 3) {
                var number = props[0];
                var balance = props[2];
                NopCommerce.GiftCardBalanceView.appendCard(containerId, number, balance);
            }
        }
    }
}
NopCommerce.GiftCardBalanceView.queryCard = function(hiddenFieldId, containerId, cardNumberId, cardCVVId) {
    NopCommerce.GiftCardBalanceView.hiddenField = $('#' + hiddenFieldId);
    NopCommerce.GiftCardBalanceView.container = $('#' + containerId);
    NopCommerce.GiftCardBalanceView.cardNumberField = $('#' + cardNumberId);
    NopCommerce.GiftCardBalanceView.cardCVVField = $('#' + cardCVVId);
    if (NopCommerce.GiftCardBalanceView.loadingGraphic)
        NopCommerce.GiftCardBalanceView.loadingGraphic.show();

    var cardNumber = NopCommerce.GiftCardBalanceView.cardNumberField.val();
    var cardCVV = NopCommerce.GiftCardBalanceView.cardCVVField.val();
    cardNumber = cardNumber.replace(/\D/g, '');
    if (cardNumber.length >= 19 && cardCVV >= 4) {
        if (NopCommerce.GiftCardBalanceView.hiddenField && NopCommerce.GiftCardBalanceView.container) {
            //if there are places to put these things, do it
            var ajaxURL = "/giftcards.ajax?" + NopCommerce.GiftCardBalanceView.VAR_COMMAND + "=balance&" + NopCommerce.GiftCardBalanceView.VAR_CARDNUMBER + "=" + cardNumber + "&" + NopCommerce.GiftCardBalanceView.VAR_CVV + "=" + cardCVV;
            $.getJSON(ajaxURL, NopCommerce.GiftCardBalanceView.queryCard_Response);
        }
    }
    else {
        //display error message
        if (NopCommerce.GiftCardBalanceView.loadingGraphic)
            NopCommerce.GiftCardBalanceView.loadingGraphic.hide();
    }
}

NopCommerce.GiftCardBalanceView.queryCard_Response = function(responseData) {
    if (NopCommerce.GiftCardBalanceView.loadingGraphic)
        NopCommerce.GiftCardBalanceView.loadingGraphic.hide();
    if (NopCommerce.GiftCardBalanceView.summaryContainer)
        NopCommerce.GiftCardBalanceView.summaryContainer.show();
    var cardJSON = responseData;
    if (cardJSON.status == "Activated") {
        var cardSummary = cardJSON.number + ';' + cardJSON.CVD + ';' + cardJSON.balance;
        var cardNumber = cardJSON.number;
        var cardBalance = cardJSON.balance;

        var cardsList = new Array();
        if (NopCommerce.GiftCardBalanceView.hiddenField) {
            var cards = NopCommerce.GiftCardBalanceView.hiddenField.val().split('|');
            for (var i = 0; i < cards.length; i++) {
                if (cards[i].indexOf(cardNumber) != 0) {
                    cardsList.push(cards[i]);
                }
                else {
                    try {
                        NopCommerce.GiftCardBalanceView.cardNumberField.val('');
                        NopCommerce.GiftCardBalanceView.cardCVVField.val('');
                        if (NopCommerce.GiftCardBalanceView.errorMessagesContainer) {
                            NopCommerce.GiftCardBalanceView.errorMessagesContainer.text('');
                        }
                        return;
                    }
                    catch (er) {
                    }
                }
            }

            cardsList.push(cardSummary);

            //add it back
            NopCommerce.GiftCardBalanceView.appendCard(NopCommerce.GiftCardBalanceView.container.attr("id"), cardNumber, cardBalance);
            NopCommerce.GiftCardBalanceView.hiddenField.val(cardsList.join('|'));

            NopCommerce.GiftCardBalanceView.cardNumberField.val('');
            NopCommerce.GiftCardBalanceView.cardCVVField.val('');
            if (NopCommerce.GiftCardBalanceView.errorMessagesContainer) {
                NopCommerce.GiftCardBalanceView.errorMessagesContainer.text('');
            }
        }
    }
    else {
        if (NopCommerce.GiftCardBalanceView.errorMessagesContainer) {
            NopCommerce.GiftCardBalanceView.errorMessagesContainer.text(cardJSON.message);
        }
    }
}
NopCommerce.GiftCardBalanceView.appendCard = function(parentElementId, cardNumber, balance) {
    var gcb = new NopCommerce.GiftCardBalanceView(parentElementId);
    gcb.setCardNumber(cardNumber);
    gcb.setBalance(balance);
}
NopCommerce.LimitCharacters = function(e) {
    if (e.target)
        var textArea = e.target;

    var maxLength = 300;
    if (e.data)
        maxLength = e.data.limit;
    if (textArea) {
        //if (textArea.nodeType == 3) textArea = textArea.parentNode;

        var allowedKeyCodes = [8, 9, 35, 36, 46, 37, 38, 39, 40];
        var keyCode = e.charCode;
        var keyPressed = String.fromCharCode(keyCode);

        if (allowedKeyCodes.indexOf(keyCode) >= 0) {
            NopCommerce.Truncate(e);
            return true;
        }

        if (textArea.value.length <= maxLength) {
            return true;
        }
        else {
            NopCommerce.Truncate(e);
            e.preventDefault();
            return false;
        }
    }
    return true;
}
NopCommerce.Truncate = function(e)
{
    if (e.target)
        var textArea = e.target;
    var maxLength = 300;
    if (e.data)
        maxLength = e.data.limit;
    if (textArea)
    {
        //if (textArea.nodeType == 3) textArea = textArea.parentNode;
        
        if (textArea.value.length > maxLength)
        {
            textArea.value = textArea.value.substr(0, 300);
        }
    }
}

//form auto selector
NopCommerce.AutoFocusForm = function(id) {
    if (id)
        this.id = id;
    NopCommerce.AutoFocusForm.ActiveForms[this.id] = this;
    //tack on to the load event
    $(window).load(Delegate.create(this, this.onLoad));
};
NopCommerce.AutoFocusForm.ActiveForms = new Object();
NopCommerce.AutoFocusForm.prototype = {
    id: "default",
    registeredFields: new Object(),
    focus: function(focusName) {
        if (this.registeredFields[focusName]) {
            var element = $('#' + this.registeredFields[focusName]);
            if (element) {
                $('html, body').animate({
                    scrollTop: element.offset().top
                }, 500);
                element[0].focus();
            }
        }
    },
    registerFocus: function(focusName, focusId) {
        //this will replace previous selections
        this.registeredFields[focusName] = focusId;
    },
    focusFromHash: function() {
        //select
        var hash = location.hash;
        var namePair = hash.replace('#', '').split('=');
        if (namePair.length > 1) {
            var affId = namePair[0];
            var focusName = namePair[1];
            if (affId == this.id) {
                if (this.registeredFields[focusName]) {
                    this.focus(focusName);
                }
            }
        }
    },
    onLoad: function(e) {
        //console.log('loaded');
        this.focusFromHash();
        //console.log('should have selected');
    }
}
NopCommerce.AutoFocusForm.focus = function(autoFocusFormId, focusName) {
    var aff = NopCommerce.AutoFocusForm.ActiveForms[autoFocusFormId];
    if (aff) {
        aff.focus(focusName);
    }
}
NopCommerce.AutoFocusForm.registerFocus = function(autoFocusFormId, focusName, focusId) {
    var aff = NopCommerce.AutoFocusForm.ActiveForms[autoFocusFormId];
    if (aff == null) {
        //create a default if there is none
        aff = new NopCommerce.AutoFocusForm(autoFocusFormId);
    }
    aff.registerFocus(focusName, focusId);
}
