/* Global application controller and settings */

function Application() {
    // Settings
    var animationSpeed;

    // Internal state
    var categoryId;
    var filterListPositive; // selected filters
    var filterListNegative; // selected filters
    var productListType;
    var supplierList;
    var paymentDeliveryTypeSelectJson;

    /**
     * Set initial values
     */
    this.init = function() {
        this.animationSpeed = 'fast';
        this.filterListPositive = [];
        this.filterListNegative = [];
        this.productListType = 'large';
        this.supplierList = [];
        this.paymentDeliveryTypeSelectJson = {};
    };
    /**
     * Update filter list from checkboxes
     */
    this.updateFilterList = function() {
        var self = this;
        self.filterListPositive = [];
        self.filterListNegative = [];
        $("input.filterItem.enabled").each( function(i, item) {
            if( $(item).is(":checked") ) {
                self.filterListPositive.push( $(item).attr('filterId') );
            } else {
                self.filterListNegative.push( $(item).attr('filterId') );
            }
        });
    };
    this.setFilterListPositive = function( filter ) {
        this.filterListPositive = filter;
    };
    this.setFilterListNegative = function( filter ) {
        this.filterListNegative = filter;
    };
    /**
     * Update supplier list from checkboxes
     */
    this.updateSupplierList = function() {
        var self = this;
        self.supplierList = [];
        $("input.supplierItem:checked").each( function(i, item) {
            self.supplierList.push( $(item).attr('supplierId') );
        });
    };
    this.setSupplierList = function( supplier ) {
        this.supplierList = supplier;
    };
    /**
     * Updates productListType
     */
    this.setProductListType = function(type) {
        this.productListType =  type;
    }
    /**
     * Enable/Disable filter
     */
    this.setFilterEnabled = function (filterId, enabled) {
        var $filterInput = $("#filterList input.filterItem[filterId='" + filterId + "']");
        if( enabled ) {
            $("#filterList input.filterItemActive[filterId='" + filterId + "']").attr('checked','checked');
            $filterInput.addClass("enabled");
            $filterInput.attr('disabled','');
            $filterInput.parent("td").removeClass('disabled');
        } else {
            $filterInput.removeClass("enabled");
            $filterInput.attr('disabled','disabled');
            $filterInput.parent("td").addClass('disabled');
        }

    }
    this.setSupplierAll = function( enabled ) {
        $("#supplierAll").attr('checked', enabled ? 'checked' : '' );
        $("#supplierList .supplierItem[supplierId != '0']").each( function( i, item) {
            //                    var supplierId = $(this).attr("supplierId");
            //                    $("#supplierList input.supplierItemActive[supplierId='" + supplierId + "']").attr('checked','checked');
            if( enabled ) {
                $(item).removeClass("enabled");
                $(item).attr('disabled','disabled');
                $(item).attr('checked','checked');
                $(item).parent("td").addClass('disabled');
            } else {
                $(item).addClass("enabled");
                $(item).attr('disabled','');
                $(item).attr('checked','');
                $(item).parent("td").removeClass('disabled');
            }
        });
    }
    /**
     * Show product content
     */
    this.showContent = function( categoryId ) {
        var self = this;
        //        console.log( self.filterList );
        if( typeof categoryId != 'undefined' ) {
            this.categoryId = categoryId;
        }
        this.updateFilterList();
        this.updateSupplierList();
        $("#content").fadeOut( self.animationSpeed, function() {
            $("#content").html( $('#loaderInfoContainer').html() );
            $("#content").show();
            $("#content").load("/main/productContent", {
                categoryId: self.categoryId,
                selectedFilterListPositive: self.filterListPositive.toString(),
                selectedFilterListNegative: self.filterListNegative.toString(),
                selectedSupplierList: self.supplierList.toString(),
                productListType: self.productListType
            }, function() {
                $("#content").hide();
                $.each( self.filterListPositive , function( i, filterId ) {
                    $("#filterList input.filterItem[filterId='" + filterId + "']").attr('checked','checked');
                    self.setFilterEnabled( filterId, true );
                });
                $.each( self.filterListNegative , function( i, filterId ) {
                    self.setFilterEnabled( filterId, true );
                });
                //                console.log( self.supplierList ) ;
                if( self.supplierList[0] == 0 ) {
                    self.setSupplierAll(true)
                } else {
                    self.setSupplierAll(false)
                    $.each( self.supplierList , function( i, supplierId ) {
                        $("#supplierList input.supplierItem[supplierId='" + supplierId + "']").attr('checked','checked');
                    });
                }
                $(this).fadeIn( self.animationSpeed );
                self.setupPageDimensions();
            } );
        } );
    };
    /**
     * Show static content
     */
    this.showStaticContent = function( pageName ) {
        var self = this;
        $("#menuCategoryUl .selected").removeClass('selected');
        $("#content").fadeOut( self.animationSpeed, function() {
            $("#content").html( $('#loaderInfoContainer').html() );
            $("#content").show();
            $("#content").load("/main/staticContent", {
                pageName: pageName
            }, function() {
                $("#content").hide();
                $(this).fadeIn( self.animationSpeed );
                self.setupPageDimensions();
            } );
        } );
    };
    this.showProductDetail = function( productId, title ) {
        //        $("#ui-dialog-title-productDetailDialog").html(title);
        $("#productDetailDialog").hide();
        $("#productDetailDialog").load('/main/productDetail', {
            productId: productId
        }, function() {
            $("#productDetailDialog").fadeIn('fast');
        } );
        $("#productDetailDialog").dialog("open");
    }
    /**
     * Setup page dimensions (must be called after each ajax load)
     */
    this.setupPageDimensions = function () {
        var headerHeight = $("#headerBox").height();
        var newHeight = $(window).height() - headerHeight - 52;
        $('#content, #menuCategory, #rightColumn, #staticContent').css('height', newHeight + 'px');
        //        $('#content').height( newHeight );
        //        $('#menuCategory').height( newHeight );
        //        $('#rightColumn').height( newHeight );
        //$('#content').css('height', $(window).height() - 20 );
        //$('#debug').html( $("#content").innerHeight() + " " +  $("#filterBox").height() + " " + $("#productListType").height() );
        $('#productList').height( newHeight - $("#filterBox").height() - 20 );
    //$('#productList').height( $("#content").innerHeight() - $("#filterBox").height() - $("#productListType").height() );
    //            console.log( $("#content").innerHeight() );
    //            console.log( $("#filterBox").height() );
    //
    //            console.log( $("#content").innerHeight() - $("#filterBox").height() );
    }

    /**
     * Show order list dialog
     */
    this.showOrderList = function() {
        var self = this;
        $("#orderListContent").load("/main/orderList", {
            }, function() {
                $("#orderListDialog").dialog("open");
            });
    }

    /**
     * Register user
     */
    this.submitRegisterUser = function() {
        var self = this;
        if( $("#registerUserForm").valid() ) {
            $.getJSON('/main/registerUser', $("#registerUserForm").getFormData(), function(data) {
                $("#registerUserForm .messageTd").html( data.message );
                if( data.status == 'ok' ) {
                    self.showUserBox();
                    $("#registerUserDialog").dialog('close');
                }
            });
        }
    }
    /**
     * Show register user dialog
     */
    this.showRegisterUser = function() {
        var self = this;
        $("#registerUserForm").load("/main/userAddressForm", {
            }, function() {
                //            console.log( self.getUserAddressFormValidateRules() );
                $("#registerUserForm").validate( self.getUserAddressFormValidateRules( "#registerUserForm" ) );
                $("#registerUserDialog").dialog("open");
            });
    }
    /**
     * Modify user data
     */
    this.submitModifyUser = function() {
        var self = this;
        if( $("#modifyUserForm").valid() ) {
            $.getJSON('/main/modifyUser', $("#modifyUserForm").getFormData(), function(data) {
                $("#modifyUserForm .messageTd").html( data.message );
                if( data.status == 'ok' ) {
                    self.showUserBox();
                    $("#modifyUserDialog").dialog('close');
                }
            });
        }
    }
    /**
     * Show modify user dialog
     */
    this.showModifyUser = function() {
        var self = this;
        $("#modifyUserForm").load("/main/userAddressForm", { 
            hideLogin: true
        }, function() {
            //            console.log( self.getUserAddressFormValidateRules() );
            $("#modifyUserForm").validate( self.getUserAddressFormValidateRules( "#modifyUserForm" ) );
            $("#modifyUserDialog").dialog("open");
        });
    }
    /**
     * Show modify user dialog
     */
    this.showUserBox = function() {
        $("#userBox").load('/main/userBox');
    }

    this.setPaymentDeliveryTypeSelectJson = function( value ) {
        this.paymentDeliveryTypeSelectJson = value;
    };
    /**
     * Update paymentDeliveryType select. Called when Country Id changes
     */
    this.updatePaymentDeliveryTypeSelect = function() {
        var self = this;
        var country = $("select.showPaymentDeliveryType").val();
        $("select[name='paymentDeliveryType']").jsonFeedSelect( self.paymentDeliveryTypeSelectJson[country] );
    }
    /**
     * Show order address dialog
     */
    this.showOrderAddress = function() {
        var self = this;
        $("#orderAddressForm").load("/main/userAddressForm", {
            hideLogin: true,
            hidePassword: true,
            showPaymentDeliveryType: true
        }, function() {
            //            console.log( self );
            $("#orderAddressForm").validate( self.getUserAddressFormValidateRules( "#modifyUserForm" ) );
            //            $("#orderAddressForm").validate( self.getUserAddressFormValidateRules( "#orderAddressForm" ) );
            self.updatePaymentDeliveryTypeSelect();
            $("#orderAddressDialog").dialog("open");
        });
    }
    /**
     * Send order
     */
    this.sendOrder = function() {
        var self = this;
        this.showOrderAddress();
    //        $("#orderAddressDialog").dialog("open");
    }
    /**
     * Submit order address
     */
    this.submitOrderAddress = function() {
        var self = this;
        if( $("#orderAddressForm").valid() ) {
            $.getJSON('/main/orderAddress', $("#orderAddressForm").getFormData(), function(data) {
                $("#messageTd").html( data.message );
                if( data.status == 'ok' ) {
                    //                    $("#userBox").load('/main/userBox');
                    $("#orderAddressDialog").dialog('close');
                    self.showOrderPreview();
                //                    $("#orderPreviewDialog").dialog('open');
                } else {
                    $("#orderAddressDialog").dialog('close');
                    $("#notAdultWarningDialog").dialog('open');
                }
            });
        }
    }

    /**
     * Refresh order preview dialog - send form data
     */
    this.refreshOrderPreview = function() {
        var self = this;
        var options = {};
        options['paymentDeliveryTypeChange'] = $("select[name='paymentDeliveryTypeChange']").val();
        options['bonusCode'] = $("input[name='bonusCode']").val();
        application.showOrderPreview( options );
    }

    /**
     * Show order preview dialog
     */
    this.showOrderPreview = function( data ) {
        var self = this;
        $("#orderPreviewDialog").load("/main/orderPreview", data, function() {
            $("#orderPreviewDialog").dialog("open");
        });
    }
    /**
     * Submit order
     */
    this.submitOrderPreview = function() {
        var self = this;
        $.getJSON('/main/orderSend', function(data) {
            if( data.status == 'ok' ) {
                $("#userBox").load('/main/userBox');
                $("#orderAddressPreview").dialog('close');
                $("#orderSentDialog").dialog('open');
            }
        });
    }
    /**
     * Cancel order
     */
    this.cancelOrder = function() {
        var self = this;
        $.getJSON('/main/orderCancel', function(data) {
            if( data.status == 'ok' ) {
        //                $("#userBox").load('/main/userBox');
        //                $("#orderAddressPreview").dialog('close');
        //                $("#orderCancelDialog").dialog('open');
        }
        });
    }

    this.getUserAddressFormValidateRules = function( formId ) {
        return {
            rules: {
                firstname: "required",
                lastname: "required",
                street: "required",
                city: "required",
                postcode: {
                    required: true,
                    digits: true
                },
                email: {
                    required: true,
                    email: true
                },
                login: {
                    required: true,
                    minlength: 5
                },
                password: {
                    required: true,
                    minlength: 5
                },
                password2: {
                    required: true,
                    minlength: 5,
                    equalTo: formId + " .password"
                }
            //adult: "required"
            },
            messages: {
                firstname: "Please enter your firstname",
                lastname: "Please enter your lastname",
                username: {
                    required: "Please enter a username",
                    minlength: "Your username must consist of at least 2 characters"
                },
                password: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                },
                password2: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long",
                    equalTo: "Please enter the same password as above"
                },
                email: "Please enter a valid email address"
            }
        }

    }

    this.addToBasket = function( productId, count) {
        var self = this;
        $("#loadingDialog").dialog('open');
        $.getJSON('/main/addToBasket', {
            productId: productId,
            count: count
        }, function(data) {
            $("#messageTd").html( data.message );
            if( data.status == 'ok' ) {
                $("#basketBox").load('/main/basketBox');
                $("#loadingDialog").dialog('close');
            }
        });

    }
};

var application = new Application();
application.init();
