if(typeof bibil == 'undefined') bibil = {};

$(function(){
            
    setEvents();        
    
    $(".ajax-data").each(function(i, el){                            
        $(el).trigger("ajax-data-update");        
    })        
    
})


function errorHandler(res){
    //error
    opt = {header: 'Ошибка', body: '', type: 'err'};
    
    if(typeof res.res == 'object'){
        for(a in res.res){
            opt.body += "<p class='error-item'>"+res.res[a]+"</p>";
        }
    }else{
        opt.body = 'Произошла ошибка. Повторите попытку позже или обратитесь к администрации сайта.';
    }
    
    opt.id = 'errors-on-save-ajax-form';        
    popup(1, opt);
    
}

function setEvents(){
    
    $("form .submit").unbind();
    $("form .submit").click(function(){            
        var frm = $(this).parents("form").eq(0);            
        if(frm.size()){
            frm.submit();
        }
        return false;
    })    
        
    
    $("form.ajax").unbind();
    $("form.ajax").ajaxForm({
        dataType: 'json',
        beforeSerialize: function(){
            tinyProccess();
        },
        success: function(res, status, xhr, form){
            var onFunc = form.attr("onajaxsubmit");
            var onSuccess = form.attr("success");
            var evalcode = form.attr("eval");
            
            if(onFunc){
                window[onFunc].call(this, res, status, xhr, form);
            }else{            
                if(typeof res.res == 'object' || res.res == ''){                    
                    errorHandler(res);
                }else{
                    if(onSuccess && typeof window[onSuccess] == 'function'){
                        window[onSuccess].call(this, res, status, xhr, form)
                    }
                    
                    if(evalcode){
                        eval(evalcode);
                    }
                }
            }
        }
        
    });
    
    
    $('a.confirm, a.ajax, span.ajax').unbind();
    $('a.confirm, a.ajax, span.ajax').bind('click', function(ev, flg){
        
        me = this;        
        var conf = $(this).hasClass("confirm") ? true : false;
        
        if(typeof flg == 'undefined' && conf)
        {            
            popup(1, 'Предупреждение', 'Продолжить?', {
                buttons: true, 
                type: 'notice', 
                buttonOk: 'Да',
                buttonCallbackOk: function(opt){                    
                    popup(0, {id: opt.id});                    
                    $(me).trigger('click', 1);         
                }
            });      
            return false;
        }else{
            var href = $(this).attr("href");
            var callback = $(this).attr("callback");            
            var evalcode = $(this).attr("eval");            
            
            if(!callback){
                callback = $(this).attr("success");            
            }
            
            if(!$(this).hasClass("ajax")){
                if(href) window.location = href;
            }else{
                                
                $.get(href, function(res){
                    if(callback){
                    
                        if(typeof res.res == 'object' || res.res == ''){                            
                            errorHandler(res);
                        }else{                                                
                            if(typeof callback == 'string' && typeof window[callback] == 'function'){
                                window[callback].call(me, res);
                            }                        
                        }
                    }else{
                        if($(me).hasClass("ajax-inline")){                            
                            //$(me).before(res.res);
                            $(me).remove();
                        }
                    }
                    
                    if(evalcode){
                        eval(evalcode);
                    }                    
                })
                
                return false;
                
            }
        }
    })      
       
    
    $(".open-popup").unbind();
    $(".open-popup").click(function(){        
        var urlPage = $(this).attr("href") || null;
        var body = '', opt = {}, header = '';
        var me = this;                
        opt.buttons = true;
        opt.width = 600;
        var success = $(this).attr("success");
        
        if(urlPage){
            $.get(urlPage, function(res){
                
                if(typeof res.res == 'object' || res.res == ''){                            
                    errorHandler(res);                
                }else{
                    popup(1, header, res.res, opt);
                    if(success && typeof window[success] == 'function'){
                        window[success].call(me, res);
                    }
                    setEvents();                                        
                }
            })            
            
            return false;
        }
    })            

    $(".ajax-data").unbind("ajax-data-update");
    $(".ajax-data").bind("ajax-data-update", function(){                        
        var me = $(this);
        var url = $(this).attr("url");
        if(url){
            var postdata = $(this).html();
            $.post(url, {__serialized_data: postdata}, function(res){
                if(typeof res.res == 'object' || res.res == ''){                            
                    errorHandler(res);                
                }else{
                    me.html(res.res);
                    update_anim(me);
                    setEvents();
                    me.show();
                }
            });
        }            
    });
    
            
}



function get(params, func){
    $.ajax({
        url: '/index.php?init_mode=ajax',
        success: func,
        type: 'get',
        dataType: 'json',
        data: params
    });
}


function log(str){
    if(typeof console != 'undefined'){
        console.debug(str);
    }
    
}


$.ajaxSetup({
    url: '/index.php?init_mode=ajax',
    dataType: 'json',
    
    beforeSend: function(){
        popup(1, '', '<p class="ajax-loader"></p>', {width: 500, buttons: false, closeButton: false, transparent: true, overlay: false, id: 'ajax-loader'});
    },
   
        
    complete: function(){        
        //alert('x');
        popup(0, {id: 'ajax-loader'});
    },

    error: function(xhr, status, err){                
        detailErr = bibil.cfg.__debug ? '<br/><br/><b>Ошибка:</b> <i>'+status+'</i><br/><b>Ответ сервера</b><br/><textarea style="width:400px; height:200px; background:#000; border: 1px #000 solid; color:#fff">'+xhr.responseText+'</textarea>' : '';
        popup(1, 'Ошибка...', '<p style="text-align:center; padding:0px">Произошла ошибка при обработке запроса. Обратитесь к администрации сайта.'+detailErr+'</p>', {type: 'err'});        
    } 
})

function update_anim(el){
    el.toggleClass('updated-value');    
    el.everyTime(200, function(i){
        el.toggleClass('updated-value');        
    }, 3);

}



function redirect(url){    
    if(typeof url == 'undefined') url = window.location;
    window.location = url;
}


function tinyProccess(){
    if(typeof tinymce == 'undefined')  return;
    if(tinymce.editors.length > 0){
        
        tinymce.each(tinymce.editors, function(ed){                        
            try{
                var content = ed.getContent();                                        
                var el = ed.getElement();                                                                    
                el.value = content;                                                 
            }catch(e){
                //alert('tinyMCE error: '+e);
                log('tinyMCE error: '+e);
            }                           
        })  
        
        //delete all editors

    }    
}


function removeTiniEditors(){
    if(typeof tinymce == 'undefined')  return;
    if(tinymce.editors.length > 0){
        tinymce.each(tinymce.editors, function(ed){
            try{ ed.remove() }catch(e){};
        });               
    }
}

function setCookie(name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
