//////////////////////////////////////////////
// Kasseler CMS: Content Management System  //
// =========================================//
// Copyright (c)2007-2009 by Igor Ognichenko//
// http://www.kasseler-cms.net/             //
//////////////////////////////////////////////
var agent = navigator.userAgent.toLowerCase();
var j = jQuery.noConflict();

function getCookie(name){
    var cookie = " " + document.cookie; var search = " " + name + "="; var setStr = ''; var offset = 0; var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);
            if (end == -1) end = cookie.length;
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    return setStr;
}

function haja(options, parameters, methods_class){
    var o = {}; 
    for(var i in options) o[i] = options[i];
    for (var i in methods_class) KR_AJAX[i] = methods_class[i];
    o.data = parameters; 
    KR_AJAX.processResponse(o);
}

function ajax(url, id){ajaxed({action : url, animation : false, elm : id}, {});}
function ajaxed(options, parameters){haja(options, parameters, {});}
function setCookie(name, value, expires, path, domain, secure){document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires:"") + ((path) ? "; path=" + path:"") + ((domain) ? "; domain=" + domain:"") + ((secure) ? "; secure":"");}
function $$(element) {return (typeof element === "string") ? document.getElementById(element):element;}
function $V(element) {return (typeof element === "string") ? document.getElementById(element).value:element.value;}
function $S(element) {return (typeof element === "string") ? document.getElementById(element).style:element.style;}
function hack_opera(){if(navigator.userAgent.toLowerCase().indexOf("opera") != -1) KR_AJAX.set.atrib({style:'position:absolute;left:-1px;top:-1px;opacity:0;width:0px;height:0px', alt:'', src:''}, document.body.appendChild(document.createElement('img')));}
function isElement(object){return object && object.nodeType == 1;}
function isArray(object){return object != null && typeof object == "object" && 'splice' in object && 'join' in object;}
function isHash(object){return object instanceof Hash;}
function isFunction(object){return typeof object == "function";}
function isObject(object){return typeof object == "object";}
function isString(object){return typeof object == "string";}
function isNumber(object){return typeof object == "number";}
function isUndefined(object){return typeof object == "undefined";}

Array.prototype.remove = function(obj) {var a = []; for (var i=0; i<this.length; i++) if (this[i] != obj) a.push(this[i]); return a;}
String.prototype.trim = function(){ return this.replace(/\s*((\S+\s*)*)/, "$1").replace(/((\s*\S+)*)\s*/, "$1");}
String.prototype.replaceAll = function(s1, s2) {return this.split(s1).join(s2)}
String.prototype.endWith=function(value, caseSensitive){if (caseSensitive) if (this.toLowerCase().substring(this.length-value.length,this.length)==value.toLowerCase()) return true; else if (this.substring(this.length-value.length,this.length)==value) return true; return false;}
String.prototype.startWith=function(str, caseSensitive){if (caseSensitive) if (this.toLowerCase().substring(0,str.length)==str.toLowerCase()) return true; else if (this.substring(0,str.length)==str) return true; return false;}

if (!window.KR_AJAX) KR_AJAX = {};
KR_AJAX.extend = function(dest, src, skipexist){var overwrite = !skipexist; for (var i in src) if (overwrite || !dest.hasOwnProperty(i)) dest[i] = src[i]; return dest;};

(function($){$.extend($, {
    varsion:'1.0.2',
    charset:'UTF8',
    status:0,
    href:'',
    timer:Object,
    isReady:false,
    ajaxed:false,
    nulls:function(){},
    options:{action:'', method:'POST', elm:'#hide_conteiner', animation:true, addType:'', async:true, user:'', passswd:'', cache:false, dataType:'html', contentType:'application/x-www-form-urlencoded', data:'', global:true},
    cache:{link:[], script:[]},
    action:{image : 'includes/images/loading/loading_zindex.gif', text : 'Загрузка. Пожалуйста, подождите...'},
    alert:"Your browser does not support the expanded opportunities of management of a site, we urgently recommend to replace a browser.",
    headers:{'Content-Type':'application/x-www-form-urlencoded; Charset='+$.charset, 'AJAX_ENGINE':'KR_AJAX', 'HTTP_X_REQUESTED_WITH':'XMLHttpRequest', 'If-Modified-Since':'Sat, 1 Jan 2000 00:00:00 GMT'},
    onload:false,
    
    browser : {
        safari:agent.indexOf("safari")!=-1,
        opera:agent.indexOf("opera")!=-1,
        msie:(agent.indexOf("msie")!=-1) && (agent.indexOf("opera")==-1),
        mozilla:(agent.indexOf("mozilla")!=-1) && ((agent.indexOf("webkit")==-1) && (agent.indexOf("compatible")==-1))
    },

    init:function(){
        if($.browser.msie){try {$.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {$.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (err) {$.xmlhttp = null;}}}
        if(!$.xmlhttp && typeof XMLHttpRequest != "undefined") $.xmlhttp = new XMLHttpRequest();
        if(!$.xmlhttp) alert($.alert);
        else {$.isReady = true; $.onload = true;}
        $.loadedHash();
    },

    document : {
        getElementsByClassName:function(className, parent, tag, callBack){
            var r = [], re, e, i;
            if(!parent) parent = document;
            re = new RegExp("(^|\\s)"+className+"(\\s|$)");
            e = $.document.getElementsByTagName(tag, parent);
            for(i = 0; i < e.length; ++i) {
                if(re.test(e[i].className)) {
                    r[r.length] = e[i];
                    if(callBack) callBack(e[i]);
                }
            }
            return r;
        },
        
        getElementsByTagName:function(tag, parent){
            var list = null;
            tag = tag || '*';
            parent = $$(parent) || document;
            if(typeof parent.getElementsByTagName != 'undefined') {
                list = parent.getElementsByTagName(tag);
                if(tag=='*' && (!list || !list.length)) list = parent.all;
            } else {
                if (tag=='*') list = parent.all;
                else if(parent.all && parent.all.tags) list = parent.all.tags(tag);
            }
            return list || [];
        },
        
        getElementById:function(e){
            if(typeof(e)=='string') {
                if(document.getElementById) e=document.getElementById(e);
                else if(document.all) e=document.all[e];
                else e=null;
            }
            return e;
        }
    },
    
    getPosition:function(e){
        var left = 0;
        var top  = 0;
        while(e.offsetParent){
            left += e.offsetLeft;
            top  += e.offsetTop;
            e = e.offsetParent;
        }
        left += e.offsetLeft;
        top  += e.offsetTop;
        return {x:left, y:top}
    },
    
    loadedHash:function(){if(location.href.indexOf('ajax:')!=-1) if (this.isReady) ajaxed({elm:'ajax_content', action:location.href.substring(location.href.indexOf('#'), location.href.length).replace('#ajax:', '').replaceAll('[amp]', '&'), animation:false}, {});},
    set_var:function(name, value){$.options.vars += "&"+name+"="+encodeURIComponent(value);},
    ext:function(methods){for (var i in methods) $[i] = methods[i];},
    addEvent:function(obj, name, handler){
        if(!$.isReady) if (obj.attachEvent) obj.attachEvent('on' + name, handler); else obj.addEventListener(name, handler, false);
        else {
            if($.onload) handler();
            else {var timeout = $.timeonload = setInterval(function(){if($.onload){try {handler(); clearInterval(timeout);} catch (e){}}}, 100);}
        }    
    },
    onstartload:function(){},
    onendload:function(){},
    oninsert:function(){},

    processResponse:function(o){
        j(document).ready(function(){
            for(var i in $.options) if(o[i]==null) o[i] = $.options[i];
            if(o.elm!='' && o.elm[0]!='.' && o.elm[0]!='#') o.elm = '#'+o.elm;
            if(o.action=='') return false;
            j.ajax({type: o.method, url: o.action, scriptCharset:'UTF-8', cache: o.cache, dataType: o.dataType, async: o.async, username: o.user, password: o.passswd, contentType: o.contentType, data: o.data, global: o.global,
                success: function(msg){
                    $.result=msg, 
                    $.onendload(msg); $.ajaxed = false;
                    if(o.elm!='') {if(o.addType=='') j(o.elm).html(msg); else if(o.addType=='prepend') j(o.elm).prepend(msg); else if(o.addType=='append') j(o.elm).append(msg);}
                    $.oninsert(msg);
                    $.onendload = $.onstartload = $.oninsert = function(){};
                },
                error:function(xhr, txt, err){},
                complete:function(XMLHttpRequest, textStatus){if(o.animation==true) KR_AJAX.animation('hide'); $.ajaxed = false;},
                beforeSend:function(XMLHRequest){if(o.animation==true) KR_AJAX.animation('show'); $.onstartload(); $.ajaxed = true;}
            });
        });
    },

    parse:{
        search:function(text, string){
             if(text.toLowerCase().indexOf(string)==-1) return '';
             var reg=/([\s]*)([\s\S]*?)([\s|>]+)/i
             ind = text.toLowerCase().indexOf(string)+string.length;
             var arr=reg.exec(text.substring(text.length, text.toLowerCase().indexOf("=", ind)+1));
             if(!arr) return '';
             var s = arr[2].trim();
             if(s[0]=="'" || s[0]=='"') s = s.substring(s.length, 1);
             if(s[s.length-1]=="'" || s[s.length-1]=='"') s = s.substring(s.length-1, 0);
             return s;
        },

        inds : function(html, start, end){
            var ind = Array(html.toLowerCase().indexOf(start), html.indexOf('>', html.toLowerCase().indexOf(start) + 1), html.toLowerCase().indexOf(end, html.indexOf('>', html.toLowerCase().indexOf(start) + 1) + 1));
            var atrib = {param : html.substring(ind[0]+ind[0].length, ind[1]), text : html.substring(ind[1]+1, ind[2]), tag : html.substring(ind[0], ind[2]+end.length)}
            return {ind1 : ind[0], ind2 : ind[1], ind3 : ind[2], param : atrib.param, text : atrib.text, tag : atrib.tag};
        },

        title:function(text){
            if(text.toLowerCase().indexOf("<title>")==-1) return text;
            var reg=/<title>(.*?)<\/title>/g
            var arr=reg.exec(text);
            document.title=arr[1];
            return text.replace(reg, "");
        },

        style:function(text){
            var styles = '';
            ind = this.inds(text, '<style', '</style>');
            while(ind.ind1 != -1 && ind.ind3 != -1){
                styles += ind.text;
                text = text.replace(ind.tag, '');
                ind = this.inds(text, '<style', '</style>');
            }
            if (styles!='' && styles!='undefined'){
                var style = KR_AJAX.create.element('style', {type:'text/css'}, {}, false);
                if (style.styleSheet) style.styleSheet.cssText = styles;
                else if (KR_AJAX.browser.mozilla || KR_AJAX.browser.opera) style.innerHTML = styles;
                else style.appendChild(document.createTextNode(styles));
                document.getElementsByTagName('head')[0].appendChild(style);
            }
            return text;
        }
    },

    include : {
        script : function(url, handler){
            $.onload = false;
            var script = KR_AJAX.create.element('script', {src:url}, {});
            script.onerror = script.onload = script.onreadystatechange = function(){
                var t = this;
                if (!t.loaded && (!t.readyState || t.readyState == 'loaded' || t.readyState == 'complete')){
                    t.loaded = 1;
                    if(handler && isFunction(handler)) try {handler();} catch (e){}
                    $.onload = true;
                    t.onerror = t.onload = t.onreadystatechange = null;
                    t.inprocessTO = setTimeout(function(){
                        t.inprocess = 0;
                    }, 10);
                }
            }
        },

        style : function(url){
            var link = KR_AJAX.create.element('link', {href:url, rel:'stylesheet'}, {}, false);
            document.getElementsByTagName('head')[0].appendChild(link);
        }
    },

    set:{
        opacity:function(elm, opacity){$$(elm).style.opacity = opacity/100; $$(elm).style.filter = "alpha(opacity="+opacity+")";},
        style:function(style, elm){for(var i in style){try{if(elm.style[i]!='undefined' && style[i]!='undefined') elm.style[i] = style[i];} catch(e) {}}},
        atrib:function(a, el){for (var i in a) el[i] = a[i];}
    },

    create:{
        element:function(name, ext, style, append){
            if(!append) append=true;
            var el = document.createElement(name);
            for (var i in ext) el[i] = ext[i];
            for (var i in style) try {el.style[i] = style[i]} catch(er) {};
            if(append!=false) document.body.appendChild(el);
            return el;
        }
    },

    window:{
        height:function(){return (window.innerHeight ? window.innerHeight:(document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body.offsetHeight))},
        width:function(){return (window.innerWidth ? window.innerWidth:(document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body.offsetWidth));},
        docheight:function(){return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;},
        docwidth:function(){return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;},

        scrollY:function(){
            var scrollY = 0;
            if(document.documentElement && document.documentElement.scrollTop) scrollY = document.documentElement.scrollTop;
            else if(window.pageYOffset) scrollY = window.pageYOffset;
            else if(window.scrollY) scrollY = window.scrollY;
            else if(document.body && document.body.scrollTop) scrollY = document.body.scrollTop;
            return scrollY;
        },

        scrollX:function(){
            var scrollX = 0;
            if(document.documentElement && document.documentElement.scrollLeft) scrollX = document.documentElement.scrollLeft;
            else if(window.pageXOffset) scrollX = window.pageXOffset;
            else if(window.scrollX) scrollX = window.scrollX;
            else if(document.body && document.body.scrollLeft) scrollX = document.body.scrollLeft;
            return scrollX;
        }
    },
    
    animation:function(type){
        if(!j(".fone_ajax").get(0)){
            j("<div class='fone_ajax'><div class='loading_ajax'><img src='includes/images/loading/effect.gif' alt='Loading...' /><br /></div></div>").prependTo("body");
            j(window).bind("resize", function(){j(".fone_ajax").css("height", j(window).height());});
        }
        j(".fone_ajax").css("height", j(document).height());
        j(".fone_ajax").fadeTo('slow', type=='show'?0.70:0.0);
        if(type=='hide') setTimeout(function(){j(".fone_ajax").css("display", 'none');}, 700)
    },
         
    effect:{
        swicher:{
            show:function(e, height, step){steps = height/step; var sh = steps; for(var i=1;i<=step;i++){setTimeout("KR_AJAX.effect.swicher.set('"+e+"', "+sh+")", 10*i*1.2); sh+=steps;}},
            hide:function(e, height, step){steps = height/step; var sh = height-steps; for(var i=1;i<=step;i++){setTimeout("KR_AJAX.effect.swicher.set('"+e+"', "+sh+")", 10*i*1.2); sh-=steps;}},
            set:function(e, height){$$(e).style.height = height+'px';}
        }
    },

    Array:{
        IndexOf:function(array, elm){for (var i=0; i<array.length; i++) if (array[i]==elm) return i; return -1;}
    },
    
    ajaxForm : {
        defaults:{selector:'.ajaxform', onInit:null, onStartSend:null, onEndSend:null, element:['select', 'input', 'textarea'], resultType:'html', elm:'#hide_conteiner', nullOnSend:false, data:{}},
        
        init:function(options){
            o = j.extend(this.defaults, options);
            j(document).ready(function(){
                j(o.selector).submit(function(e){
                    KR_AJAX.ajaxForm.send(o, this); return false;
                });
                if(o.onInit!=null) o.onInit();
                j('input.submit').after("<img style='visibility: hidden;' class='form_sender' src='includes/images/loading/small.gif' alt='Loading...' />");
            });
        },
        
        send:function(o, obj){
            if(KR_AJAX.ajaxed==false){
                haja({effect:false, elm:o.elm, action:obj.action, method:obj.method, dataType:o.resultType}, j(obj).serializeArray(), {
                    onstart:function(){j('.form_sender').css('visibility','visible'); if(o.onStartSend!=null) o.onStartSend(o);},
                    onend:function(msg){if(o.onEndSend!=null) o.onEndSend(o, msg); if(o.nullOnSend==true) o.onEndSend = o.onStartSend = null; j('.form_sender').css('visibility','hidden');}
                });
            }
        }
    },

    iframeWrite:function(doc, text){doc.open(); doc.write(text); doc.close(); doc.body.innerHTML = text;}
})
})(KR_AJAX)

j(document).ready(function(){j('body').append('<div style="display:none;" id="hide_conteiner"></div>');});

