if (typeof jQuery !== 'undefined')
{
	$j = jQuery;
}

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 makeToggler(elm, params)
{
	$(params.togglableID).toggle();
	elm[params.attrToChange] = $(params.togglableID).visible() ? params.hideWord : params.showWord;
	setSessionValue(typeof(params.sessionType) !== 'undefined' ? params.sessionType : 'onClose' ,params.sessionName,!$(params.togglableID).visible());

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

		try
		{
			if (!doSearch)
				needElm.focus();
			else
				elm.form.focus();
		}
		catch (e)
		{

		}
	}
	else
	{
		document.body.focus();
	}

	return true;
}

function deleteFile(url_loc, className, recordID, db_field, idToHide, messageConfirm, forStreamName)
{
	if (confirm(messageConfirm))
	{
		funcTo = function(rjs)
		{
			if (rjs.deleted)
			{
				$(idToHide).hide();
			}
		}

		var call = 'form.POST '+sg_URL_CORE+'ajax/ajax.php';

		obj =
		{
			action: "deleteFile",
			recordID: recordID,
			className: className,
			db_field: db_field,
			forStreamName: forStreamName
		};

		new AjaxRequest(call, { parameters: obj, onSuccess: funcTo });

	}
}

/*
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;
				}
			}
		}
	}

	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",
		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 showImageReal(src, str)
{
	var im_pre = new Image();
	im_pre.src = src;

	winbm=window.open('#','',str);
	winbm.document.write('<'+'!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"'+'>');
	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 id="img" src="'+src+'" onload="window.resizeTo(this.width + window.outerWidth - window.innerWidth, this.height + window.outerHeight - window.innerHeight)">');
	winbm.document.write('</body>');
	winbm.document.write('</html>');
	winbm.focus();
	img = winbm.document.getElementById('img')
	// $(img).hide()
	// observe('load',onLoadRis)

	// $(im_pre).observe('load',function (){alert(99); alert(winbm)})

	return false;
}

function onLoadRis()
{
	alert(234)
	return;
} */

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


/** опора на name. Т.е. принимается соглашение, что elm из листа идет с именем name[xx], с айтема - без скобок. **** Насколько это правильно - ну, вопрос некоторый.. Т.е. может быть вообще надо считать, что все является листом */
function updateOne(elm, isList, func)
{
	params = new Object();

	if (isList)
	{
		var exp = /^(.*?)\[(.*?)\]$/;

		var resultArray = exp.exec(elm.name);
		params.fieldName = resultArray[1];
		params.id = resultArray[2];
	}
	else
	{
		params.fieldName = elm.name;
		params.id = elm.form.id.value; // разобраться, надо ли
	}

	var curForm = elm.form;

	parentElm = elm.parentNode
    params.adminAction = 'Save'; 
    params.isList = isList;    

	adminOneInner(parentElm, elm, params, func)
}

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.checklist)
        // обрабатываем список чекбоксов
        {
            obj.value = new Object();

            arr = new Array()
            arr[0] = "input"

            var j = 0
            Selector.findChildElements($(elm.checklist),arr).each(
            function(el)
            {
                if (el.checked)
                {
                    obj.value[j] = el.value
                    j++
                }
            })
        }
        else if (elm.type == 'select-multiple')
        {
            obj.value = new Object();
            opts = elm.options

            var j = 0
            for(i=0;i<opts.length;i++)
            {
                if (opts[i].selected)
                {
                    obj.value[j] = opts[i].value
                    j++
                }
            }
        }
		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 updateForm(form, funcTo)
{
	var newInp = document.createElement('input');
	newInp.type = 'hidden';
	newInp.name = 'action';
	newInp.value = 'updateForm';

	$(form).insert({bottom: newInp});

	new AjaxRequest('form.POST  '+sg_URL_CORE+'ajax/ajax.php', { parameters: {q: form}, onSuccess: funcTo });

	return false;
}

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 isSpecSym_ForIntKeyDown(code, pos)
{
	if (typeof pos == 'undefined') { pos = false }

	sym = getSpecSymOnKeyDownCode(code);
	res = false || (!pos && (sym == '-'))

	return res;
}

function isSpecSym_ForFloatKeyDown(code, pos)
{
	if (typeof pos == 'undefined') { pos = false }

	sym = getSpecSymOnKeyDownCode(code);
	res = sym == '.' || sym == ',' || (!pos && (sym == '-'))

	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 getIDFromoutID(outID)
{
	var exp = /^(.*?)\[(.*?)\]$/;

	var resultArray = exp.exec(outID);
	id = resultArray[2];

	return id;
}

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

function setSessionValue(mod, key, value, funcTo)
{
	if (typeof funcTo == 'undefined') funcTo = function(){}

	obj =
	{
		action: "setSessionValue",
		mod: mod,
		key: key,
		value: value
	};
	
	call = 'form.POST '+sg_URL_CORE+'ajax/ajax.php';

	new AjaxRequest(call, { parameters: obj, onSuccess: funcTo});
}

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 getParentForm(elm)
{
	if (elm.tagName == 'FORM')
	{
		return elm;
	}
	else if (elm.tagName == 'BODY')
	{
		return false;
	}
	else
	{
		return getParentForm(elm.parentNode);
	}
}

function num_format(num, dec)
{
	if (typeof dec == 'undefined') dec = sg_DEFAULT_PRICE_DECIMAL;

	sep = ' ';

	num += ''; // приводим к строке
	parts = num.split(".");

	snum = parts[0];

	newNum = ''

	for (var i=snum.length-1 ;i>=0;i--)
	{
		rest = ((snum.length-i) % 3)

		newNum = (rest ? '' : sep ) + snum.charAt(i) + newNum;
	}

	frac = (typeof parts[1] !== 'undefined' ? parts[1] : '')
	newFrac = frac + '0'.times(dec-frac.length)

	res = newNum + (newFrac.length > 0 ? '.' : '') + newFrac
	return res;
}

function parseNum_format(num)
{
	newNum = ''

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

	return parseFloat(newNum);
}

function disallow(elm, evt, mod, pos)
{
	if (typeof mod == 'undefined') { mod = 'int' }
	if (typeof pos == 'undefined') { pos = false }

	// для keydown!!!!
	var charCode = (evt.which) ? evt.which : event.keyCode

	switch (mod)
	{
		case 'int': res = !isLetter_KeyDown(charCode) && !isSpecSym_KeyDown(charCode) || isSpecSym_ForIntKeyDown(charCode, pos);
		break;

		case 'float': res = ( !isLetter_KeyDown(charCode) && !isSpecSym_KeyDown(charCode) ) || isSpecSym_ForFloatKeyDown(charCode, pos);
		break;

		default: res = false;
	}

	return res;
}

function makeDopFileStreamElm(wrapDivId)
{
	wrapDiv = $(wrapDivId)
	lastDiv = wrapDiv.childElements().last()

	newDiv = lastDiv.cloneNode(true)

	$(wrapDivId).appendChild(newDiv)

	re = /(\d*)\*Div/
	ms = lastDiv.id.match(re)

	n = parseInt(ms[1])+1

	str = lastDiv.id
	res = str.replace(re,n+'*Div')
	newDiv.id = res

	res = str.replace(re,n+'*')
	newDiv.select('input').first().name = res

	// newTr.innerHTML = tr.innerHTML

	/*
	var newTd = document.createElement('td');
	$(newTr).insert({top: newTd}) */

	// newTr = Object.clone(tr);
	// tb.insert({bottom: newTr});

	// tb.childNodes.push(newTr)

	return;
}

function disableRubrs()
{
	$$('tr[id*="rubr"]').each(function(n){ n.hide() })
	$$('input[id*="rubr"]').each(function(n){ n.value = ''})

	return;
}

if (typeof Class !== 'undefined')
{
	var langClass = Class.create(
	{
		initialize: function(opt)
		{
			this.data = {};

			opt = opt || {};
			this.ph = opt.ph || '#';
		},

		add: function()
		{
			var key = arguments[0];
			var text = arguments[1];
			var ph = this.ph;
			this.data[key] = text;
			if (arguments.length > 2)
			{
				var args = $A(arguments);
				args.shift();
				args.shift();

				this.replace(key, args, false);
			}
		},

		get: function()
		{
			var args = $A(arguments);
			var key = args.shift();

			if (args.length > 0)
			{
				var res = this.replace(key, args, true);
				if (res)
				{
					return res;
				}
			}

			return typeof this.data[key] !== 'undefined' ? this.data[key] : key;
		},

		replace: function(key, args, ret)
		{
			ret = typeof ret !== 'undefined' && ret ? true : false;
			var ph = this.ph;
			var text = this.data[key];
			args.each(function(val){
				var valKey, valRepl;

				$H(val).each(function(v){
					valKey = v.key;
					valRepl = v.value;
				})

				var re = new RegExp(ph+valKey+ph, "m");
				text = text.replace(re,valRepl);
			})
			if (ret)
			{
				return text;
			}
			else
			{
				this.data[key] = text;
			}
		}
	});
}

function getArraySelectCount(arr,isCheckbox)
{
	var count = 0;
	for(i=0;i<arr.length;i++)
	{
		if ((isCheckbox ? arr[i].checked : arr[i].selected))
			count++;
	}

  	return count; 
}

