/// <reference path="jquery-1.7.1.js" />

if (typeof console == "undefined") var console = { log: function (m) { } };

// enamor
(function ($) {
    
    var $e = $.enamor = {
        // common/base functions
    };

})(jQuery);

// Layout
(function ($) {

    var $e = $.enamor;

    function initDailyAlerts() {
        $('#daily_alert .colorbox_close').click(function () { $.fn.colorbox.close(); });
        
        var form = $('#daily_alert form'), formFlashMsg = FlashMsg(form);
        
        $('#signup_alert:first').colorbox({
            scrolling: false, inline: true, href: "#daily_alert",
            onClosed: function () { 
                console.log('signup_alert.colorbox.onClosed()');
                formFlashMsg.remove(); },
            onComplete: function () {
                console.log('signup_alert.colorbox.onComplete()');
                form.data("validator").settings.submitHandler = function (form) {
                    console.log('signup_alert.submitHandler()');
                    formFlashMsg.remove();
                    var emailAddy = $('#email_input').val(),
                        submitBtn = $('#email_submit'),
                        city = $('#city').val(),
                        reqData = { Key: city, Value: emailAddy };

                    $.ajax({
                        type: 'POST',
                        url: '/Account/NonUserAlerts',
                        data: $.toJSON(reqData),
                        beforeSend: function () { submitBtn.val('Submitting...'); },
                        complete: function () { submitBtn.val('Submit'); },
                        success: function (data) {
                            if (data.Success) {
                                $('#email_input').val('');
                                $.fn.colorbox.close();
                                window.location = '/Home/ThankYou/4';
                            }
                            else {
                                //on user error
                                formFlashMsg.error(data.Message);
                                $.fn.colorbox.resize();
                            }
                        },
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8'
                    });

                    return false;
                }
            }
        });
    };

    function initFacebookDetails() {
        $('#connect_details .colorbox_close').click(function () { $.fn.colorbox.close(); });
        $('#facebookdetails').colorbox({ scrolling: false, inline: true, href: '#connect_details' });
    };

    function initChooseCity() {
        $('a#choose_city').click(function () { toggleCities(); return false; });
    }

    function toggleCities() {
        var cities = $('#cities_list');
        (cities.is(':visible')) ? cities.slideUp() : cities.slideDown();
    };

    $e.layout = {
        init: function () {
            initDailyAlerts();
            initFacebookDetails();
            initChooseCity();

            var c = $('#content, #mycontent');
            if (c.hasClass('home')) { $('li.deal_of_day a').addClass('selected'); }
            else if (c.hasClass('recent_deals')) { $('li.recent_deals a').addClass('selected'); }
            else if (c.hasClass('coming_deals')) { $('li.coming_deals a').addClass('selected'); }
        }
    };

})(jQuery);

// purchase
(function ($) {

    var $e = $.enamor;

    var value,          // Deal value
        donation,       // Deal donation percentage
        credit,         // Customer credit balance
        quantity = 1,   // Deal quantity
        customerEmail,  // customer's email
        confirmView = false;

    var gifts = []; // gifts information to be serialize to JSON

    var form,           // purchase form
        validator,      // form validator
        submitHandler;  // form submit handler

    $e.purchase = {
        
        // intialize default values, event binding, etc
        init: function (options) {
            
            value         = options.value || 1;
            credit        = options.credit || 0;
            donation      = options.donation || 3;
            customerEmail = options.email;
            
            // whether to auto open the gift screen on page load
            var isGift = options.isGift || false; 
            
            form = $('#payform');

            // initilize quantity (used in updateView())
            quantity = $('#Quantity', form).val();

            validator = form.data("validator");
            // save current submit handler before override it
            submitHandler = validator.settings.submitHandler;
            validator.settings.submitHandler = confirmPayment; 

            // rise click event when MakeDonation checkbox is clicked to for validation
            $('#MakeDonation:first', form).click(function(){ $('#SelectedCharity', form).click(); });

            // handle quantity changes
            $('#Quantity', form).bind('change click', function(){ setQuantity($(this).val()); });

            // handle quantity changes when up/down buttons are clicked
            $('.t-link', form).click(function(){ setQuantity($('#Quantity', form).val()); });

            $('.change-order').click(function(){ hideSummary(); });

            $('#CCNumber').bind('keyup', function(){ 
                var val = $(this).val();
                $(this).removeClass('cc-amex cc-jcb cc-mc cc-visa cc-discover cc-dinners'); 
                if(val && val.length>12){ getCardType(); }
            });

            form.submit(function (e) {  
                if(confirmView){
                    $('#submit_order').hide();
                    $('.change-order').hide();
                    $('#submit_processing').show();
                    //return false;  
                }
                else{ confirmView = true; }
            });
//            $('.submit_order', form).click(function(){alert('hola mundo cruel!!');/* $(this).hide(); */});
            
            // remove gift instances
            $('a.remove_gift').live('click', function () {
                var li = $(this).parents('li');
                var id = li.attr('id').replace(/gift/,'');
                removeGift(id); // remove the gift for the collection and update screen values
                li.fadeOut();
                return false;
            });

            // handle add gift link/modal form
            $('.add_gift', form).colorbox({
                // colorbox settings
                scrolling: false, inline: true, href: '#give_gift',
                
                onComplete: function () {
                    // customize submitHandler
                    $('#give_gift form').data("validator").settings.submitHandler = function (form) {
                        
                        var giftform = $('#give_gift');

                        // if teh gift will be emailed to someone
                        var emailed = $('#email_gift', giftform).attr('checked');

                        // gift info
                        var data = { id: gifts.length + 1,
                                     to: $('#deliveryto', giftform).val(),
                                     from: $('#deliveryfrom', giftform).val(),
                                     message: $('#deliverymessage', giftform).val(),
                                     method: emailed ? 1 : 0, // emailed or printed
                                     text: emailed ? 'Email it for me' : 'We\'ll email you to print',
                                     email:  emailed ? $('#gift_email', giftform).val() : customerEmail };
                        
                        addGift(data);

                        // add gift html                        
                        var li = '<li id=gift'+data.id+' style="margin-bottom:10px"> \
                                    <div class="gift_header clearfix"><div class="left"><h3>Gift</h3></div><a href="#" class="remove_gift right">remove</a></div>\
                                    <ul class="gift_body clearfix">\
                                        <li><span class="left">To:</span><span class="deliveryTo">'+data.to+'</span></li>\
                                        <li><span class="left">From:</span><span class="deliveryFrom">'+data.from+'</span></li>\
                                        <li><span class="left">Message:</span><span class="deliveryMessage">'+data.message+'</span></li>\
                                        <li><span class="left">Delivery:</span><span class="deliveryMethod">'+data.text+'.<br />('+data.email+')</span></li>\
                                    </ul></li>';

                        $('#gifts ul:first').append(li);

                        // reset gift form
                        $('#give_gift :input').not(':submit').val('');
                        $('#email_gift', giftform).attr('checked', true);
                        $('#gift_email', giftform).show();
                        
                        $.fn.colorbox.close();
                        
                        return false;
                    }
                }
            });

            var email = $('#gift_email');

            $('input#email_gift').click(function () {
                email.addClass('required');
                email.attr('required', 'required');
                email.show();
                $.fn.colorbox.resize();
            });

            $('input#print_gift').click(function () {
                email.removeClass('required');
                email.attr('required', false);
                email.hide();
                $.fn.colorbox.resize();
            });

            // populate gifts (in case of return from post cause an error)
            gifts = $.parseJSON($('#GiftsJson').val());
            if(!gifts){ gifts = []; }

            if (isGift) { $('#add_gift').click(); }
            else { $('#Quantity', form).blur(); }
        
            updateView();
        }
    };

    //#region private functions

    function getCardType() {
        // remove spaces and dashes, TODO wouldn't be better to get only digits with an regex?
        var cc = $('#CCNumber').val().replace(' ', '').replace('-', '');

        var CARDS = {
            Visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
            MasterCard: /^5[1-5][0-9]{14}$/,                    // MasterCard beigins with 51-55, and length is 16.
            DinersClub: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,     // Diners Club begins with 300-305 or 36 or 38, and length is 14.
            Amex: /^3[47][0-9]{13}$/,                           // American Express begins with 34 or 37, and length is 15.
            Discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/           // Discover begins with 6011, and length is 16.
        };
        var element = $('#CCNumber');
        if (CARDS.Amex.test(cc)) { element.addClass('cc-amex'); return 'American Express'; } 
        else if (CARDS.MasterCard.test(cc)) { element.addClass('cc-mc'); return 'MasterCard'; } 
        else if (CARDS.Visa.test(cc)) { element.addClass('cc-visa'); return 'Visa'; }
        else if (CARDS.DinersClub.test(cc)) { element.addClass('cc-dinners');return 'DinersClub'; }
        else if ((/^(2014|2149)/).test(cc) && cc.length == 15) { return 'enRoute'; } //enRoute begins with 2014 or 2149, and length is 15.
        else if (CARDS.Discover.test(cc)) { element.addClass('cc-discover');return 'Discover'; } 
        else if ((/^(3)/).test(cc) && cc.length == 16) { element.addClass('cc-jcb'); return 'JCB'; }             //JCB begins with 3, and length is 16.
        else if ((/^(2131|1800)/).test(cc) && cc.length == 15) { element.addClass('cc-jcb'); return 'JCB'; }     //JCB begins with 2131 or 1800, and length is 15.
        else return 'Credit Card not recognized';
    };

    function hideSummary(){
        $('#almost_done').hide();
        var form = $('#payform');
        form.find('.edit-view').show();
        form.find('.summary-view').hide();
        $('#add_gift_container, #add_more_gifts, a.remove_gift, #gift_list_spacer', form).show();
        $('#purchase_donation').show();
        updateView();
        validator.settings.submitHandler = confirmPayment;
        confirmView = false;
    }

    function showSummary() {
    
        $('#almost_done').show();

        var form = $('#payform');
        form.find('.edit-view').hide();
        form.find('.summary-view').show();

        // Purchase Amount (quantity, gits)
        var container = $('#purchase_amt');
        $('#add_gift_container, #add_more_gifts, a.remove_gift, #gift_list_spacer', container).hide();
        if(gifts.length == 0) { $('#gift_list_callout').hide(); }

        // Donation Options
        container = $('#purchase_donation');
        var donate = $('#MakeDonation').is(':checked');

        if(donate) {
            $('#charity_name', container).html($('#SelectedCharity option:selected', container).text());
            var donationAmount = value * (donation / 100);
            var don = $.formatNumber(donationAmount * quantity, { format: "#,##0.00", locale: "us" });
            container.find('#donation_amount').html(don);
        }
        else { container.hide(); }

        // Payment Options
        var total = value * quantity;
        billingcontainer = form.find('#billing_summary');
        paymentcontainer = form.find('#payment_summary');
        
        if(total > credit){
            billingcontainer.find('#billing_name').html($('#CCFirstName').val() + ' ' + $('#CCLastName').val());
            billingcontainer.find('#address').html($('#CCAddress').val());
            billingcontainer.find('#billing_citystatezip').html($('#CCCity').val() + ', ' + $('#SelectedStateId option:selected').text() + '  ' + $('#CCZipCode').val());

            paymentcontainer.find('#total_amount').html(total - credit);
            paymentcontainer.find('#card_type').html(getCardType()).show();
            paymentcontainer.find('#expiration').html($('#CCExpirationMonth').val() + '/' + $('#CCExpirationYear').val());
            paymentcontainer.find('#card_number_enc').html('*****'+$('#CCNumber').val().match(/.{4}$/));
        }
        else{
            paymentcontainer.find('#total_amount').html(total);
            paymentcontainer.find('#ccard-info-synopsis').hide();
            paymentcontainer.find('#credit-synopsis').show();
            billingcontainer.hide();
        }
    };

    function setQuantity(qty) {
        
        if (quantity == qty) { /* nothign to do */ return; }
        
        // quantity cannot be smaller then numger of gifts
        if (qty < gifts.length) {
            var input = $("#Quantity").data("tTextBox");
            input.value(gifts.length); // reset to minimum
            qty = gifts.length;
        }
        quantity = qty;
        updateView();

    }

    function updateView() {
        
        $('#qty_2').html(quantity);

        // show "Im giving a gift" link if no gift has been added
        if (quantity > 0 && gifts.length < 1) { 
            $('#add_gift').show(); 
        }
        else { 
            $('#add_gift').hide(); 
        }

        // update sale total
        var total = $.formatNumber(quantity * value, { format: "#,##0.##", locale: "us" });
        $('#totalAmount').html(total);

        // show CC form if needed
        if (total <= credit) {
            $('CreditCardRequired').val(false);
            $('.ccardfield').attr('disabled', true);
            $('#ccard-form').hide('fast');
            $('#ccard-info-synopsis').hide();
        }
        else {
            $('CreditCardRequired').val(true);
            $('.ccardfield').attr('disabled', false);
            $('#ccard-form').show('fast');
            $('#ccard-info-synopsis').show();
        }

        // update remaining info
        var remaining = quantity - gifts.length;
        $('#remaining_purchases').html(remaining);
        if (remaining > 0 && gifts.length > 0) { $('#add_container').show(); }
        else { $('#add_container').hide(); }
    };

    function addGift(data) {
        
        gifts.push(data);
        $('#GiftsJson').val($.toJSON(gifts));
        updateView();
    };

    function removeGift(id) {
        
        gifts = jQuery.grep(gifts, function(e){ return e.id != id  });
        $('#GiftsJson').val($.toJSON(gifts));
        updateView();
    }

    function confirmPayment() {
        
        showSummary();
        
        document.getElementById('almost-done').scrollIntoView();
        
        // restore for submitHandler
        validator.settings.submitHandler = submitHandler; 
    }

    //#endregion    
        
})(jQuery);

$(document).ready(function () {
    $.enamor.layout.init();
});

$(document).ready(function () {

    /*
    TODO 
    Layout.register => change to unobtrusive validation
    move this into $.enamor.account namespace
    */

    var Layout = {
        my_account: function () {
            $('#more_alerts').colorbox({ inline: true, href: '#cities_list' }, function () {
                $('#cities_list a').click(function () {
                    var cityKey = $(this).attr('id');
                    updateCityAlert(cityKey, true);

                    return false;
                });
            });

            $('#alert_cities a').click(function () {
                var clickedCity = $(this);
                var cityKey = clickedCity.attr('id');
                updateCityAlert(cityKey, false, function () {
                    clickedCity.parent().fadeOut('slow');
                });

                return false;
            });

            $('#change_password a').click(function () {
                $(this).parent()
            		.slideUp()
            		.next()
            		    .slideDown();

                $('#password_fields :input').addClass('required');

                return false;
            });

            $('#password_fields a').click(function () {
                $(this)
            		.parent()
            		.parent()
            			.slideUp()
            			.prev()
            				.slideDown();


                $('#password_fields input.text').val('');

                $('#password_fields :input').removeClass('required');

                return false;
            });

            // TODO MC why is disabled? customer should not be able to change his birthday?
            //            $('#Birthday').datepicker({
            //                changeMonth: true,
            //                changeYear: true,
            //                yearRange: '1930:1992'
            //            });

            $(document).bind('cbox_closed', function () {
                $('#cities_list').undelegate('a', 'click');
            });

        },

        register: function () {
            $('#register_form').validate({
                rules: {
                    password: {
                        minlength: 5
                    },
                    confirm_password: {
                        minlength: 5,
                        equalTo: "#password"
                    }
                }
            });

            $('#birthday_field').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '1930:1992'
            });
        }
    }

    Layout.my_account();
    Layout.register();
});

function updateCityAlert(cityKey, update, hollaback) {
    reqData = { Key: cityKey, Value: update };

    $.ajax({
        type: 'POST',
        url: '/Account/UserAlerts',
        data: $.toJSON(reqData),
        success: function (data) {
            if (data.Key.Success) {
                if (update) {
                    $.fn.colorbox.close();
                    $('#alert_cities').prepend(data.Value);
                }
                else {
                    hollaback();
                }
            }
        },
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    });
}

var FlashMsg = function (ele) {
    //private state
    var _addBefore = ele;
    
    var isOn = _addBefore.hasClass('flashMsgOn') ? true : false;

    var markup = function (msgType, msg) {
        return ('<div id="flashMsg" class="' + msgType + '">' + msg + '</div>');
    }

    var show = function(msgType, msg) {
        if(!isOn) {
            _addBefore.before(markup(msgType, msg));
            _addBefore.addClass('flashMsgOn');
        }
        else {
            $('#flashMsg').addClass(msgType).html(msg);
        }
    }

    //return public interface
    return {
        remove: function() {
            if(_addBefore.hasClass('flashMsgOn')) {
                $('#flashMsg').remove();
            }
        },

        error: function (msg) {
            show('error', msg);
        },

        success: function (msg) {
            show('success', msg);
        }
    }
}
