if (typeof Class !== 'undefined')
{
    var AjaxRequest = Class.create(
    {
        initialize: function(url, options)
        {
            this.url = url || '';
            this.options = options || {
            };

            this.onSuccess = Object.isFunction(this.options.onSuccess) ? this.options.onSuccess : Prototype.emptyFunction;
            this.onFailure = Object.isFunction(this.options.onFailure) ? this.options.onFailure : Prototype.emptyFunction;
            this.parameters = this.options.parameters || {
            };

            this.method = this.options.method || 'post';
            this.caching = this.options.caching || false;
            this.loader = this.options.loader || null;
            this.user = this.options.user || null;
            this.password = this.options.password || null;
            this.async = this.options.async || true;

            this.send();
        },
        send: function()
        {
            var req = new JsHttpRequest();
            req.onreadystatechange = function()
            {
                if (req.readyState == 4)
                {
                    this.onSuccess(req.responseJS,req.responseText);
                    
                    if (req.responseText)
                    {
                        try 
                        { 
                            $('ajaxDebug').update(req.responseText);
                        }                    
                        catch (e) 
                        {
                        
                        };
                    }
                }
            }

            var fx = req.onreadystatechange;
            req.onreadystatechange = fx.bind(this);

            req.loader = this.loader;
            req.caching = this.caching;
            req.open(this.method, this.url, this.async, this.user, this.password);

            req.send(this.parameters);
        }
    });
}

function sleep(naptime)
{
	naptime = naptime * 1000;
	var sleeping = true;
	var now = new Date();
	var alarm;
	var startingMSeconds = now.getTime();
	while(sleeping)
	{
		alarm = new Date();
		alarmMSeconds = alarm.getTime();
		if(alarmMSeconds - startingMSeconds > naptime)
		{ 
			sleeping = false;
		}
	}      
}

function getRes()
{
	return sg_lastAjaxResult;
}

function getLastAjax()
{
//	setTimeout("getRes()", 100);
	setTimeout("getRes()", 300);
	setTimeout("getRes()", 300);
	setTimeout("getRes()", 300);
	setTimeout("getRes()", 300);
	setTimeout("getRes()", 300);
	
//	sg_lastAjaxResult = null;
	return sg_lastAjaxResult;
}

function cblur(elm)
{
    if (elm.multiple)
        return true;
    
    var needElm;
    var founded = false;
    var doSearch = true;
    if (elm.form)
    {
        $(elm.form).getElements().each(function(el){
            if (!doSearch)
                return false;
            
            ob = el;
            isGood = ob.type != 'hidden' && !ob.disabled;
            pob = ob.parentNode;
            isGoodParent = pob.style.display != 'none';
            
            isGood = isGood && isGoodParent;
            
            if (founded && isGood)
            {
                needElm = el;
                doSearch = false;
            }
                
            if (el == elm)
                founded = true;
        });
        
        if (!doSearch)
            needElm.focus();
        else
            elm.form.focus();
    }
    else
    {
        document.body.focus();
    }
    
    return true;
}

function deleteFile(url_loc, className, recordID, db_field, typeStock, idToHide, messageConfirm)
{
    if (confirm(messageConfirm))
    {
        var req = new JsHttpRequest();
        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                if (req.responseJS)
                {
                    if (req.responseJS.deleted)
                    {
                        $(idToHide).hide();
                    }
                }

                if (req.responseText)
                {
                    $('debug').innerHTML = req.responseText;
                }
            }
        }

        var call = 'form.POST '+url_loc+'core/ajax/delete.php';
        req.open(null, call, true);
        req.send(
        {
            action: "deleteFile",
            ajax: "1",
            recordID: recordID,
            className: className,
            db_field: db_field,
            typeStock: typeStock
        });
    }
}

function getMessage(key)
{
	//, type = 'error', $accessType = null, $className = null, $action = 'item', $curLang = null
	
	var req = new JsHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            if (req.responseJS)
            {
                if (req.responseJS.message)
                {
                    sg_lastAjaxResult = req.responseJS.message;
                    return req.responseJS.message;
                }
            }

            if (req.responseText)
            {
                $('debug').innerHTML = req.responseText;
            }
        }
    }

    var script = 'core/ajax/common.php';
    
    var url = sg_isAdmin ? '../' + script : script;
    
    var call = 'form.POST ' + url;
    req.open(null, call, false);
    req.send(
    {
        action: "getMessage",
        ajax: "1",
        key: key
    });
}

// стандратное значение str - 'scrollbars=yes,left=10,top=10,status=yes,width=600,height=600'
function showImageReal(src, str)
{
    winbm=window.open('#','',str); 
    winbm.document.write('<html><head>');
    winbm.document.write('<meta http-equiv="content-type" content="text/html; charset=windows-1251">');
    winbm.document.write('</head>');
    winbm.document.write('<body>');                                        winbm.document.write('<img src="'+src+'">');
    winbm.document.write('</body>');
    winbm.document.write('</html>');
    winbm.focus(); 
    
    return false;
}

function getQueryVariable() 
{
    //полачаем строку запроса (?a=123&b=qwe) и удаляем знак ?
    var query = window.location.search.substring(1);  
    //получаем массив значений из строки запроса вида vars[0] = ‘a=123’;
    var vars = query.split("&");
    var arr = new Array(); 
    //переводим массив vars в обычный ассоциативный массив 
    for (var i=0;i<vars.length;i++) 
    {
        var pair = vars[i].split("=");
           arr[pair[0]] = pair[1];
    }
    
    return arr;
}

function updateOne(elm, isList, codeToEval)
{
    var req = new JsHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            if (req.responseJS)
            {
                elm.value = req.responseJS.value;
                eval(codeToEval);
            }

            if (typeof req.responseText != 'undefined') 
            {
                $("debug").innerHTML = req.responseText;
            }
        }
    }
    
    if (isList)
    {
        var exp = /^(.*?)\[(.*?)\]$/;
        
        var resultArray = exp.exec(elm.name);
        fieldNameToPost = resultArray[1];
        idToPost = resultArray[2];
    }
    else
    {
        fieldNameToPost = elm.name;
        idToPost = elm.form.id.value;
    }

    valueToPost = elm.value;
    
    var curForm = elm.form; 
    
    req.open(null, 'form.POST core/ajax/updateOne.php', true);
    
    obj = new Object();
    obj.ajax = "1";
    obj.fieldName = fieldNameToPost;
    obj.id = idToPost;
    obj[fieldNameToPost] = elm.value;
    obj.className = curForm.className.value; 
    // вот так тоже работает, но не всегда :) obj.className = curForm.className; 
    
    req.send(obj);
}

function updateForm(form, codeToEval)
{
    var req = new JsHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            if (req.responseJS)
            {
                eval(codeToEval);
            }

            if (req.responseText)
            {
                $("debug").innerHTML = req.responseText;
            }
        }
    }
    
    req.open(null, 'form.POST core/ajax/updateForm.php', true);
    
    req.send({ajax: "1", q: form});
}

function getSpecSymOnKeyDownCode(code)
{
    if (Prototype.Browser.IE)
    {
        switch (code)
        {
            case 192: res = "`";
            break;
            case 189: 
            case 109:
                res = "-";
            break;
            case 187: res = "=";
            break;
            case 220: res = '\\';
            break;
            case 219: res = "[";
            break;
            case 221: res = "]";
            break;
            case 186: res = ";";
            break;
            case 222: res = "'";
            break;
            case 188: res = ",";
            break;
            case 190:
            case 110: res = ".";
            break        
            case 191:
            case 111: res = "/";
            break;
            case 106: res = "*";
            break;
            case 107: res = "+";
            break;
            default: res = false;
        }
    }
    else
    {
        switch (code)
        {
            case 96: res = "`";
            break;
            case 45: res = "-";
            break;
            case 61: res = "=";
            break;
            case 92: res = '\\';
            break;
            case 91: res = "[";
            break;
            case 93: res = "]";
            break;
            case 59: res = ";";
            break;
            case 39: res = "'";
            break;
            case 44: res = ",";
            break;
            case 46: res = ".";
            break        
            case 47: res = "/";
            break;
            case 42: res = "*";
            break;
            case 43: res = "+";
            break;
            default: res = false;
        }
    }
    
    return res;
}

function isLetter_KeyDown(code)
{
    return (code >= 65 && code <= 90);
}

function isNumber_KeyDown(code)
{
    return (code >= 48 && code <= 57);
}

function isSpecSym_KeyDown(code)
{
    sym = getSpecSymOnKeyDownCode(code);
    res = (sym ? true : false);
    
    return res;
}

/*
 function displayKeyCode(evt)
 {
    // var textBox = getObject('txtChar');
     var charCode = (evt.which) ? evt.which : event.keyCode;
     $('genDebug').innerHTML = charCode;
     alert(charCode);
     textBox.value = String.fromCharCode(charCode);
     if (charCode == 8) textBox.value = "backspace"; //  backspace
     if (charCode == 9) textBox.value = "tab"; //  tab
     if (charCode == 13) textBox.value = "enter"; //  enter
     if (charCode == 16) textBox.value = "shift"; //  shift
     if (charCode == 17) textBox.value = "ctrl"; //  ctrl
     if (charCode == 18) textBox.value = "alt"; //  alt
     if (charCode == 19) textBox.value = "pause/break"; //  pause/break
     if (charCode == 20) textBox.value = "caps lock"; //  caps lock
     if (charCode == 27) textBox.value = "escape"; //  escape
     if (charCode == 33) textBox.value = "page up"; // page up, to avoid displaying alternate character and confusing people             
     if (charCode == 34) textBox.value = "page down"; // page down
     if (charCode == 35) textBox.value = "end"; // end
     if (charCode == 36) textBox.value = "home"; // home
     if (charCode == 37) textBox.value = "left arrow"; // left arrow
     if (charCode == 38) textBox.value = "up arrow"; // up arrow
     if (charCode == 39) textBox.value = "right arrow"; // right arrow
     if (charCode == 40) textBox.value = "down arrow"; // down arrow
     if (charCode == 45) textBox.value = "insert"; // insert
     if (charCode == 46) textBox.value = "delete"; // delete
     if (charCode == 91) textBox.value = "left window"; // left window
     if (charCode == 92) textBox.value = "right window"; // right window
     if (charCode == 93) textBox.value = "select key"; // select key
     if (charCode == 96) textBox.value = "numpad 0"; // numpad 0
     if (charCode == 97) textBox.value = "numpad 1"; // numpad 1
     if (charCode == 98) textBox.value = "numpad 2"; // numpad 2
     if (charCode == 99) textBox.value = "numpad 3"; // numpad 3
     if (charCode == 100) textBox.value = "numpad 4"; // numpad 4
     if (charCode == 101) textBox.value = "numpad 5"; // numpad 5
     if (charCode == 102) textBox.value = "numpad 6"; // numpad 6
     if (charCode == 103) textBox.value = "numpad 7"; // numpad 7
     if (charCode == 104) textBox.value = "numpad 8"; // numpad 8
     if (charCode == 105) textBox.value = "numpad 9"; // numpad 9
     if (charCode == 106) textBox.value = "multiply"; // multiply
     if (charCode == 107) textBox.value = "add"; // add
     if (charCode == 109) textBox.value = "subtract"; // subtract
     if (charCode == 110) textBox.value = "decimal point"; // decimal point
     if (charCode == 111) textBox.value = "divide"; // divide
     if (charCode == 112) textBox.value = "F1"; // F1
     if (charCode == 113) textBox.value = "F2"; // F2
     if (charCode == 114) textBox.value = "F3"; // F3
     if (charCode == 115) textBox.value = "F4"; // F4
     if (charCode == 116) textBox.value = "F5"; // F5
     if (charCode == 117) textBox.value = "F6"; // F6
     if (charCode == 118) textBox.value = "F7"; // F7
     if (charCode == 119) textBox.value = "F8"; // F8
     if (charCode == 120) textBox.value = "F9"; // F9
     if (charCode == 121) textBox.value = "F10"; // F10
     if (charCode == 122) textBox.value = "F11"; // F11
     if (charCode == 123) textBox.value = "F12"; // F12
     if (charCode == 144) textBox.value = "num lock"; // num lock
     if (charCode == 145) textBox.value = "scroll lock"; // scroll lock
     if (charCode == 186) textBox.value = ";"; // semi-colon
     if (charCode == 187) textBox.value = "="; // equal-sign
     if (charCode == 188) textBox.value = ","; // comma
     if (charCode == 189) textBox.value = "-"; // dash
     if (charCode == 190) textBox.value = "."; // period
     if (charCode == 191) textBox.value = "/"; // forward slash
     if (charCode == 192) textBox.value = "`"; // grave accent
     if (charCode == 219) textBox.value = "["; // open bracket
     if (charCode == 220) textBox.value = "\\"; // back slash
     if (charCode == 221) textBox.value = "]"; // close bracket
     if (charCode == 222) textBox.value = "'"; // single quote

    return false;

 }  */
 
function getIDFromListID(listID)
{
    var exp = /^(.*?)\[(.*?)\]$/;
    
    var resultArray = exp.exec(listID);
    id = resultArray[2];
    
    return id;
}

function eventCoreWrapper(func,event)
{
    elm = event.element();
    return func(elm);
}

function setSessionValue(mod, key, value)
{
    var req = new JsHttpRequest();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            if (req.responseText)
            {
                $('debug').innerHTML = req.responseText;
            }
        }
    }

    var call = 'form.POST /core/ajax/common.php';
    req.open(null, call, true);
    req.send(
    {
        action: "setSessionValue",
        ajax: "1",
        mod: mod,
        key: key,
        value: value
    });
}

function jsCheck()
{
    document.getElementById('jsWarning').style.display = 'none';
}

function cookieCheck()
{
    document.cookie = 'cookieCheckCode=cookieCheckCode';
    ex = /cookieCheckCode=cookieCheckCode/
    cookieEnabled = ex.test(document.cookie)
    
    if (!cookieEnabled) 
    {
        document.getElementById('cookieWarning').style.display = 'inline';
    }
}

function num_format(num)
{
    sep = ' ';
    
    num = Math.floor(num);
    num = String(num);
    
    newNum = ''
    
    for (var i=num.length-1 ;i>=0;i--) 
    {
        rest = ((num.length-i) % 3)
        
        newNum = (rest ? '' : sep ) + num.charAt(i) + newNum; 
    }

    return newNum;
}

function parseNum_format(num)
{
    newNum = ''
    
    for (var i=num.length-1 ;i>=0;i--) 
    {
        newNum = (num.charAt(i) === ' ' ? '' : num.charAt(i)) + newNum; 
    }

    return parseInt(newNum);
}

function getParentForm(elm)
{
    if (elm.tagName == 'FORM')
    {
        return elm;
    }
    else if (elm.tagName == 'BODY')
    {
        return false;
    }
    else
    {
        return getParentForm(elm.parentNode);
    }
}

function adminOne(parentElm, inputElm, params, func)
{
    regexp = /\[/;
    
    if (typeof( params.isList ) == 'undefined') // сделать setc
        params.isList = regexp.test(parentElm.id)
    
    adminOneInner(parentElm, inputElm, params, func)
}

function adminOneInner(parentElm, elm, params, func)
{
    funcTo = function (rjs,rtext)
    {
        is = Object.isFunction(func)
        
        if (is)
        {

            func(rjs,rtext)
        }
        
        if (rjs)
        {
            if (params.adminAction !== 'Save')
            {
                try 
                { 
                    $(parentElm).update(rjs.value_output); 
                }                    
                catch (e) 
                {
                
                };
            }
            else
            {
                if (params.adminAction !== 'Off' && (typeof rjs.dontRenew == 'undefined' || !rjs.dontRenew))
                {
                    try 
                    { 
                        elm.value = rjs.value_output; 
                    }
                    catch (e) 
                    {
                    
                    };
                }
            }
            
            // setTimeout('var oEditor = FCKeditorAPI.GetInstance("long"); oEditor.MakeEditable()',5000)
            
            if (params.adminAction == 'On')
            {
                try {$(params.fieldName+(params.isList ? '['+params.id+']' : '')).focus()} catch (e) {} ;
                
                if (rjs.fck)
                {
                    try { $('_fckToolbar').show() } catch (e) {};
                }
                // var oEditor = FCKeditorAPI.GetInstance(params.fieldName);
                // oEditor.MakeEditable();
            }
            else
            {
                
                // try { delete FCKeditorAPI; } catch (e) {};
                
                try { 
                    $('_fckToolbar').hide(); 
                    // $('_fckToolbar').innerHTML = ''  
                    
                    } catch (e) {};
                    
                // **** в рамках эксперимента такое проболвал location.href = location.href
                    
            }
            
            if (params.adminAction == 'Off')
            {
                // FCKeditorAPI = null;
                // parentElm.innerHTML = $('jest').innerHTML; 
            }
        }
    }
    
    hrefs = new Array()
    
    for (i in document.styleSheets) 
    {
         if (document.styleSheets[i].href)
            hrefs.push(document.styleSheets[i].href)
    }

    obj = params 

    obj.height = (typeof parentElm.offsetHeight !== 'undefined' ? parentElm.offsetHeight : null);
    obj.width = (typeof parentElm.offsetWidth !== 'undefined' ? parentElm.offsetWidth : null);
    
    // obj.cssClass = getParentForm(parentElm).firstDescendant().className
    // obj.cssStyle= getParentForm(parentElm).firstDescendant().style ? getParentForm(parentElm).firstDescendant().style.cssName : ''
    obj.cssSheets = hrefs.join(',')
    if (typeof obj.className == 'undefined') obj.className =  getParentForm(parentElm).className.value
    if (typeof obj.outID == 'undefined') obj.outID = getParentForm(parentElm).id
    
    if (params.adminAction !== 'On' && params.adminAction !== 'Off')
    {
        if (typeof(FCKeditorAPI) !== 'undefined')
        {
            fck = FCKeditorAPI.GetInstance(params.fieldName);
        }
        else
        {
            fck = false
        
        }
        
        if (fck)
        {
            obj.value = fck.GetData();
        }
        else if (elm.type !== 'checkbox' || elm.checked)
        {
            obj.value = elm.value;
        }
    }
    
    obj.action = 'adminOne';
    
    new AjaxRequest('form.POST '+sg_URL_CORE+'ajax/ajax.php', { parameters: obj, onSuccess: funcTo });
}

function getIDFromListID(listID)
{
    var exp = /^(.*?)\[(.*?)\]$/;

    var resultArray = exp.exec(listID);
    id = resultArray[2];
    
    return id;
}
