/**
 * Библиотека NextJS.   
 */
nextjs = {
msgError : null,
_xhr : null,
async : true,
method : 'POST',
timeout : 10000,
_requestFinish : false,
_requestAbort : false


};

nextjs.loader = {
stack : [],
stackCount : 0,

add : function(func) {
    if (typeof func != 'function') return;
    var count = this.stackCount;
    this.stack[count] = func;
    ++this.stackCount;
},

load : function() {
    var oldHandler = window.onload;
    window.onload = function() {
        if (typeof oldHandler == 'function') oldHandler();
        if (nextjs.loader.stack.length != 0) {
            for (var i = 0; i < nextjs.loader.stack.length; ++i) {
                nextjs.loader.stack[i]();
            }
        }
    }
}
};

nextjs._createXHR = function() {
    try { return new XMLHttpRequest(); } catch (e) {}
    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {}
    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (e) {}
    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {}
    return null;
};

nextjs.data = {
parseJSON : function(dataJSON) {
    var result = {};
    try {
        if (window.JSON !== undefined && window.JSON.parse !== undefined) result = JSON.parse(dataJSON);
        else result = eval('(' + dataJSON + ')');
    } catch (e) {
        //alert(e);
        return result;
    }
    return result;
},
htmlspecialchars : function(strData) { 
    strData = strData.toString();
    strData = strData.replace(/&/g, '&amp;'); 
    strData = strData.replace(/</g, '&lt;'); 
    strData = strData.replace(/>/g, '&gt;'); 
    strData = strData.replace(/"/g, '&quot;'); 
    strData = strData.replace(/\'/g, '&#039;');
    return strData; 
},
htmlspecialchars_decode : function(strData) {
    strData = strData.toString();
    strData = strData.replace(/&amp;/g, '&');
    strData = strData.replace(/&lt;/g, '<');
    strData = strData.replace(/&gt;/g, '>');
    strData = strData.replace(/&quot;/g, '"');
    strData = strData.replace(/&#039;/g, '\'');
    return strData;
},
encodeValue : function(strData) {
    var encodedStr;
    if (!window.encodeURIComponent) {
        encodedStr = escape(strData);
        encodedStr = encodedStr.replace(/@/g, '%40');
        encodedStr = encodedStr.replace(/\//g, '%2F');
        encodedStr = encodedStr.replace(/\+/g, '%2B');
    } else {
        encodedStr = encodeURIComponent(strData);
        encodedStr = encodedStr.replace(/~/g, '%7E');
        encodedStr = encodedStr.replace(/!/g, '%21');
        encodedStr = encodedStr.replace(/\(/g, '%28');
        encodedStr = encodedStr.replace(/\)/g, '%29');
        encodedStr = encodedStr.replace(/'/g, '%27');
    }
    return encodedStr.replace(/\%20/g, '+');
}
};

/**
 * Сетевые функции библиотеки.
 */
nextjs.network = {};

/**
 * Получить текст результата запроса.
 */
nextjs.network.send = function(url, options, data) {
    nextjs._requestFinish = false;
    nextjs._requestAbort = false;
    // Настройка.
    if (typeof options != 'object') options = {};
    var method = (options.method !== undefined && options.method.toUpperCase() == 'GET') ? 'GET' : nextjs.method;
    var async = (options.async !== undefined) ? options.async : nextjs.async;
    var timeout = (options.timeout !== undefined) ? options.timeout : nextjs.timeout;
    var response = null;
    var xhr = nextjs._createXHR();
    if (xhr == null) return;
    // Подготовка данных.
    var strData = '';
    if (typeof data == 'object') {
        for (var record in data) {
            var tmpValue;
            if (data[record] === false) tmpValue = 0;
            else if (data[record] === true) tmpValue = 1;
            else tmpValue = data[record]; 
            strData += record + '=' + nextjs.data.encodeValue(tmpValue) + '&';
        }
    }
    
    var pos = strData.lastIndexOf('&');
    if (pos != -1) strData = strData.substr(0, pos);
    // Формирование url, если GET запрос.
    if (method == 'GET') {
        var pos = url.lastIndexOf('?');
        if (pos != -1) url += '&' + strData;
        else url += '?' + strData;
    }
    
    // Отправка запроса.
    xhr.open(method, url, async);
    xhr.setRequestHeader('X-AJAX-Transport', 'NextJS');
    xhr.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 04:58:08 GMT');
    var sendData = null;
    if (method.toUpperCase() == 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        sendData = strData;
    }
    
    if (!async) {
        xhr.send(sendData);
        nextjs._requestFinish = true;
        response = xhr.responseText;
        return response;
    }
    
    // Установка времени ожидания запроса.
    if (timeout > 0) var timeoutID = window.setTimeout(function() { nextjs.network.abort(xhr); }, timeout);
    
    xhr.onreadystatechange = function() {
        if (nextjs._requestAbort == true) {
            if (options.onAbort) options.onAbort(xhr);
            return;
        }
        if (options.onreadystatechange) options.onreadystatechange(xhr);
        if (xhr.readyState == 4) {
            nextjs._requestFinish = true;
            if (timeoutID) clearTimeout(timeoutID);
            if (xhr.status == 200) {
                if (options.onSuccess) options.onSuccess(xhr);
            } else {
                if (options.onFailure) options.onFailure(xhr);
            }
        }
    };
        
    xhr.send(sendData);
};

nextjs.network.abort = function(xhr) {
    if (nextjs._requestFinish == false) {
        nextjs._requestAbort = true;
        xhr.abort();
        nextjs._requestFinish = true;
    }
};
