if (window.com == null) {
    window.com ={};
}
if (window.com.intrice == null) {
    window.com.intrice ={};
}
function log(s) {
    //$('#debug').append(s+'<br />');
    //console.log(s);
}
com.intrice.ajax = function(myName, urlPrefix, jsessionId, lang, defaultPage) {
    this.myName = myName;
    this.jsessionRegExp = com.intrice.ajax.jsessionRegExp = /;jsessionid=[\dA-Fa-f]*/;
    this.isAjaxReady = location.pathname.replace(this.jsessionRegExp, '') == myName;
    var title_to = document.title.indexOf('|');
    if (title_to == -1) {
        title_to = document.title.indexOf('--');
        if (title_to == -1) {
            title_to = document.title.length;
        } else {
            title_to += 3;
        }
    } else {
        title_to += 2;
    }
    this.document_title = document.title.substring(0, title_to);
    this.urlPrefix = urlPrefix;
    var prefix = urlPrefix.indexOf('/') == 0 ?
                 urlPrefix.substring(1) :
                 urlPrefix;
    if (prefix.lastIndexOf('/') == prefix.length-1) {
        prefix = prefix.substring(0, prefix.length-1);
    }
    var urlPrefixRegExp = this.urlPrefixRegExp = new RegExp('^.*?\\/'+prefix+'\\/');
    this.alreadyAdded = {};
    this.loaders = [];
    this.jsessionId = jsessionId;
    this.lang = lang;
    this.defaultPage = defaultPage;
    com.intrice.ajax.self = this;
    if (location.hash == '' && this.isAjaxReady && this.defaultPage) {
        this.getContent(this.defaultPage);
    }
    if (this.isAjaxReady) {
        this.bindHistory();
    } else {
        $("a[rel='history']").attr('href', function(i){
            var hash = this.href;
            var matches = hash.match(com.intrice.ajax.jsessionRegExp);
            var jsessionParam = matches ? matches[0] : '';
            hash = hash.replace(urlPrefixRegExp, '')
                    .replace(/\.html/, '')
                    .replace(com.intrice.ajax.jsessionRegExp, '');
            if ( $.browser.msie && parseInt($.browser.version) == 6 ) {
                hash = hash.replace(/\?/, '_');
            }
            if (hash != '') {
                return myName + jsessionParam + "#" + hash;
            } else {
                return myName + jsessionParam;
            }
        });
    }
    if (location.hash && this.isAjaxReady && location.hash != this.defaultPage) {
        var pageToLoad = location.hash.replace(/^#/, '');
        this.pageWasLoaded = null;
        this.getContent(pageToLoad);
        this.pageWasLoaded = pageToLoad;
    }
    // vars for closure:
    var isAjaxReady = this.isAjaxReady;
    var jsessionRegExp = this.jsessionRegExp;
    var urlPref = this.urlPrefix;
    var redirectFunc = function (link) {
        var hash = location.hash;
        var params = this.paramsToStr();

        if (hash && hash != '' && isAjaxReady) {
            hash = hash.replace( jsessionRegExp, '');
            var matches = hash.match(/\?.*$/);
            var paramsHash = matches ? matches[0] : '';
            matches = hash.match(jsessionRegExp);
            var jsessionParam = matches ? matches[0] : '';
            var newLink = urlPref+hash
                    .replace(/.*?#/, '')
                    .replace(/:.*$/, '')
                    .replace(/\?.*$/, '') +".html" +
                    jsessionParam +
                ((params.length > 0) ? "?" + params : "") +
                ((paramsHash.length > 0) ? paramsHash : "");
            window.location.replace(newLink);
        } else {
            if (link) {
                window.location.replace(link);
            } else {
                window.location.replace(this.getLink());
            }
        }
    };
    if (request) request.redirect = redirectFunc;
    else if (com.intrice.request) com.intrice.request.prototype.redirect = redirectFunc;
};

com.intrice.ajax.prototype.bindHistory = function() {
    var urlPrefixRegExp = this.urlPrefixRegExp;
    var alreadyAdded = this.alreadyAdded;
    var getContent = this.getContent;
    log("bindHistory: "+this.urlPrefixRegExp);
    $("a[rel='history']").attr('href', function(i) {
        var hash = this.href;
        if (hash.indexOf("#")>-1) return hash;
//        var matches = hash.match(this.jsessionRegExp);
//        var jsessionParam = matches ? matches[0] : '';
        hash = hash.replace(urlPrefixRegExp, '').replace(/\.html/, '')
                .replace(com.intrice.ajax.jsessionRegExp, '');
        if ( $.browser.msie && parseInt($.browser.version) == 6 ) {
            hash = hash.replace(/\?/, '_');
        }
        if ( ! alreadyAdded[hash]) {
            $.History.bind(hash, com.intrice.ajax.self.getContent);
            alreadyAdded[hash] = true;
        }
        return /*myName +*/ "#" + hash;
    });
    log("/bindHistory");
};

com.intrice.ajax.prototype.changeLocalLinks = function(vurl) {
    log("changeLocalLinks");
    if (this.isAjaxReady) {
        $("a[rel='local']").attr('href', function(i) {
            return '#' + vurl + this.href.replace(/^.*?#/, ':')
                    .replace(com.intrice.ajax.jsessionRegExp, '');
        });
        $("a[rel='local-anchor']").attr('name', function(name) {
            return vurl + ':' + this.name;
        });
    }
    log("/changeLocalLinks");
};

com.intrice.ajax.prototype.changeTitle = function (title) {
    $('#ajax-target-title').html(title);
};

/*com.intrice.ajax.prototype.onAjaxSuccess = function(data, vurl) {
    log("onAjaxSucces: "+vurl);
    var dom = $(data);
    var self = com.intrice.ajax.self;
    self.changeTitle($('#ajax-title', dom).html());
//    $('#ajax-target-title').text($('#ajax-title', dom).text());
//        $('#ajax-target-breadcrubs').html($('#ajax-breadcrubs', dom).html());
    $('#ajax-target-content').html($('#ajax-data-content', dom).html());
    var submenu = $('#ajax-submenu-content', dom).html();
    if (submenu && submenu.length > 0) {
        $('#ism-faq').html(submenu);
    }

    if (vurl) self.changeLocalLinks(vurl);
    self.bindHistory();
    document.title =
        self.document_title + $('#ajax-title', dom).text();
    //if (vurl && window.location.hash != vurl) window.location.hash = vurl;
    for (var i=0, max=self.loaders.length; i < max; ++i) {
        if (self.loaders[i][0](window.location.hash)) {
            self.loaders[i][1](window.location.hash);
            break;
        }
    }
    self.stopLoaderAnimation();
    log("/onAjaxSucces");
};*/
com.intrice.ajax.prototype.onAjaxSuccess = function(data, vurl) {
    log("onAjaxSucces: "+vurl);
    var content_index = data.indexOf('/*=*content*=*/');
    var submenu_index = data.indexOf('/*=*menu*=*/');
    var d = eval('('+data.substring(0,submenu_index < 0? content_index: submenu_index)+')');
    if (d.relogin_function) {
        d.relogin_function();
        return;
    }
    var submenu = submenu_index >= 0 ?
            data.substring(submenu_index + 12, content_index) :
            '';
    var content = data.substring(content_index + 15, data.indexOf('/*=*end*=*/'));
    $('#ajax-target-title').html(d.title_img.length > 0? d.title_img: d.title);
    $('#ajax-target-content').html(content);
    if (submenu_index >= 0) {
        $('#ism-faq').html(submenu);
    }
    var self = com.intrice.ajax.self;
    document.title = self.document_title + d.title.replace(/&rsquo;/, "'");
    if (d.page_function) {
        d.page_function();
    }
    if (vurl) self.changeLocalLinks(vurl);
    self.bindHistory();
    for (var i=0, max=self.loaders.length; i < max; ++i) {
        if (self.loaders[i][0](window.location.hash)) {
            self.loaders[i][1](window.location.hash);
            break;
        }
    }
    self.stopLoaderAnimation();
    log("/onAjaxSucces");
};

com.intrice.ajax.prototype.registerPageLoader = function(cond, func) {
    this.loaders.push([cond, func]);
};

com.intrice.ajax.prototype.startLoaderAnimation = function() {
    $('#ajax-loader').html('<img src="/i/ajax_loader.gif" alt="" />');
};
com.intrice.ajax.prototype.stopLoaderAnimation = function() {
    $('#ajax-loader').html('');
};

com.intrice.ajax.prototype.getContent = function(hash) {
    var self = com.intrice.ajax.self;
    if (self.pageWasLoaded == hash) {
        self.pageWasLoaded = null;
        return true;
    }
    log("getContent: "+hash);
    self.startLoaderAnimation();
    var vurl = (hash && hash != '') ?
            hash.replace(/:.*$/, '') :
            self.defaultPage? self.defaultPage: '';
    if ( $.browser.msie && parseInt($.browser.version) == 6 ) {
        vurl = vurl.replace(/_/, '?');
    }
    var realUrl = new String(self.urlPrefix);
    if (vurl.indexOf('?') > 0) {
        realUrl += vurl.replace(/\?/, '.html'+self.jsessionId+'?');
    } else {
        realUrl += vurl + (vurl != ''? '.html': '')+self.jsessionId;
    }
    $.ajax({
        url: realUrl,
        data: {ajax: 'true', LANG: self.lang},
        dataType: 'html',
        success: function(data) {
            self.onAjaxSuccess(data, vurl);
        }
    });
    log("/getConten");
    return true;
};
com.intrice.ajax.prototype.getFormDataUtil = function(form) {
    var dataHash = {};
    var elements = form.elements;
    if (elements) {
        for (var i=0, max=elements.length; i<max; ++i) {
            var el = elements[i];
            if (el.tagName.toLowerCase() == 'select') {
                dataHash[el.name] = el.options[el.selectedIndex].value;
            } else if (el.type.toLowerCase() == 'checkbox') {
                dataHash[el.name] = el.checked ? "on" : "";
            } else {
                dataHash[el.name] = el.value;
            }
        }
    }
    return dataHash;
};


