var rot13map;

function body_load ()
{
}

function body_unload ()
{
}

function go(addr)
{
	document.location.href = addr;
}

function go_false (addr)
{
	go (addr);
	return false;
}

function go_rel_addr (rel_addr)
{
	go (site_base_addr + rel_addr);
}

function confirm_go (question, addr)
{
	if (window.confirm (question))
		go(addr);
}

function findPos(obj)
{
        var curleft = 0, curtop = 0;
        while (obj)
        {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
                obj = obj.offsetParent;
        }
        return [curleft, curtop];
}

function search_blur (obj)
{
	if (obj.value == '') {obj.value = 'Поиск'; }
}

function search_focus (obj)
{
	if (obj.value == 'Поиск') { obj.value = ''; }
}

function search_submit (obj)
{
	var val = obj.s.value;
	// val = val.replace ('/', '%2F');
	val = val.replace ('/', ' ');
	var newAddr = site_base_addr + 'search/query.' + val + '/';
	
	if (obj.s.value == '' || obj.s.value == 'Поиск')
		return false;
	
	go (newAddr);
	return false;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function rot13init()
{
	var map = new Array();
	var s   = "abcdefghijklmnopqrstuvwxyz";
  
	for (i = 0; i < s.length; i++)
		map[s.charAt(i)]			= s.charAt((i+13)%26);
		
	for (i = 0; i < s.length; i++)
		map[s.charAt(i).toUpperCase()]	= s.charAt((i+13)%26).toUpperCase();
		
	return map;
}

function rot13(a)
{
	if ( ! rot13map)
		rot13map=rot13init();
		
	s = "";
	for (i = 0; i < a.length; i++)
	{
		var b = a.charAt(i);
		s += (b>='A' && b<='Z' || b>='a' && b<='z' ? rot13map[b] : b);
	}
	
	return s;
}

function mail_decrypt (objId, cryptedAddr)
{
	var obj = document.getElementById(objId);
	if ( ! obj)
		return;
		
	var addr = rot13 (cryptedAddr);
	obj.innerHTML = '<a href="mailto:' + addr + '" rel="nofollow">' + addr + '</a>' ;
}

function open_popup (insite_addr, window_name, width, height)
{
	var url = site_base_addr + insite_addr;	
	var params = "scrollbars=yes,status=no,resizable=yes,toolbar=no,directories=no,menubar=no," + 			
				"width=" + width + ",height=" + height;

	var popUp = window.open (url, window_name, params);
	popUp.focus ();
	
	return popUp;
}

function get_tmp1()
{
	return '11';
}

function common_shop_form_submit (obj)
{
	obj.vdf.value = '00' + get_tmp1() + '15a';

	return true;
}

function links_count (obj, item_id, type)
{
	// onmousedown="links_count(this, banner_id);"
	/* var curdate = new Date().getTime();
	var link = (obj && obj.href) ? obj.href : "";
	var sect = type == 1 ? 'quatrix' : 'shop_quatrix';
	var url = site_base_addr + 'out/' + sect + '/banner.' + item_id + 
		'/time.' + curdate + '/?href=' + escape(link);
		
	document.createElement("img").src = url;
	*/
}








/* ****************************************************************************************** */

function brand_list_load (brand_list_obj, categ_id, rubric_id)
{
	if (brand_list_obj.getAttribute ('loading'))
		return;
	brand_list_obj.setAttribute ('loading', '1');
	
	var url = site_base_addr + 'catalog/ajax_get_brands_list/';
	
	if (categ_id != '')
		url += 'categ_id.' + categ_id + '/';
	else if (rubric_id != '')
		url += 'rubric_id.' + rubric_id + '/';
		
	jx.load (url, set_brand_list_data, 'xml');
}

function set_brand_list_data (xml)
{
	var objSelect = document.getElementById('global_skidki_brands_list');
	if ( ! objSelect)
	{
		alert ('Can not get select node!');
		return;
	}
	
	objSelect.innerHTML = '<option value="0"> - Выберите компанию - </option>';
	
	var brands_list = xml.documentElement.getElementsByTagName("option");
		
	var option;
	for (var i = 0; i < brands_list.length; i++) 
	{
		option = document.createElement ('option');
		option.appendChild (document.createTextNode(brands_list[i].getAttribute ('text')));
		option.setAttribute ('value', brands_list[i].getAttribute ('value'));
		objSelect.appendChild (option);
	}
	
	objSelect.setAttribute ('loading', '2');
}

function brand_change (obj)
{
	if (obj.getAttribute ('loading') != '2')
		return;
		
	go (site_base_addr + 'shop/' + obj.value + '/');
}

/* ****************************************************************************************** */


function load_captcha_image (mod)
{
	obj_img = document.getElementById ('img_captcha_code');
	if ( ! obj_img)
	{
		alert ("Can't find img_captcha_code!");
		return false;
	}
	url = site_base_addr + mod + '/captcha/?' 
		+ Math.floor(Math.random() * 1000000000);
	obj_img.src = url;
}



/************************************************************************************************/

//V3.01.A - http://www.openjs.com/scripts/jx/
jx = {
	//Create a xmlHttpRequest object - this is the constructor. 
	getHTTPObject : function() {
		var http = false;
		//Use IE's ActiveX items to load the file.
		if(typeof ActiveXObject != 'undefined') {
			try {http = new ActiveXObject("Msxml2.XMLHTTP");}
			catch (e) {
				try {http = new ActiveXObject("Microsoft.XMLHTTP");}
				catch (E) {http = false;}
			}
		//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
		} else if (window.XMLHttpRequest) {
			try {http = new XMLHttpRequest();}
			catch (e) {http = false;}
		}
		return http;
	},
	
	// This function is called from the user's script. 
	//Arguments - 
	//	url	- The url of the serverside script that is to be called. Append all the arguments to 
	//			this url - eg. 'get_data.php?id=5&car=benz'
	//	callback - Function that must be called once the data is ready.
	//	format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
	//			the string will be 'eval'ed before returning it. Default:'text'
	//	method - GET or POST. Default 'GET'
	load : function (url,callback,format,method, opt) {
		var http = this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
		if(!http||!url) return;
		//XML Format need this for some Mozilla Browsers
		if (http.overrideMimeType) http.overrideMimeType('text/xml');

		if(!method) method = "GET";//Default method is GET
		if(!format) format = "text";//Default return type is 'text'
		if(!opt) opt = {};
		format = format.toLowerCase();
		method = method.toUpperCase();
		
		//Kill the Cache problem in IE.
		var now = "uid=" + new Date().getTime();
		url += (url.indexOf("?")+1) ? "&" : "?";
		url += now;

		var parameters = null;

		if(method=="POST") {
			var parts = url.split("\?");
			url = parts[0];
			parameters = parts[1];
		}
		http.open(method, url, true);

		if(method=="POST") {
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", parameters.length);
			http.setRequestHeader("Connection", "close");
		}

		var ths = this;// Closure
		if(opt.handler) { //If a custom handler is defined, use it
			http.onreadystatechange = function() { opt.handler(http); };
		} else {
			http.onreadystatechange = function () {//Call a function when the state changes.
				if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
					if(http.status == 200) {
						var result = "";
						if(http.responseText) result = http.responseText;
						//If the return is in JSON format, eval the result before returning it.
						if(format.charAt(0) == "j") {
							//\n's in JSON string, when evaluated will create errors in IE
							result = result.replace(/[\n\r]/g,"");
							result = eval('('+result+')');

						} else if(format.charAt(0) == "x") { //XML Return
							result = http.responseXML;
						}

						//Give the data to the callback function.
						if(callback) callback(result);
					} else {
						if(opt.loadingIndicator) document.getElementsByTagName("body")[0].removeChild(opt.loadingIndicator); //Remove the loading indicator
						if(opt.loading) document.getElementById(opt.loading).style.display="none"; //Hide the given loading indicator.
						
						if(error) error(http.status);
					}
				}
			}
		}
		http.send(parameters);
	},
	bind : function(user_options) {
		var opt = {
			'url':'', 			//URL to be loaded
			'onSuccess':false,	//Function that should be called at success
			'onError':false,	//Function that should be called at error
			'format':"text",	//Return type - could be 'xml','json' or 'text'
			'method':"GET",		//GET or POST
			'update':"",		//The id of the element where the resulting data should be shown. 
			'loading':"",		//The id of the loading indicator. This will be set to display:block when the url is loading and to display:none when the data has finished loading.
			'loadingIndicator':"" //HTML that would be inserted into the document once the url starts loading and removed when the data has finished loading. This will be inserted into a div with class name 'loading-indicator' and will be placed at 'top:0px;left:0px;'
		}
		for(var key in opt) {
			if(user_options[key]) {//If the user given options contain any valid option, ...
				opt[key] = user_options[key];// ..that option will be put in the opt array.
			}
		}
		
		if(!opt.url) return; //Return if a url is not provided

		var div = false;
		if(opt.loadingIndicator) { //Show a loading indicator from the given HTML
			div = document.createElement("div");
			div.setAttribute("style","position:absolute;top:0px;left:0px;");
			div.setAttribute("class","loading-indicator");
			div.innerHTML = opt.loadingIndicator;
			document.getElementsByTagName("body")[0].appendChild(div);
			this.opt.loadingIndicator=div;
		}
		if(opt.loading) document.getElementById(opt.loading).style.display="block"; //Show the given loading indicator.
		
		this.load(opt.url,function(data){
			if(opt.onSuccess) opt.onSuccess(data);
			if(opt.update) document.getElementById(opt.update).innerHTML = data;
			
			if(div) document.getElementsByTagName("body")[0].removeChild(div); //Remove the loading indicator
			if(opt.loading) document.getElementById(opt.loading).style.display="none"; //Hide the given loading indicator.
		},opt.format,opt.method, opt);
	},
	init : function() {return this.getHTTPObject();}
}

/*********************************************************************/

function shop_comment_submit (obj_form)
{
	if (obj_form.name.value == '') 
	{
		alert ('Необходимо ввести имя!');
		return false;
	}
	
	if (obj_form.header.value == '') 
	{
		alert ('Необходимо ввести заголовок!');
		return false;
	}
	
	if (obj_form.text.value == '') 
	{
		alert ('Необходимо ввести текст сообщения!');
		return false;
	}
	
	var checkEmail = /^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*?[a-z]+$/;
	if (obj_form.email.value.length > 0 && ! checkEmail.test (obj_form.email.value))
	{
		alert ('E-Mail введён неверно!');
		return false;
	}
	
	if (obj_form.code.value.length != 3)
	{
		alert ('Необходимо ввести 3-х значный код, находящийся на картинке!');
		return false;
	}
	
	return true;
}

function shop_comment_form_show ()
{
	var button = document.getElementById('shop_add_comment_button');
	if ( ! button)
	{
		alert ("Can't find shop_add_comment_button!");
		return false;
	}

	obj = document.getElementById ('shop_comments_form_container');
	if ( ! obj)
	{
		alert ("Can't find shop_comments_form_container!");
		return false;
	}
	
	if (obj.getAttribute('b_showed'))
		return false;
	
	button.style.display = 'none';
	obj.style.display = 'block';
	obj.setAttribute ('b_showed', '1');
	
	load_captcha_image ('shop');
	return false;
}

function quote_post (id)
{
	shop_comment_form_show ();	
	
	var url = site_base_addr + 'shop/get_comment_source/id.' + id + '/';
	
	jx.load (url, set_comment_post_data, 'json');
	// alert (url);
	/* new Ajax.Request(url,
  	{
    	method:'get',
    	onSuccess: function(transport, json)
    	{
      		var json = transport.responseText.evalJSON();
      		
      		textarea.value += "\n[quote=" + json.name + "]\n" + json.text + "\n[/quote]\n";
    	},
    	onFailure: function()
    	{ 
    		alert('Невозможно загрузить текст комментария для цитирования!'); 
    	}
  	});
  	*/
}

function set_comment_post_data (json)
{
	var textarea = document.getElementById('shop_comment_textarea');
	if ( ! textarea)
	{
		alert ("Невозможно найти поле ввода комментария!");
		return;
	}
	
	textarea.value += "\n[quote=" + json.name + "]\n" + json.text + "\n[/quote]\n";
}

function load_captcha_image_voting ()
{
	obj_img = document.getElementById ('img_captcha_code_voting');
	if ( ! obj_img)
	{
		alert ("Can't find img_captcha_code_voting!");
		return false;
	}
	obj_img.src = site_base_addr + 'images/i/loading.gif';
	url = site_base_addr + 'shop/captcha_voting/?' 
		+ Math.floor(Math.random() * 1000000000);
	obj_img.src = url;
}


function shop_rating (value, shop_id)
{
	var obj = document.getElementById('shop_rating_vote_block');
	if ( ! obj)
	{
		alert ("Can not find vote block!");
		return;
	}
	
	obj.setAttribute ('shop_id', shop_id);
	
	var obj_vote_value = document.getElementById('vote_value');
	if ( ! obj_vote_value)
	{
		alert ("Can't find vote_value!");
		return;
	}
	obj_vote_value.innerHTML = (value > 0) ? '+1' : '-1';
	
	var caller_id = (value > 0) ? 'shop_rating_up' : 'shop_rating_down';
	
	var caller = document.getElementById(caller_id);
	if ( ! caller)
	{
		alert ("Can not find caller vote link!");
		return;
	}
	
	if (obj.getAttribute ('cur_value') == value)
	{
		obj.style.display = 'none';
		obj.setAttribute ('cur_value', 0);
		return;
	}
	
	obj.setAttribute ('cur_value', value);
	/* if (obj.style.display == 'block')
	{
		obj.style.display = 'none';
		return;
	} */
	
	// obj.style.left = caller.offsetLeft + "px";
	obj.style.display = 'block';
	if (obj.getAttribute ('is_code_loaded') != '1')
	{
		obj.setAttribute ('is_code_loaded', '1');
		load_captcha_image_voting();
	}
}

function shop_rating_send ()
{
	var obj = document.getElementById('shop_rating_vote_block');
	if ( ! obj)
	{
		alert ("Can not find vote block!");
		return ;
	}
	
	var field = document.getElementById('shop_rating_field_code');
	if ( ! field.value.match(/^[a-z0-9]{3}$/i))
	{
		alert ('Необходимо ввести код на картинке!');
		return ;
	}
	
	url = site_base_addr + 'shop/rate/shop_id.' + obj.getAttribute ('shop_id') 
		+ '/value.' + obj.getAttribute ('cur_value') 
		+ '/code.' + field.value + '/';
		
	obj.setAttribute ('is_code_loaded', 0);
	obj.setAttribute ('cur_value', 0);
	obj.style.display = 'none';
	field.value = '';
	
	var obj_rating = document.getElementById('cur_rating_value');
	obj_rating.setAttribute ('old_value', obj_rating.innerHTML);
	obj_rating.innerHTML = '<img src="' + site_base_addr + 'images/i/loading-mini.gif" />';

	jx.load (url, do_shop_rating_vote, 'json');
}

function do_shop_rating_vote (json)
{
	var obj_rating = document.getElementById('cur_rating_value');
	
	if (json.result != '1')
	{
		obj_rating.innerHTML = obj_rating.getAttribute ('old_value');
		alert (json.result);
	}
	else
	{
		obj_rating.innerHTML = json.new_rating;
		if (json.new_rating > 0)
			obj_rating.style.color = 'green';
		else if (json.new_rating < 0)
			obj_rating.style.color = 'red';
		else
			obj_rating.style.color = 'gray';
	}
}
