"use strict";
/**
 * Created by JetBrains PhpStorm.
 * User: sergasd
 * Date: 11.08.11
 * Time: 17:48
 * USER MODULE
 */

var User = (function($){

    'use strict';

    var tpls = {
        'changeManagerReason' :
                '<div>' +
                    '<textarea class="user_textarea" placeholder="Укажите причину смены менеджера" ></textarea>' +
                    '<div class="button_orange">' +
                        '<input id="change_manager_reason" type="button" value="Сменить"><span></span>' +
                    '</div>' +
                '</div>',
        'tpl2' : ''

    };


    var settings = {
        "isLogin" : false,
        "userName" : "username",
        "notRegisterText" : "Для покупки тура необходимо зарегистрироваться.",
        "buyTourConfirmText" : "Тур будет добавлен в личный кабинет.",
        "deleteTouristText" : "Турист будет удален?.",
        "touristTable" : ".tourists_table",
        "orderTable" : ".search_result",
        "editOrderId" : false,
        "managerId" : false,
        "regionId" : false
    };

    var that;



    function setSettings(options)
    {
        this.settings = $.extend(this.settings, options);
        //console.log(this.settings);
    }

    function init(options) {
        this.setSettings(options);

        this.dialog.init();
        this.request.init();

        that = this;

        this.ui.zebra();
    }





    /**
     * UI MODULE
     * Модуль пользовательского интерфейса
     * */
    var ui = {

        zebra : function(){
            $(settings['orderTable'] + " tr:even").css("background", "#fef8f2");
            $(settings['orderTable'] + " tr:odd").css("background", "#fff");
            $(".search_result tr:even").css("background", "#fef8f2");
        }

    };


    /**
     * AUTH MODULE
     * */
    var auth = {
        'vkLogin' : function(){return "vkLogin begin";},
        'fbLogin' : function(){return "fbLogin begin";}
    };


    /**
     * DIALOG MODULE
     * Модуль диалогового окна
     * */
    var dialog = {

        settings : {
            'width' : 800,
            'height' : 400,
            'splashScreenClass' : 'splash_screen',
            'containerSelector' : '.dialog_container',
            'contentSelector' : '.dialog_content',
            'closeButtonLabel' : "Закрыть",
            'closeButtonSelector' : '.dialog_button_close'
        },

        setOptions : function(options){
            $.extend(this.settings, options);
            return this;
        },

        init : function(options){
            this.setOptions(options);
            var that = this;
            var splash = '<div class="' + this.settings['splashScreenClass'] + '"></div>';
            $("body").prepend(splash);

            var dialog = '<div class="dialog_container">' +
                            '<div class="dialog_top">' +
                                '<a class="dialog_button_close" href="#">' + this.settings['closeButtonLabel'] + '</a>' +
                            '</div>' +
                            '<div class="dialog_content"></div>' +
                        '</div>';

            $("body").prepend(dialog);

            $(this.settings['closeButtonSelector']).bind('click', function(e){
                e.preventDefault();
                that.close();
            });
            return this;
        },

        _setCenter : function(){
            var left = (($("." + this.settings['splashScreenClass']).width()) / 2) - (this.settings['width'] / 2);
            var scrollTop = $(document).scrollTop();
            var top = ($("body").height() / 2) - (this.settings['height'] / 2);

            $(this.settings['contentSelector']).css({
                'width' : this.settings['width'],
                'height' : this.settings['height']
            });

            $(this.settings['containerSelector']).css({
                'left' : left + 'px',
                'top' : scrollTop + top + 'px',
                'zIndex' : '1100'
            }).show();
            return this;
        },

        _showSplash : function(){
            var ie7 = ($.browser.msie && $.browser.version == 7.0) ? true : false;
            $("object").hide();

            if(!ie7)
                $("." + this.settings['splashScreenClass']).fadeTo(10, 0.4).css('z-index', '1000').height($(document).height()).show();
            return this;
        },
        _hideSplash : function(){
            $("." + this.settings['splashScreenClass']).hide();
            return this;
        },

        /**
         * @function show
         * */
        show : function(){
            setTimeout(function(){
                User.dialog._showSplash()._setCenter();
            }, 0);

            return this;
        },
        close : function(){
            $("object").show();
            this._hideSplash();
            $(this.settings['containerSelector']).hide();
            return this;
        },

        setContent : function(content){
            $(this.settings['contentSelector']).html(content);
            return this;
        }

    };

    /**
     * ORDER MODULE
     * модуль работы с заказами
     * */
    var order = {

        buyTour : function(id, data){
            /*покупка только для зарегистрированных*/
            if(settings['isLogin'] === false)
            {
                alert(settings['notRegisterText']);
                return false;
            }

            //console.log(data);

            if(!confirm(settings['buyTourConfirmText'])) return;

            $.ajax({
                "url" : "/user/buytour",
                "type" : "POST",
                "dataType" : "JSON",
                "data" : {"id" : id, "data" : data},

                "success" : function(data){
                    alert(data.content);
                }
            });
        },

        deleteOrder : function(id){
            var tr = $(settings['orderTable']).find('tr[order_id="' + id + '"]');
            $.getJSON('/user/deleteorder',{'id' : id}, function(data){
                if(data.status == "ok")
                {
                    tr.fadeOut(100, function(){
                        tr.remove();
                        User.ui.zebra();
                    });
                }
                else
                {
                    User.dialog.setOptions({'width':'250','height':'90'}).setContent(data.content).show();
                }

            });
        },

        deleteTouristDialog : function(id){
            if(!confirm(settings['deleteTouristText']))
                return false;

            this._deleteTourist(id);
        },

        addTouristDialog : function(params){
            params = params || {};

            $.post('/user/tourist/getcontent/id/add_dialog/order_id/' + User.settings['editOrderId'], params, function(data){
                if(data && data.status != 'undefined')
                    User.dialog.setOptions({'width':'750','height':'520'}).setContent(data.content).show();
            }, 'JSON');
        },

        editTouristDialog : function(touristId, params){
            params = params || {};

            $.post('/user/tourist/getcontent/id/edit_dialog/order_id/' + User.settings['editOrderId'] + '/tourist_id/' + touristId, params, function(data){
                if(data && data.status != 'undefined')
                    User.dialog.setOptions({'width':'750','height':'520'}).setContent(data.content).show();
                    //console.log(data);

            }, 'JSON');
        },
        

        _deleteTourist : function(id){
            var tr = $(settings['touristTable']).find('tr[tourist_id="' + id + '"]');

            $.post('/user/tourist/delete',{'id' : id}, function(){
                User.order._refreshTourists();
            }, 'JSON');
        },

        _addTourist : function(tourist){
            this._refreshTourists();
        },

        

        _refreshTourists : function(){
            $.post('/user/tourist/list', {'order_id' : User.settings['editOrderId']}, function(data){
                if(data.status && data.status == 'ok')
                {
                    $(that.settings['touristTable']).html(data.content);
                    User.ui.zebra();
                }

            }, 'JSON');
        },

        changeManagerReason : function(){

            if(that.settings.managerId)
                User.dialog.setOptions({'width':'400','height':'150'}).setContent(User.tpls['changeManagerReason']).show();
            else
                this.changeManagerDialog();
        },


        changeManagerDialog : function(reason){
            $.post('/user/tourist/getcontent/id/manager_dialog', {'reason' : reason}, function(data){
                if(data.status == 'ok')
                    User.dialog.setOptions({'width':'830','height':'600'}).setContent(data.content)._setCenter().show();
            }, 'JSON');
        },

        changeManager : function(id, reason){
            $.post('/user/tourist/changemanager', {'id' : id, 'reason' : reason, 'order_id':User.settings['editOrderId']}, function(data){
                if(data.status == "ok")
                    window.location.reload(true);
            }, 'JSON');
        },

        request : function(){
            $.post('/user/tourist/getcontent/id/order_application', {'order_id' : User.settings['editOrderId']}, function(data){
                    if(data.status == 'ok')
                        User.dialog.setOptions({'width':'400','height':'300'}).setContent(data.content).show();
                }, 'JSON');
        },

        payOrder : function(amount, orderId, payType){
            var win = null,
                params = "directories=yes,menubar=yes,toolbar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";

            orderId = orderId || User.settings.editOrderId;

            $.ajax({
                'url' : '/user/tourist/payorder',
                'type' : 'POST',
                'async' : false,
                'dataType' : 'JSON',
                'data' : {'order_id' : orderId, 'amount' : amount, 'pay_type' : payType},
                'success' : function(data){

                    if(data.status == 'error'){
                        User.dialog.setContent(data.content).setOptions({'width' : 400, 'height' : 100}).show();
                    }
                    else if(data.status == 'ok' && data.url){
                        win = window.open(data.url, 'payment', params);
                    }

                }

            });

        }





    };


    /**
     * REQUEST MODULE
     * модуль для работы с запросом
     * */
    var request = {
        _items : {},

        init : function(){
            var quertString = window.location.href.substr(window.location.href.indexOf('?') + 1).split('&');

            for(var i = 0; i < quertString.length; i++)
            {
                var tmp = quertString[i].split('=');
                this._items[tmp[0]] = tmp[1];
            }
        },

        getParam : function(param, def){
               return (this._items[param] != undefined) ? this._items[param] : def;
        }


    };





    /**
     * CONTACTS MODULE
     * модуль контактов
     * */
    var contacts = {

        showManager : function(id){
            $.getJSON('/contacts/contacts/getEmployeeContacts?eid=' + id, {}, function(data){
                if(data.status == "ok")
                    User.dialog.setOptions({'width' : 400, 'height' : 200}).setContent(data.content).show();
            });
        }

    };


    return {
        'settings' : settings,
        'tpls' : tpls,
        'init' : init,
        'setSettings' : setSettings,
        /*'buyTour' : buyTour,*/
        /*'zebra' : zebra,*/
        //auth module
        'auth' : auth,
        //dialog module
        'dialog' : dialog,
        //order module
        'order' : order,
        //contacts module
        'contacts' : contacts,
        //request module
        'request' : request,
        //UI
        'ui' : ui
    };


    

})(jQuery);
