$(document).ready(function () {
    var Layout = {
        init: function (lbl) {
            (typeof Layout[lbl] === 'function') ? Layout[lbl]() : false;
        },

        home: function () {
            $('li.deal_of_day a').addClass('selected');
        },

        recent_deals: function () {
            $('li.recent_deals a').addClass('selected');
        },

        coming_deals: function () {
            $('li.coming_deals a').addClass('selected');
        },

        deals: function () {
        },

        my_account: function () {
            $('#more_alerts').colorbox({ inline: true, href: '#cities_list' }, function () {
                $('#cities_list').delegate('a', 'click', function () {
                    var cityKey = $(this).attr('id');
                    updateCityAlert(cityKey, true);

                    return false;
                });
            });

            $('#alert_cities').delegate('a', 'click', function () {
                var clickedCity = $(this);
                var cityKey = clickedCity.attr('id');
                updateCityAlert(cityKey, false, function () {
                    clickedCity.parent().fadeOut('slow');
                });

                return false;
            });

            $('#change_password').delegate('a', 'click', function () {
                $(this).parent()
            		.slideUp()
            		.next()
            		    .slideDown();

                $('#password_fields :input').addClass('required');

                return false;
            });

            $('#password_fields').delegate('a', 'click', function () {
                $(this)
            		.parent()
            		.parent()
            			.slideUp()
            			.prev()
            				.slideDown();


                $('#password_fields input.text').val('');

                $('#password_fields :input').removeClass('required');

                return false;
            });

            //            $('#Birthday').datepicker({
            //                changeMonth: true,
            //                changeYear: true,
            //                yearRange: '1930:1992'
            //            });

            $(document).bind('cbox_closed', function () {
                $('#cities_list').undelegate('a', 'click');
            });

        },

        my_history: function () {

        },

        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'
            });
        }
    }

    var viewLabel = $('#content').attr('class');
    //(viewLabel) ? Layout[viewLabel]() : Layout['init']();
    (viewLabel) ? Layout.init(viewLabel) : false;

    $('#choose_city').click(function () {
        toggleCities();
        return false;
    });

    nonUserAlertHelper();

    facebookConnectDetails();
});

function toggleCities() {
    var cities = $('#cities_list');

    (cities.is(':visible')) ? cities.slideUp() : cities.slideDown();
}

function facebookConnectDetails() {
    $('#facebookdetails').colorbox({
        scrolling: false,
        inline: true,
        href: '#connect_details'
    });
    return false;
}

/* 
    Handles Non user alert form interaction
 */
function nonUserAlertHelper() {
    var alertForm = $('#daily_alert form')
      , formFlashMsg = FlashMsg(alertForm);

    $('#signup_alert').colorbox({
        scrolling: false,
        inline: true,
        href: "#daily_alert",
        onClosed: function () {
            formFlashMsg.remove();
        },
        onComplete: function () {
            alertForm.validate({
                submitHandler: function (form) {
                    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) {
                                //formFlashMsg.success(data.Message); //Note: there is no message returned in this context
                                $('#email_input').val('');
                                $.fn.colorbox.close();
                                window.location = '/Home/ThankYou/4';
                            }
                            else {
                                //on user error
                                formFlashMsg.error(data.Message);
                                $.fn.colorbox.resize();
                            }

                            //$.fn.colorbox.resize();
                        },
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8'
                    });

                    return false;
                }
            });
        }
    });

    var giftForm = $('#give_gift form');
    //var giftContainer = $('#gifts table tr');
    var giftContainer = $('#gifts ul');

    $('.add_gift').colorbox({
        scrolling: false,
        inline: true,
        href: '#give_gift',
        onClosed: function () {

        },
        onComplete: function () {
            giftForm.validate({

                submitHandler: function (form) {
                    var deliveryTo = $('#deliveryto'),
                    deliveryFrom = $('#deliveryfrom'),
                    deliveryMessage = $('#deliverymessage'),
                    giftEmail = $('#gift_email'),
                    giftSubmit = $('#submit_gift'),
                    formdata = { DeliveryTo: deliveryTo.val(), DeliveryFrom: deliveryFrom.val(), DeliveryMessage: deliveryMessage.val(), DeliveryMethod: giftEmail.val() },
                    giftCount = $('#qty').val(),
                    remainingPurchases = $('#remaining_purchases'),
                    totalRemaining = remainingPurchases.html(),
                    addContainer = $('#add_container'),
                    giftLink = $('#add_gift');


                    $.ajax({
                        type: 'post',
                        url: '/Purchase/GetGiftView',
                        data: $.toJSON(formdata),
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        beforeSend: function () {
                            giftSubmit.val('Submitting...');
                        },
                        success: function (data) {
                            if (data.Success) {
                                giftContainer.append(data.Message);
                                if (giftCount > 0) {

                                    if (totalRemaining > 0) {
                                        remainingPurchases.html(totalRemaining - 1);
                                    }
                                    else if (totalRemaining == '') {
                                        remainingPurchases.html(giftCount - 1);
                                        totalRemaining = giftCount;
                                    }
                                    else {
                                        remainingPurchases.html(0);
                                    }

                                    if ((totalRemaining - 1) > 0) {
                                        addContainer.show();
                                        giftLink.show();
                                    }
                                    else {
                                        addContainer.hide();
                                        giftLink.hide();
                                    }
                                }
                                deliveryTo.val('');
                                deliveryFrom.val('');
                                deliveryMessage.val('');
                                giftEmail.val('');
                                giftSubmit.val('Done');
                                $.fn.colorbox.close();
                            }
                            else {
                                alert(result.Message);
                            }
                        },
                        error: function () {
                        }
                    });
                    return false;

                }
            });
        }
    });

}

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);
        }
    }
}