/* base javascript functions for EDMR */
var linked_key='';
var linked_list='';
var linked_label='';
var linked_remove='';
var __temp = null;

function displayOn(obj) {
	if ( !obj.tagName )	{
		obj = document.getElementById(obj);
	}
	if ( obj ) {
		obj.style.display = 'block';
	}
	return false;
}
function displayOff(obj) {
	if ( !obj.tagName )	{
		obj = document.getElementById(obj);
	}
	if ( obj ) {
		obj.style.display = 'none';
	}
	return false;
}

function displayOnOff(obj) {
	if ( !obj.tagName )	{
		obj = document.getElementById(obj);
	}
	if ( obj ) {
		if ( !obj.style || !obj.style.display || obj.style.display == 'none')
		{
			obj.style.display = 'block';
		} else {
			obj.style.display = 'none';
		}
	}
	return false;
}

function displayOnOffById(id) {
	var obj = document.getElementById(id);
	if ( obj ) {
		if ( !obj.style || !obj.style.display || obj.style.display == 'none')
		{
			obj.style.display = 'block';
		} else {
			obj.style.display = 'none';
		}
	}
	return false;
}

function setCheckByValue(id, name, val, onlyone) {
	var frm = $(id);
	if ( frm.tagName == "FORM" )
	{
		if ( !name )
		return fasle;
		for(var i=0; i<frm.elements.length; i++) {
			if (frm.elements[i].name != name) {
				continue;
			}
			//alert(frm.elements[i].name);
			if ( frm.elements[i].value == val )
			{
				frm.elements[i].checked = true;
			}
			if ( onlyone && frm.elements[i].value != val )
			{
				frm.elements[i].checked = false;
			}
		}
	}
	return false;
}
function checkLenth(id, maxlen, indicate, period) {
	var objInd = null;
	if ( !document.getElementById(id) ) {
		return;
	}
	if ( !maxlen ) {
		maxlen = 1024;
	}
	if ( !period ) {
		period = 0.2;
	}
	if ( indicate ) {
		objInd = document.getElementById(indicate);
	}

	new Form.Element.Observer(
	id,
	period, // 200 milliseconds
	function(el, value){
		var str = new String(value);
		if ( str.length > maxlen ) {
			alert('Сообщение не должно быть длиннее '+maxlen+' символов!');
			el.value = str.substr(0,maxlen-1);
			if ( objInd ) {
				objInd.innerHTML = 1;
			}
		} else {
			if ( objInd ) {
				objInd.innerHTML = maxlen - str.length;
			}
		}
	}
	);
}

function url_skip_ts(url) {
	var str = new String(url);
	var re = new RegExp("([\?&])t=[0-9]+");
	return str.replace(re, '');
}

function add_ts(param) {
	var ts = new Date();

	if ( param ) {
		param=param.merge({ t : ts.getTime() });
	} else {
		param = new Hash({ t : ts.getTime() });
	}

	return param;
}

function visibilityByClass(list, vilible) {
	if ( list && list.length ) {
		list.each( function(stl) {
			var elems = document.getElementsByClassName(stl);
			if ( elems && elems.length ) {
				elems.each( function(el) {
					el.style.visibility = vilible;
				});
			}
		});
	}
}

function comments_save(obj, param)
{
	try
	{
		document.getElementById("cmnts_form").disabled = true;

		obj = document.getElementById(obj);
		if ( !obj.id ) return false;
		if (!obj.value) {alert('Нельзя добавлять пустой комментарий.');return false;}

		url = '/comments/save.html';
		url = url_skip_ts(url);
		param=param.merge({ __feedback : obj.id });
		param = add_ts(param);
		new Ajax.Request(url, {
			method: 'post',
			parameters: param,
			onSuccess : function(response) {
				obj.value='';
				document.getElementById("cmnts_form").disabled=false;
				comments_page(response.responseText,'lastcomment');
				return false;
			},
			onFailure: function()
			{
				alert('Не получилось сохранить комментарий. Попробуйте чуть позже.');
				document.getElementById("cmnts_form").disabled=false;
			},
			evalScripts : true
		});
		return false;
	}
	catch (e) {alert(e);}
}

function sendmess(obj, ispost, url, param)
{
	if ( !obj.tagName )	{
		obj = document.getElementById(obj);
	}
	if ( !obj.id )	{
		return false;
	}
	ts = add_ts(new Hash());
	url = url + ts['t'] + '/';

	if ( ispost ) {
		ispost='POST';
		obj.innerHTML = 'подождите...';
		if ( document.all ) {
			visibilityByClass(new Array('srch-box1', 'srch-box2'), 'hidden');
		}
	} else {
		ispost='GET';
	}
	if ( !param ) {
		param = new Hash();
	}

	new Ajax.Updater(obj.id, url, {
		asynchronous : false,
		method: ispost,
		parameters: param,
		onSuccess : function(response) {
			//alert(pnode.innerHTML);
			//obj.innerHTML = response.responseText;
			return false;
		},
		evalScripts : true
	}
	);
	return false;
}

var sendmess4_link = null;

function sendmess4(obj, ispost, url, param, mode, link_obj)
{
	closemess4();
	sendmess4_link = link_obj;

	var holder = jQuery(obj.parentNode).find('.popup-holder-2');
	if (cmnts_isuid)
	{
		ts = add_ts(new Hash());
		url = url + ts._object['t'] + '/';
		if ( ispost )ispost='POST';
		else ispost='GET';

		if ( !param ) param = new Hash();

		new Ajax.Request(url, {
			method: ispost,
			asynchronous : false,
			parameters: param,
			onSuccess: function(response) {
				holder.html(response.responseText);
				if (mode == 1) jQuery(holder).css('top',(jQuery(obj).position().top)+'px').css('left',(jQuery(obj).position().left)+'px');
				if (mode == 2) jQuery(holder).css('top',(jQuery(obj).position().top)+'px').css('left',(jQuery(obj).position().left-10)+'px');
				jQuery(holder).css('display','block');
			}
		});
		return false;
	}
	else
	{
		new Ajax.Request("/profile/msg_regist.html", {
			method:'GET',
			asynchronous : false,
			parameters: add_ts(new Hash()),
			onSuccess: function(response) {
				holder.html(response.responseText);
				if (mode == 1) jQuery(holder).css('top',(jQuery(obj).position().top)+10+'px').css('left',(jQuery(obj).position().left)+20+'px');
				if (mode == 2) jQuery(holder).css('top',(jQuery(obj).position().top+7)+'px').css('left',(jQuery(obj).position().left-10)+'px');
				jQuery(holder).css('display','block');
			},
			evalScripts : true
		});

		return false;
	}
}

function closemess4()
{
	jQuery('.popup-holder-2').css('display','none').html('');
}

function msgRegistAction(typei, obj)
{
	if (typei==1)
	{
		var ts = new Date();
		var param=new Hash({email: $('cr_email').value, newpassword1: $('cr_newpassword1').value});
		new Ajax.Updater(obj,"/profile/msg_regist.html?ts="+ts.getTime(), {
			asynchronous : false,
			parameters: param,
			method: 'post',
			evalScripts : true
		});
	}
	else if (typei==2)
	{
		new Ajax.Updater(obj,"/profile/add/msg_regist.html", {
			asynchronous : false,
			parameters: add_ts(new Hash()),
			method: 'get',
			evalScripts : true
		});
	}
	else if (typei==3)
	{
		var ts = new Date();
		var param=new Hash({email: $('cr_email').value, newpassword1: $('cr_newpassword1').value, newpassword2: $('cr_newpassword2').value});
		new Ajax.Updater(obj,"/profile/add/msg_regist.html?ts="+ts.getTime(), {
			asynchronous : false,
			parameters: param,
			method: 'post',
			evalScripts : true
		});
	}
	return false;
}

function comments_regist_check(obj,param)
{
	if (comments_div) $(comments_div).innerHTML='';
	comments_div='comment_regist';
	if (!$(obj).value.length) return false;
	if (cmnts_isuid) return comments_save(obj,param);

	new Ajax.Updater('comment_regist', "/profile/comment_regist.html", {
		asynchronous : false,
		parameters: add_ts(new Hash()),
		method: 'get',
		evalScripts : true
	});
	return false;
}

function comments_regist_check3(obj,param)
{
	if (comments_div) $(comments_div).innerHTML='';
	comments_div='comment_regist';
	if (cmnts_isuid) return comments_save(obj,param);

	new Ajax.Updater('comment_regist', "/profile/comment_regist.html?version=3", {
		asynchronous : false,
		parameters: add_ts(new Hash()),
		method: 'get',
		evalScripts : true
	});
	return false;
}



function comment_regist_types(typei,version)
{
	var version = (version != undefined)?3:0;
	var url = '';

	if (typei==1)
	{
		var ts = new Date();
		var param=new Hash({email: $('cr_email').value, newpassword1: $('cr_newpassword1').value});
		if (version == 3) url = "/profile/comment_regist.html?version=3&ts="+ts.getTime();
		else url = "/profile/comment_regist.html?ts="+ts.getTime();

		new Ajax.Updater(comments_div, url, {
			asynchronous : false,
			parameters: param,
			method: 'post',
			evalScripts : true
		});
	}
	else if (typei==2)
	{
		if (version == 3) url = "/profile/add/comment_regist.html?version=3";
		else url = "/profile/add/comment_regist.html";

		new Ajax.Updater(comments_div, url, {
			asynchronous : false,
			parameters: add_ts(new Hash()),
			method: 'get',
			evalScripts : true
		});
	}else if (typei==3)
	{
		var ts = new Date();
		if (version == 3) url = "/profile/add/comment_regist.html?version=3&ts="+ts.getTime();
		else url = "/profile/add/comment_regist.html?ts="+ts.getTime();

		var param=new Hash({email: $('cr_email').value, newpassword1: $('cr_newpassword1').value, newpassword2: $('cr_newpassword2').value});
		new Ajax.Updater(comments_div, url, {
			asynchronous : false,
			parameters: param,
			method: 'post',
			evalScripts : true
		});
	}
	return false;
}

function feedback(obj, param) {
	if ( !obj.tagName )	{
		obj = document.getElementById(obj);
	}
	if ( !obj.id )	{
		return false;
	}

	url = '/x/feedback.php';
	url = url_skip_ts(url);
	if ( param ) {
		param=param.merge({ __feedback : obj.id });
	} else {
		param = new Hash({__feedback : obj.id});
	}
	param = add_ts(param)

	var wheight=(window.innerHeight)?window.innerHeight: ((document.all)?document.body.offsetHeight:null);
	if ( $('lastcomment') && $('lastcomment').offsetTop) {
		wheight = $('lastcomment').offsetTop;
	}

	new Ajax.Updater(obj.id, url, {
		asynchronous : false,
		method: 'post',
		parameters: param,
		onSuccess : function(response) {
			//alert(obj.tagName);
			if (obj.tagName == 'TEXTAREA' ) {
				obj.value = '';
			} else {
				obj.innerHTML = response.responseText;
			}
			window.scrollBy(0,wheight);
			return false;
		},
		evalScripts : true
	});
	return false;
}

function clear_obj(obj) {
	if ( !obj.tagName ) {
		return false;
	}
	obj.innerHTML = '';
	return false;
}

function mailback(obj, id) {
	url = '/x/mailback.php';
	url = url_skip_ts(url);
	param = new Hash({__getmail : id});
	param = add_ts(param)

	req = new Ajax.Request(url, {
		asynchronous : false,
		method: 'post',
		parameters: param,
		onSuccess : function(transport) {
			obj.href = transport.responseText;
		}
	});
	return;
}

function rich_list_update(url, id, act, value, param) {
	var obj = $(id);
	if ( obj && obj.id ) {
		url = url_skip_ts(url);
		var ts = new Date();
		if ( param ) {
			param=param.merge({ t : ts.getTime() });
		} else {
			param = new Hash({ t : ts.getTime() });
		}
		param=param.merge({ 'act' : act, 'val' : value, 'cont' : obj.innerHTML });
		new Ajax.Updater(obj.id, url, {
			method: 'post',
			parameters: param,
			evalScripts: true
		});
	}
	return false;
}

function rich_list_observ(url, id, value, param) {
	var obj = $(id);
	if ( obj && obj.id ) {
		obj.style.display = 'none';
		obj.innerHTML = '';
		if ( !value || !url ) {
			return false;
		}
		url = url_skip_ts(url);
		var ts = new Date();
		if ( param ) {
			param=param.merge({ t : ts.getTime() });
		} else {
			param = new Hash({ t : ts.getTime() });
		}
		param=param.merge({ q : value });
		/*
		if ( param['__ctrl'] ) {
		Form.Element.disable(param['__ctrl']+'_value');
		}
		*/

		new Ajax.Updater(obj.id, url, {
			method: 'post',
			parameters: param,
			evalScripts: true
		});
	}
	return false;
}

function updateItemByUrl(klass, url) {
	var obj = $(klass+'_content');
	obj.innerHTML = '';

	var ts = new Date();
	var str = new String(url);
	var re = new RegExp("([\?&])t=[0-9]+");
	url = str.replace(re, '');

	new Ajax.Updater(obj.id, url, {
		method: 'get',
		parameters: { t : ts.getTime() },
		evalScripts: true
	});
}

function updateClassByItem(item, klass) {
	var src = $(item);
	if ( src && src.innerHTML) {
		var arr = document.getElementsByClassName(klass);
		for( index = 0; index < arr.length; index++ ) {
			if ( arr[index].id != src.id ) {
				arr[index].innerHTML = src.innerHTML;
			}
		}
	};
}

function updateLabel(obj, pid) {
	if ( (label = prompt('Название', obj.innerHTML)) ) {
		obj.innerHTML = label;
		while( obj.parentNode && obj.parentNode.tagName != 'BODY' ) {
			if (obj.parentNode.className == 'linkedlist' && obj.parentNode.id ) {
				updateClassByItem(obj.parentNode.id, obj.parentNode.className);
				new Ajax.Request(linked_label, {
					parameters: {'core_linkedfiles[pid]' : pid, 'core_linkedfiles[title]' : label},
					method: 'post'
				});
				break;
			}
			obj = obj.parentNode;
		}
	}
	return false;
}

function removeLinked(obj, pid) {
	if ( (confirm('Вы уверены, что хотите удалить объект?')) ) {
		while( obj.parentNode && obj.parentNode.tagName != 'BODY' ) {
			if (obj.parentNode.className == 'linkedthumb') {
				obj.parentNode.style.display = 'none';
			}
			if (obj.parentNode.className == 'linkedlist' && obj.parentNode.id ) {
				updateClassByItem(obj.parentNode.id, obj.parentNode.className);
				new Ajax.Request(linked_remove, {
					parameters: {'core_linkedfiles[pid]' : pid, 'core_linkedfiles[key]' : linked_key},
					method: 'post'
				});
				break;
			}
			obj = obj.parentNode;
		}
	}
	return false;
}

function insertLinkedImg (url,width,height,title) {
	html = "<img src=\""+url+"\"";
	if ( width && width!="") {
		html += " width=\""+width+"\"";
	}
	if (height && height!="") {
		html += " heigth=\""+height+"\"";
	}
	html += " />";
	tinyMCE.execCommand('mceInsertContent',false,html);
	return false;
}

function insertLinkedImg1 (url,width,height,title) {
	html = "<img src=\""+url+".thumb.jpg\"";
	if ( width && width!="") {
		html += " width=\""+width+"\"";
	}
	if (height && height!="") {
		html += " heigth=\""+height+"\"";
	}

	html += ' alt="insertLinkedImg"';

	if (title && title!="") {
		html += ' title="'+title+'"';
	}

	html += " />";
	tinyMCE.execCommand('mceInsertContent',false,html);
	return false;
}

function insertLinkedFile (url,title) {
	html = "<a href=\""+url+"\"";
	if ( title && title!="") {
		html += " title=\""+title+"\">"+title+"</a>";
	} else {
		html += ">"+url+"</a>";
	}
	tinyMCE.execCommand('mceInsertContent',false,html);
	return false;
}

function insertLinkedFlash (url,width,height) {
	if ( !width )
	width = "";
	if ( !height )
	height = "";
	h = "<img src=\"" + tinyMCE.getParam("theme_href") + "/images/spacer.gif\" class=\"mceItemFlash\" title=\"src:'"+url+"',width:'100',height:'100'\" width=\"100\" height=\"100\" align=\"center\" />";

	//html = "<embed src=\""+url+"\" width=\""+width+"\" height=\""+height+"\" type=\"application/x-shockwave-flash\" play=\"true\" loop=\"true\" menu=\"true\"></embed>";
	//alert(h);
	tinyMCE.selectedInstance.execCommand('mceInsertContent',false,h);
	return false;
}

function linkedUpload(url, field, klass) {
	JsHttpRequest.query(
	url, // backend
	{
		// pass a text value
		'str': document.getElementById("str_"+field).value,
		// path a file to be uploaded
		'filename': document.getElementById("upload_"+field)
	},

	// Function is called when an answer arrives.
	function(result, errors) {
		// Write errors to the debug div.
		if ( errors )
		{
			//document.getElementById("debug").innerHTML = errors;
			alert(errors);
		} else {
			if ( klass )
			{
				updateItemByUrl(klass, linked_list);
				alert('Файл добавлен');
			}
		}
		// Write the answer.
		document.getElementById("str_"+field).value = "";

		document.getElementById("upload_"+field).value = "";
		if ( document.getElementById("upload_"+field).value != "" )
		{
			// Very stupid code, but IE couldn't replace input.value
			document.getElementById("ctrl_"+field).innerHTML = '<input type="file" id="upload_'+field+'" value="">';
		}
	},
	false  // do not disable caching
	);
}

function updateCategorySelect(index,count,root) {
	if (root=="-1") {
		value_obj = $("select_category_"+count+"_"+index);
		update_obj = $("select_category_"+count+"_"+(index+1));
		root = value_obj.value;
	} else {
		update_obj = $("select_category_"+count+"_"+index);
	}
	update_obj.innerHTML = "";
	field_text = templates[count][index]["field_text"];
	field_value = templates[count][index]["field_value"];
	optional = templates[count][1+index]["optional"];

	if(templates[count][1+index]["url"]==undefined){
		templates[count][1+index]["url"]='';
	}

	url = "/core_category/" + root + templates[count][1+index]["url"] + "/tree.html";

	var ts = new Date();
	xmlhttp[count+"_"+index] = new Ajax.Request(url, {
		method: "get",
		parameters: { t : ts.getTime() },
		onSuccess: function(tree) {
			if (optional=="1") {
				newOption = document.createElement("option");
				newOption.appendChild(document.createTextNode('Выберите из списка'));
				update_obj.appendChild (newOption);
			}
			arr = tree.responseText.evalJSON();
			new_root = arr[0][field_value];
			arr.each ( function (one) {
				newOption = document.createElement("option");
				newOption.setAttribute("value",one[field_value]);
				newOption.appendChild(document.createTextNode(one[field_text]));
				update_obj.appendChild (newOption);
			});

		},
		onComplete: function(tree) {
			if (templates[count][index+2]) {
				updateCategorySelect(index+1,count,"-1");
			}
		}
	});
}

function check_server(entity,form_id){
	var ts = new Date();
	url = "/x/check.php";
	var check = new Ajax.Request(url,{
		method: "get",
		parameters: { t : ts.getTime(),entity : entity },
		onSuccess: function(ret){
			if(ret.status == 200){
				answer=ret.responseText.evalJSON();
				if(answer=='1'){
					$(form_id).submit();
				}
				else{
					alert('Сервер не работает. Попробуйте повторить сохранение через несколько минут');
				}
			}
			else{
				alert('Сервер не работает. Попробуйте повторить сохранение через несколько минут');
			}
		},
		onFailure: function(){
			alert('Сервер не работает. Попробуйте повторить сохранение через несколько минут');
		}
	});
	return false;
}


var templates = new Array();
var xmlhttp = new Array();

// Base EDMR object
var Edmr={};

Edmr.scrollToElement=function(oid)
{
	if (!$(oid)) return;
	offset=0;
	for (tmp=$(oid);tmp;tmp=tmp.offsetParent) offset+=tmp.offsetTop;
	for (tmp=$(oid).parentNode;tmp&&tmp!=document.body;tmp=tmp.parentNode) if (tmp.scroolTop) offset-=tmp.scroolTop;
	window.scrollTo(0,offset);
}

var edmr_add_onload=Edmr.add_onload=function (fn)
{
	if (window.addEventListener) window.addEventListener("load", fn, false);
	else if (window.attachEvent) window.attachEvent("onload", fn);
}

Edmr.add_domonload=function(fn)
{
	Edmr.add_domonload=function(fn){Edmr.add_domonload.cb.push(fn);}
	Edmr.add_domonload.cb=[];
	Edmr.add_domonload.execute=function()
	{
		arr=Edmr.add_domonload.cb;
		for (i=0;i<arr.length;i++) arr[i]();
	}
	Edmr.add_domonload(fn);

	var o={

		/**
		* Internet Explorer version number or 0.  Example: 6
		* @property ie
		* @type float
		*/
		ie:0,

		/**
		* Opera version number or 0.  Example: 9.2
		* @property opera
		* @type float
		*/
		opera:0,

		/**
		* Gecko engine revision number.  Will evaluate to 1 if Gecko
		* is detected but the revision could not be found. Other browsers
		* will be 0.  Example: 1.8
		* <pre>
		* Firefox 1.0.0.4: 1.7.8   <-- Reports 1.7
		* Firefox 1.5.0.9: 1.8.0.9 <-- Reports 1.8
		* Firefox 2.0.0.3: 1.8.1.3 <-- Reports 1.8
		* Firefox 3 alpha: 1.9a4   <-- Reports 1.9
		* </pre>
		* @property gecko
		* @type float
		*/
		gecko:0,

		/**
		* AppleWebKit version.  KHTML browsers that are not WebKit browsers
		* will evaluate to 1, other browsers 0.  Example: 418.9.1
		* <pre>
		* Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
		*								   latest available for Mac OSX 10.3.
		* Safari 2.0.2:		 416	 <-- hasOwnProperty introduced
		* Safari 2.0.4:		 418	 <-- preventDefault fixed
		* Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
		*								   different versions of webkit
		* Safari 2.0.4 (419.3): 419	 <-- Current Safari release
		* Webkit 212 nightly:   522+	<-- Safari 3.0 (with native SVG) should
		*								   be higher than this
		*
		* </pre>
		* http://developer.apple.com/internet/safari/uamatrix.html
		* @property webkit
		* @type float
		*/
		webkit:0,

		/**
		* The mobile property will be set to a string containing any relevant
		* user agent information when a modern mobile browser is detected.
		* Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series
		* devices with the WebKit-based browser, and Opera Mini.
		* @property mobile
		* @type string
		*/
		mobile: null
	};

	//noinspection PlatformDetectionJS
	var ua=navigator.userAgent, m;

	// Modern KHTML browsers should qualify as Safari X-Grade
	if ((/KHTML/).test(ua)) {
		o.webkit=1;
	}
	// Modern WebKit browsers are at least X-Grade
	m=ua.match(/AppleWebKit\/([^\s]*)/);
	if (m&&m[1]) {
		o.webkit=parseFloat(m[1]);

		// Mobile browser check
		if (/ Mobile\//.test(ua)) {
			o.mobile = "Apple"; // iPhone or iPod Touch
		} else {
			m=ua.match(/NokiaN[^\/]*/);
			if (m) {
				o.mobile = m[0]; // Nokia N-series, ex: NokiaN95
			}
		}
	}

	if (!o.webkit) { // not webkit
		m=ua.match(/Opera[\s\/]([^\s]*)/);
		if (m&&m[1]) {
			o.opera=parseFloat(m[1]);
			m=ua.match(/Opera Mini[^;]*/);
			if (m) {
				o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
			}
		} else { // not opera or webkit
			m=ua.match(/MSIE\s([^;]*)/);
			if (m&&m[1]) {
				o.ie=parseFloat(m[1]);
			} else { // not opera, webkit, or ie
				m=ua.match(/Gecko\/([^\s]*)/);
				if (m) {
					o.gecko=1; // Gecko detected, look for revision
					m=ua.match(/rv:([^\s\)]*)/);
					if (m&&m[1]) {
						o.gecko=parseFloat(m[1]);
					}
				}
			}
		}
	}

	// Execute DomOnLoad
	if (o.ie) {
		domReadyTimer = setInterval(function() {
			var n = document.createElement('p');
			try {
				// throws an error if doc is not ready
				//noinspection JSUnresolvedFunction
				n.doScroll('left');
				clearInterval(domReadyTimer);
				Edmr.add_domonload.execute();
			} catch (e) {
				n = null;
			}
		}, 100);
	} else if (o.webkit && o.webkit < 525) {
		domReadyTimer = setInterval(function() {
			var rs=document.readyState;
			if ("loaded" == rs || "complete" == rs) {
				clearInterval(domReadyTimer);
				Edmr.add_domonload.execute();
			}
		}, 100);
	} else {
		if (window.addEventListener) document.addEventListener("DOMContentLoaded", Edmr.add_domonload.execute, false);
		else if (window.attachEvent) document.attachEvent("onDOMContentLoaded", Edmr.add_domonload.execute);
	}
}

function getUsedSearchParams(base_url,series)
{
	var params = {
		'series':((series)?series:getSearchParam('series')),
		'min_year':getSearchParam('minyear'),
		'max_year':getSearchParam('maxyear'),
		'min_price':getSearchParam('minprice'),
		'max_price':getSearchParam('maxprice'),
		'min_haulage':getSearchParam('minhaulage'),
		'max_haulage':getSearchParam('maxhaulage'),
		'city':getSearchParam('city')
	};

	var extra = comma = '';
	for (key in params)
	{
		if (params[key] && params[key] != '')
		{
			extra += comma + key + '=' + params[key];
			comma = '&';
		}
	}

	var url = base_url + ((extra!='')?'?'+extra:'');
	window.location.href = url;
}

function getSearchParam(name)
{
	var res = '';
	$$('select[name='+name+']').any(function(obj){res = obj.value;});
	if (res == '')
	{
		$$('input[name='+name+']').any(function(obj){res = obj.value;});
	}
	res = res.replace(/\ +/g,'');

	return res;
}

function profileAuthCheck()
{
	if (cmnts_isuid) return true;
	else
	{
		new Ajax.Updater("secondary_auth_block", "/profile/auth_login.html", {
			asynchronous : false,
			parameters: add_ts(new Hash()),
			method: 'get',
			evalScripts : true
		});
		return false;
	}
}

function profileAuthAction(typei)
{
	if (typei==1)
	{
		var ts = new Date();
		var param=new Hash({email: $('cr_email').value, newpassword1: $('cr_newpassword1').value});
		new Ajax.Updater("secondary_auth_block", "/profile/auth_login.html?ts="+ts.getTime(), {
			asynchronous : false,
			parameters: param,
			method: 'post',
			evalScripts : true
		});
	}
	else if (typei==2)
	{
		new Ajax.Updater("secondary_auth_block", "/profile/auth_reg.html", {
			asynchronous : false,
			parameters: add_ts(new Hash()),
			method: 'get',
			evalScripts : true
		});
	}
	else if (typei==3)
	{
		var ts = new Date();
		var param=new Hash({email: $('cr_email').value, newpassword1: $('cr_newpassword1').value, newpassword2: $('cr_newpassword2').value});
		new Ajax.Updater("secondary_auth_block", "/profile/auth_reg.html?ts="+ts.getTime(), {
			asynchronous : false,
			parameters: param,
			method: 'post',
			evalScripts : true
		});
	}
	return false;
}

function log_click(type){
	new Ajax.Request(
		'/x/log_click.php?type='+type,
		{method: 'get'}
	);
}

function load_branding(prefix){
	img1=new Image();
	img1.src='/i/'+prefix+'_left.jpg';

	img2=new Image();
	img2.src='/i/'+prefix+'_right.jpg';

	timer = setInterval(function(){
		if(img1.width>0 && img1.height>0 && img2.width>0 && img2.height>0){
			$('b_left').style.background="url('/i/"+prefix+"_left.jpg') no-repeat right top";
			$('b_right').style.background="url('/i/"+prefix+"_right.jpg') no-repeat left top";
			clearInterval(timer);
		}
	},30);
}