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

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){
    for (var i in options) KR_AJAX.options[i] = options[i];
    for (var i in parameters) KR_AJAX.set_var(i, parameters[i]);
    for (var i in methods_class) KR_AJAX[i] = methods_class[i];
    KR_AJAX.processResponse();
}

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 ajax(url, id){ajaxed({action : url, animation : false, elm : id}, {});}
function ajaxed(options, parameters){haja(options, parameters, {});}
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,
    nulls:function(){},
    history:{html:[], url:[], id:[], title:[], hash:[], blocks:[]},
    options:{action:'', method:'POST', elm:'', animation:true, add:false, addType:'ASC', history:false, async:true, user:'', passswd:''},
    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(){
        KR_AJAX.effect.loaded.init();
        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;}
        if ($.browser.msie){
            $.History.frame = KR_AJAX.create.element('iframe', {id : 'frame_history'}, {'display' : 'none'});
            KR_AJAX.iframeWrite($.History.frame.contentWindow.document, location.href);
        }
        $.History.check();
        $.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;
        }
    },
    
    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(){},

    processResponse:function(){
        if($.xmlhttp){                
            if($.options.history) $.options.idLayer = $.options.action.replaceAll('&', '[amp]');
            if($.options.animation==true) KR_AJAX.effect.loaded.show(true);
            $.onstartload();                        
            var RH = 'setRequestHeader';                                                                                            
            $.xmlhttp.open($.options.method.toUpperCase(), $.options.action, $.options.async, $.options.user, $.options.passswd);
            try {for (var i in $.headers) $.xmlhttp[RH](i, $.headers[i]);} catch (e){}
            $.xmlhttp.send($.options.vars+'&ajax=true');            
            $.xmlhttp.onreadystatechange = function(){
                if($.xmlhttp.readyState==4){
                    try{$.ext({result:$.xmlhttp.responseText, resultXML:$.xmlhttp.responseXML});} catch (e){$.result=''; $.resultXML='';};                    
                    $.insertHTML($.result);                    
                    $.onendload();
                    KR_AJAX.effect.loaded.hide();
                    $.onendload = $.nulls;
                    $.onstartload = $.nulls;
                }
            }
        }
    },

    insertHTML:function(response){
        if($.options.idLayer && ($.browser.msie || $.browser.safari)){
            if (KR_AJAX.Array.IndexOf($.history.hash, 'ajax:'+$.options.idLayer)==-1) $.history.hash[$.history.hash.length] = 'ajax:'+$.options.idLayer;
            var hashLinks = '';
            for(i=0;i<$.history.hash.length;i++) hashLinks += '<a href="#" name="'+$.history.hash[i]+'"></a>';
            response = hashLinks + response;
        }        
        var e = ($.options.elm) ? $$($.options.elm) : KR_AJAX.create.element('div', {id:'def_con'}, {'display':'none'});
        var result = $.parse.script(response);        
        response = result.text;
        var scripts = result.script;        
        response = $.parse.style($.parse.link($.parse.title(response)));
        if (response.length<3) return false;
        inner = e.innerHTML;
        if ($.options.add!=false) e.innerHTML = ($.options.addType=='ASC') ? e.innerHTML+response:response+e.innerHTML;
        else e.innerHTML = response;
        for(var i=0;i<scripts.length;i++) if(scripts[i]) document.body.appendChild(scripts[i]);        
        if($.options.idLayer){
            if(KR_AJAX.Array.IndexOf($.history.url, location.href)==-1) $.History.set(inner, location.href, e);                
            location.hash = '#ajax:'+($.options.idLayer.replace('http://'+location.host+location.port+'/', '')).replace('#', '[diez]');
            if($.browser.msie) KR_AJAX.iframeWrite($.History.frame.contentWindow.document, location.href);
            $.href = location.href;
            if(KR_AJAX.Array.IndexOf($.history.url, location.href)==-1) $.History.set(response, location.href, e);
        }
        $.options = {action:'', method:'POST', elm:'', animation:true, add:false, addType:'ASC', history:false, async:true, user:'', passswd:''}
    },     
        
    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, "");
        },

        script:function(text){
            var reg=/<script.*?>(.|[\r\n])*?<\/script>/ig
            var str = reg.exec(text);
            var arr = [];
            var scripts = [];
            if (str!=null){
                arr = new Array(str.shift());
                while(str) {
                    str = reg.exec(text);
                    if (str!=null) arr.push(str.shift());
                }
                if(arr){
                    for(var uni=0; uni<arr.length;uni++) {    
                        text = text.replace(arr[uni], '');
                        ind1 = arr[uni].toLowerCase().indexOf('<script');
                        ind2 = arr[uni].indexOf('>', ind1 + 1);
                        ind3 = arr[uni].toLowerCase().indexOf('</'+'script>', ind2 + 1);                        
                        if(ind1!=-1 && ind2!=-1) src = this.search(arr[uni].substring(ind1, ind2 + 1), 'src'); else var src = '';                        
                        if(ind3!=-1) scr = arr[uni].substring(ind2 + 1, ind3); else scr = '';                        
                        if(src.length>0) scripts[uni] = KR_AJAX.create.element('script', {src:src}, {}, false);                                                
                        if(scr.length>0) try{eval(scr)} catch (e){};
                    }
                }
            }
            return {text:text, script:scripts};
        },

        link:function(text){
            var reg=/<link(.*?)>/ig
            while(text.toLowerCase().indexOf('<link')!=-1){
                arr = reg.exec(text);
                if(arr){
                    $.include.style(this.search(arr[1], 'href'));
                    text = text.replace(arr[0], "");
                }
            }
            return text;
        },

        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);
        }
    },

    History : {
        frame : null,
        scroll : false,
        set : function(html, url, elm){
            $.history.html[$.history.html.length] = html;
            $.history.url[$.history.url.length] = url;
            $.history.id[$.history.id.length] = elm;
            $.history.title[$.history.title.length] = document.title;
            $.history.blocks[$.history.blocks.length] = [$$('rightcol')?($$('rightcol').style.display?$$('rightcol').style.display:''):'', $$('leftcol')?($$('leftcol').style.display?$$('leftcol').style.display:''):''];
        },

        check : function(){            
            if(location.href.indexOf('[diez]')!=-1 && !this.scroll){
                scroll2elm(name2id(location.href.substring(location.href.indexOf('[diez]'), location.href.length).replace('[diez]', '')));
                this.scroll = true;
            }
            var h = ($.browser.msie && !$.browser.opera) ? $.History.frame.contentWindow.document.body.innerText : location.href;
            load_module();
            if (h!=$.href){                
                var id = KR_AJAX.Array.IndexOf($.history.url, h);
                if(id!=-1){                     
                    $$($.history.id[id]).innerHTML = $.history.html[id];
                    $.href = h;
                    document.title = $.history.title[id]; //history.go(-1);
                    if($$('rightcol')) $$('rightcol').style.display = $.history.blocks[id][0];
                    if($$('leftcol')) $$('leftcol').style.display = $.history.blocks[id][1];
                }
            }
            $.timer = setTimeout("KR_AJAX.History.check()", 10);
        }
    },

    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;
        }
    },
         
    effect:{
        loaded:{
            init:function(){
                var layer = $.create.element('div', {id:'loading_layer', className:'fone_ajax'}, {display:'none'});
                layer.style.height = ((document.body.scrollHeight>=KR_AJAX.window.height())?document.body.scrollHeight:KR_AJAX.window.height())+'px';
                $.set.opacity(layer, 60);
                var loading = $.create.element('div', {id:'loading', className:'loading_ajax'}, {display:'none'});
                $.set.opacity(loading, 95);
                loading.innerHTML = "<center><b>"+KR_AJAX.action.text+"</b><br /><img src=\"" + $.action.image + "\" alt=\"\"></center>";
                this.update();
            },

            show:function(loader){if($$('loading_layer')) $$('loading_layer').style.display = 'block'; if(loader && $$('loading')) $$('loading').style.display = 'block';},
            hide:function(){if($$('loading_layer')) $$('loading_layer').style.display = 'none'; if($$('loading')) $$('loading').style.display = 'none';},

            update : function(){
                if($$('loading_layer') && $$('loading')){
                    w_height = (document.body.scrollHeight>$.window.height()) ? document.body.scrollHeight : $.window.height();
                    $$('loading_layer').style.height = w_height+'px';
                    $$('loading').style.top = 12+'%';
                    setTimeout("KR_AJAX.effect.loaded.update()", 1);
                }
            }
        },

        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;}
    },

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