/**
 * @author 1
 */
var core = {



    /**
     * Показывает поле с сообщением об ошибке
     * @param {string} id элемента
     * @param {string} message Сообщение об ошибке
     */
    error: function(id, message){
        //$(id + "_error").html(message);
        core.message.build(message, 'info');
        $(id).addClass("inp_error");
    },
    /**
     * Убирает поле с сообщением об ошибке
     * @param {string} id элемента
     */
    unError: function(id){
        //$(id + "_error").html("");
        $(id).removeClass("inp_error");
    },
    /**
     * Проверка, заполнено ли поле
     * @param {bool} blur если тру, то это реакция на блюр
     * @param {string} field идентификатор поля
     */
    checkField: function(blur, field, field_name){
        var v_tmp = $(field).val();
        if (blur) {
            if (v_tmp.length == 0) {
                this.error(field, "Поле " + (field_name != null ? field_name : '') + " не должно быть пустым");
                return false;
            }
            else {
                this.unError(field);
                return true;
            };
                    }
        else {
            if (v_tmp.length > 0) {
                this.unError(field);
            };
                    };
        
            },
    
    init: function(){
	this.form.contact.init('#contact_form');
        this.ajax.init();
        var m = $('img').parents('a');
        var reg = /\.jpg|\.gif|\.jpeg|\.png/;
        $.each(m, function(i, val){
            href = $(val).attr('href');
            if (reg.test(href)){
                $(val).attr('rel', 'facebox').find('img').addClass('g_border');
            }
        });
      $('a[rel*=facebox][srel!=tuleni]').facebox({
        loading_image : site_url + '/media/img/facebox/loading.gif',
        close_image   : site_url + '/media/img/facebox/closelabel.gif'
      }).attr('srel', 'tuleni');        
    },
    
    
    /**
     * Загружает аяксом страничку с нужного урла и вставляет ее в указанное место
     * @param {string} href ссылка
     * @param {string} place обьект для jquery (например #register)
     * @param {function} callback функция для обратного вызова
     */
    getPage: function(href, place, callback, append){
        //place.html(progress);
        jid = place.attr('id')
        //core.progress.set(jid);
	if (! $.browser.msie ){
    	    place.block({  
                message: '<div><img src="/media/img/ajax-loader.gif"/></div><h1>Загрузка</h1>',  
                css: {'padding': '5px','border-left': '1px solid #707070','border-top': '1px solid #707070', 'border-right': '1px solid #414141', 'border-bottom': '1px solid #414141', 'background-color': '#494949'},
                overlayCSS:  {  
                    backgroundColor:'#000',  
                    opacity:        '0.6'  
                }                  
            });
	}    
        $.post(href, {
            ajax: "1"
        }, function(data){
            //core.progress.unset(jid)
            
	    if (! $.browser.msie) place.unblock();
            if (append != undefined){
                place.children("div").hide();
                place.append(data);
            }
            else place.html(data);
            if (callback != undefined) callback();
            core.init();
        });
        return false;
    },

    /**
     * Окончания для числительных ( 1 корова, 2,3,4 коровы, 5-20 коров)
     * @param {int} $i
     * @param {string} $one корова
     * @param {string} $three коровы
     * @param {string} $five коров
     */
    rep: function($i, $one, $three, $five){
        if ($i > 99) 
            $i = $i.substr(-2);
        if ($i > 4 && $i < 21) 
            return $five;
        if ($i > 9) 
            $i = $i.substr(-1);
        //return $i;
        if ($i == 0) 
            return $five;
        if ($i < 2) 
            return $one;
        if ($i < 5) 
            return $three;
        return $five;
    },
    /**
     *
     * @param {int} val
     * @param {string} somebody
     * @param {string} male
     * @param {string} female
     */
    sex: function(val, somebody, male, female){
        if (val == 0) 
            return sombody;
        if (val == 1) 
            return male;
        if (val == 2) 
            return female;
        return sombody;
    },
    
    progress: {
        one: '<img src="' + static_url + '/images/loader.gif" alt="обработка">',
        two: '<img src="' + static_url + '/images/loader2.gif" alt="обработка">',
        
        id: [],
        
        data: [],
        
        set: function(id){
            var key = core.searchValue(this.id, id);
            if (key != -1) {
                this.data[key] = $(id).html();
            }
            else {
                this.id.push(id);
                this.data.push($(id).html());
            }
            $(id).html(this.one);
        },
        
        unset: function(id){
            var key = core.searchValue(this.id, id)
            if (key != -1) {
                if (this.data[key] != '') {
                    $(this.id[key]).html(this.data[key]);
                    this.data[key] = '';
                }
            }
        }
    },
    
    searchValue: function(arr, value){
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == value) 
                return i;
        }
        return -1;
    },
    
    message: {
        data: [],
        
        add: function(message, stype){
            stype == undefined ? stype = 'done' : '';
            this.data.push({
                data: message,
                type: stype
            });
        },
        show: function(message, stype){
            if (message != undefined) {
                this.build(message, stype)
            }
            else {
                $.each(this.data, function(n, m){
                    core.message.build(m.data, m.type);
                });
                this.data = [];
            }
        },
        build: function(message, stype){
            switch (stype) {
                case 'done':
                    break;
                case 'error':
                    break;
                case 'info':
                default:
                    stype = 'info';
            }
            $.jGrowl(message, {
                theme: stype
            })
        }
    },
    
    
    ajax: {
        rel: 'ajax',
        callback: {
            id: [],
            data: []
        },
        
        hash: '',
        
        getUrl: function(){
            return document.location.hash;
        },
        
        setUrl: function(url){
            document.location.hash = '#' + url;
        },
        
        history: function(hash){
            $('a[history=' + hash + ']').click();
        },
        
        init: function(){
            //core.ajax.hash = core.ajax.getUrl().replace(/^.*#/, '');
            $.history.init(function(hash){
                if (hash) {
                    if (core.ajax.hash != hash) {
                        re = /news/;
                        re2 = /page/;
                        core.ajax.hash = hash;
                        if (re.test(hash)) {
                            var reg = /(\d+)/;
                            var arr = reg.exec(hash);
                            if (arr != null) {
                                a = '<a href="' +  site_url + 'news/all/' + arr[0] + '/" jid="' + arr[0] + '"></a>'; 
                                //alert(a);
                                showNews($(a).get(0))
                            }
                        }else if(re2.test(hash)){
                            var reg = /(\d+)/;
                            var arr = reg.exec(hash);
                            if (arr != null) {
                                a = '<a href="' +  site_url + 'news/all/?page=' + arr[0] + '" jid="' + arr[0] + '"></a>'; 
                                //alert(a);
                                showCategory($(a).get(0))
                            }                            
                        }else {
                        
                            $('a[@history=' + hash + ']').click();
                        }
                        
                        //alert('здесь будет действие ' + hash + ' 2 ' + core.ajax.hash)
                    }
                    
                    // restore ajax loaded state
                    //alert(hash);
                }
                else {
                    // start page
                    //alert('Пуста');
                }
                return false;
            });
            $("a[@history]").click(function(){
                var hash = $(this).attr('history');
                //var hash = this.href.replace(/^.*#/, '');
                //alert('Действие ' + hash);
                core.ajax.hash = hash;
                $.history.load(hash);
                //this.callback.id.push(hash);
                //this.callback.data.push(this.onclick);
                return false;
            });
        }
    },
    
    form: {
        contact: {
            form: null,
            init: function(form){
                this.form = $(form);
                if (this.form.length > 0) {
		    this.form.submit(function(){ return core.form.contact.submit()});
		    this.form.find('input[@name=sender]').blur(function(){core.form.contact.checkSender(true)});
		    this.form.find('input[@name=fullname]').blur(function() {core.form.contact.checkFullname(true)});
		    this.form.find('input[@name=message]').blur(function() {core.form.contact.checkMessage(true)})
                    this.form.find('input').focus(function(){
                        $(this).addClass('inp_select');
                    }).blur(function(){
                        $(this).removeClass('inp_select');
                    });
                }
            },
            checkFullname: function(blur){
                var field = this.form.find('[@name=fullname]').get(0);
                return core.checkField(blur, field, 'Ваше имя');
            },
            
            checkSender: function(blur){
                var field = this.form.find('[@name=sender]').get(0);
                var v_tmp = $(field).val();
                var reg = /\w+@\w+.\w/;
                if (core.checkField(blur, field, 'E-mail')) {
                    if (!reg.exec(v_tmp)) {
                        core.error('#mail', 'Проверьте e-mail - он некорректен.');
                        return false;
                    }
                    else {
                        core.unError("#mail");
                        return true;
                    };
                                    }
                else 
                    return false;
                
            },
            
            checkMessage: function(blur){
                var field = this.form.find('[@name=message]').get(0);
                return core.checkField(blur, field, 'Сообщение');
            },
            submit: function(form){
                var fn = this.checkFullname(true);
                var sender = this.checkSender(true);
                var message = this.checkMessage(true);
                if (fn && sender && message) {
                    return true;
                }
                else 
                    return false;
            }
        }
    
    }


}

