function SearchFormSubmit()
{
	var query = document.getElementById("SearchQuery").value;
	if (query != "") 
	{
		document.getElementById("SearchForm").submit();
	} else 
	{
		alert("Íå ââåäåí çàïðîñ ïîèñêà.");
	}
	
	return false;
}

function UpdateCart()
{
	var cookie = $.cookie("synccart");
	if (cookie != null)
	{
		var cookie_array = cookie.split(";");
		var count = 0;
		for (var i=0;i<cookie_array.length;i++) 
		{
			temp = cookie_array[i].split(":");
			if (temp[1]) count += Number(temp[1]);
		}
	
	document.getElementById("cart").innerHTML = count;
	}
	
}

function UpdateCartSumm()
{	
	var params = {
		page: "cartsumm",
		method: "ajax"
	};
	$("#cartsumm").load("/sync.php", params);
}

function DeviceToCart(new_id, notalerting)
{
	var cookie = $.cookie("synccart");
	var new_cookie_array = [];
	var in_array = false;
	var cookie_array = cookie != null ? cookie.split(";") : [];
	for (var i=0;i<cookie_array.length;i++) 
	{
		temp = cookie_array[i].split(":");
		if (temp[0] && temp[0] == new_id)
		{
			if (!temp[1]) temp[1] = 1;
			if (!temp[2]) temp[2] = 0;
			new_cookie_array.push(new_id + ":" + (Number(temp[1]) + 1) + ":" + temp[2]);
			in_array = true;
		}	
		else new_cookie_array.push(cookie_array[i]);
	}
	if (!in_array) new_cookie_array.push(new_id + ":1:0");
	
	cookie = new_cookie_array.join(";");
	$.cookie("synccart", cookie, {path: "/"});
	UpdateCart();
	UpdateCartSumm(exchange);
	
	if (!notalerting) alert("Óñòðîéñòâî äîáàâëåíî â êîðçèíó.");
}

function EmptyCart()
{
	$.cookie("synccart", "", {path: "/"});
	UpdateCart();
}

function Exchange(name, course, mod)
{
	collection = document.getElementsByName(name);
	for (var i=0;i<collection.length;i++)
	{
		var value = collection[i].value;
		value = Math.round(value);
		var id_num = collection[i].id;
		
		var rb = value * course;
		rb = String(Math.round(rb/100)*100).PointToCost();
		var dl = String(Math.round(value)).PointToCost();
		
		elem = document.getElementById("el"+id_num);
		
		if (mod == null)
		{
			elem.innerHTML = dl+"&nbsp;ó.å. ["+rb+"&nbsp;ð.]";
			elem.title = dl+" ó.å. ["+rb+" ð.]";
		}
		if (mod == 'rb')
		{
			elem.innerHTML = rb+"&nbsp;ð.";
			elem.title = rb+" ð.";
		}
		if (mod == 'usa')
		{
			elem.innerHTML = dl+"&nbsp;ó.å.";
			elem.title = dl+" ó.å.";
		}
	}
	
}	


String.prototype.PointToCost = function ()
{
	var value = this;
	var rb_array = [];
	for (var j=value.length-3;j>-3;j-=3)  rb_array.unshift(value.substr(Math.max(0, j), j >= 0 ? 3: 3+j));
	return rb_array.join(".");
};

function ChangePriceElementCount(name, value)
{
	var cookie = $.cookie("syncuserconf");
	if (cookie == null) cookie = "";
	
	var elems_array = cookie.split(";");
	var conf = [];
	var in_array = false;
	for (var i in elems_array)
	{
		var temp = elems_array[i].split(":");
		if (temp != "") 
		{
			if (temp[0] == name) 
			{
				temp[1] = value;
				in_array = true;
			}
			conf[temp[0]] = (temp[1]) ? temp[1] : "";			
		}				
	}
	
	if (in_array == false) conf[name] = value;
	
	var cookie_array = [];
	for (i in conf) cookie_array.push(i+":"+conf[i]);
	
	cookie = cookie_array.join(";");
	$.cookie("syncuserconf", cookie, {path: "/"});
}

function DopSearchBlock()
{
	block = document.getElementById("dopsearchblock");
	pimage = document.getElementById("dopsearchplusimage");
	mimage = document.getElementById("dopsearchminusimage");
	
	if (block.style.display == "block")
	{
		block.style.display = "none";		
		mimage.style.display = "none";
		pimage.style.display = "inline";
	}
	else
	{
		block.style.display = "block";
		mimage.style.display = "inline";
		pimage.style.display = "none";
	}
}

function GetCookieConf()
{
 	var cookie = $.cookie("syncuserconf");
	if (cookie == null) cookie = "";

	var elems_array = cookie.split(";");
	var conf = [];
	var in_array = false;
	for (var i in elems_array)
	{
		var temp = elems_array[i].split(":");
		if (temp != "")
		{
			conf[temp[0]] = (temp[1]) ? temp[1] : "";
		}
	}
	
	return conf;
}

function LoadComparisonChecks()
{
	var cookie = $.cookie("synccomparison");
	if (cookie == null || cookie == "")
	{
		var collection = document.getElementsByName('objcheck');
		for (var i=0;i<collection.length;i++) collection[i].style.display = "none";
		var collection = document.getElementsByName('objuncheck');
		for (var i=0;i<collection.length;i++) collection[i].style.display = "inline";
	}
	else 
	{	
		var ids = cookie.split(";");	
		for (var i in ids) 
		{
			var obj = document.getElementById("obj"+ids[i]);
			var objun = document.getElementById("objun"+ids[i]);
			if (obj && objun) 
			{
				obj.style.display = "inline";
				objun.style.display = "none";
			}
		}
	}
}

function UpdateComparisonText(tid)
{
	var params = {
		page: "comparisonblock",
		tid: tid,
		method: "ajax"
	};
	$("#cmpblock").load("/sync.php", params);
}

function ClearComparison(tid)
{
	$.cookie("synccomparison", "");
	UpdateComparisonText(tid);
	LoadComparisonChecks();
}


function VoteChange(index)
{
	document.getElementById("voteindex").value = index;
}

function VoteResult(show_results)
{
	if (!show_results) show_results = false;
	
	index = document.getElementById("voteindex").value;
	if (input_el = document.getElementById("t"+index)) doptext = input_el.value; else doptext = "";
	
	if (index != 0 || show_results)
	{
		if (show_results) 
		{
			index = -1;
			doptext = "";
		}
		
		var params = {
				page: "voteanswer",
				aindex: index,
				doptext: doptext,
				method: "ajax"
			};
		$("#oprosblock").load("/sync.php", params);
	}
	else
	{
		alert("Íå âûáðàí íè îäèí èç îòâåòîâ.");
	}
}

function AddToCalc(id, tid)
{
	var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
           	block = req.responseJS.content;
           	document.getElementById("calcmenu").innerHTML = block;
           	
           	Exchange("usacost", exchange, "usa");
			Exchange("brcost", exchange, "rb");
        }
    }
    req.open(null, '/sync.php', true);
    req.send( { method: "ajax", page: "calcmenu", mod: "add", devid: id, "tid": tid});
}

function DelCalc(id)
{
	var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
           	block = req.responseJS.content;
           	document.getElementById("calcmenu").innerHTML = block;
           	
           	Exchange("usacost", exchange, "usa");
			Exchange("brcost", exchange, "rb");
        }
    }
    req.open(null, '/sync.php', true);
    req.send( { method: "ajax", page: "calcmenu", mod: "del", devid: id});
}

function PopDevice(id)
{
	window.open('/popdevice'+id+'.html', '_blank', 'width=800, height=400, scrollbars, resize=true');
	return false;
}

function PopHistory(id)
{
	window.open('/pophistory'+id+'.html', '_blank', 'width=800, height=400, scrollbars, resize=true');
	return false;
}

function PopReviews(id)
{
	window.open('/popreviews'+id+'.html', '_blank', 'width=800, height=400, scrollbars, resize=true');
	return false;
}

$.extend({
    wrapfunc: function (fn, object)
	{
		var __arguments = $.makeArray(arguments), __method = __arguments.shift(), __object = __arguments.shift();
		return function(){ return __method.apply(__object, __arguments.concat(jQuery.makeArray(arguments))); }; 
	},

    sort: function (input)
	{
		var probe = false;
		do
		{
			probe = true;
			for (var i=0; i<input.length-1; i++)
			{
			    var a = typeof(input[i]) == "string" ? input[i].toLowerCase() : input[i];
			    var b = typeof(input[i+1]) == "string" ? input[i+1].toLowerCase() : input[i+1];

                            if (a > b)
                            {
                                    var temp = input[i];
                                    input[i] = input[i+1];
                                    input[i+1] = temp;
                                    probe = false;
                            };
			};
		} while (!probe);
		return input;
	},

    ksort: function (input)
	{
		var nsindexes = [];
		for (var i in input) nsindexes.push(i*1);
		var indexes = this.sort(nsindexes);
		var out = {};
		for (var i in indexes) out[indexes[i]] = input[indexes[i]];
		return out;
	},

    strksort: function (input)
	{
		var nsindexes = [];
		for (var i in input) nsindexes.push(i);
		var indexes = this.sort(nsindexes);
		var out = {};
		for (var i in indexes) out[indexes[i]] = input[indexes[i]];
		return out;
	}
});