var big_img = new Image;
//глобальні змінні для меню
var menubgcolor = "#024d84"; //Фон елемента меню
var menubghilitecolor = "#1e5888"; //Фон елемента меню (підсвітка)
var menutxtcolor = "#FFFFFF"; //Колір тексту
var menutxthilitecolor = "#FFFFFF"; //Колір тексту при підсвітці
var menucursor = "pointer";
var timer = new Array();

function Menu(label,mw,mh,top,left,mbc,mbhc,mtc,mthc){
	this.type = "Menu";
	this.label = label;
	this.menuwidth = mw;
	this.menuheight = mh;
	this.abstop = top;
	this.absleft = left;
	this.menubgcolor = mbc || "#024d84";
	this.menubghilitecolor = mbhc || "#1e5888";
	this.menutxtcolor = mtc || "#FFFFFF";
	this.menutxthilitecolor = mthc || "#FFFFFF";
	this.menucursor = "pointer";
	this.items = new Array();
	this.actions = new Array();
	
	this.addMenuItem = addMenuItem;
	this.writeMenus = writeMenus;
}

function addMenuItem(label, action) {
	this.items[this.items.length] = label;
	this.actions[this.actions.length] = action;
}

function writeMenus(){
	var menuheighttotal = this.menuheight*this.items.length+this.items.length;
	var content = '<div class="'+this.label+'" style="z-index: 1; border: 1px solid '+this.menubghilitecolor+'; border-top: 0px; background-color: '+this.menubgcolor+'; color: '+this.menutxtcolor+'; width: '+this.menuwidth+'px; height: '+menuheighttotal+'px; top: '+this.abstop+'px; left: '+this.absleft+'px; position: absolute; display:none;">';
	for (var i=0; i<this.items.length; i++) {
		var Item = this.items[i];
		var action = this.actions[i];
		content += '<div class="link'+i+'" style="width: '+this.menuwidth+'px; height: '+this.menuheight+'px; border-bottom: 1px solid '+this.menubghilitecolor+';"><a style="display: none" href="'+action+'">'+Item+'</a>'+Item+'</div>';
	}
	content += '</div>';
	document.getElementById('menucontainer').innerHTML += content;
}

//Версія браузера
function brouserdetect(){
	var ua = navigator.userAgent.toLowerCase();
	isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);
	isOpera = (ua.indexOf("opera") != -1);
	isGecko = (ua.indexOf("gecko") != -1);
	if (isIE){return "IE"}
	if (isOpera){return "Opera"}
	if (isGecko){return "Gecko"}
}
var brouser = brouserdetect();


function digitsonly(checkstr){
	var allowed = new Array('0','1','2','3','4','5','6','7','8','9');
	var res_temp = false;
	var res = true;
	for (var i=0; i<checkstr.length; i++)
	{
	res_temp = false;
		for (var j=0; j<allowed.length; j++)
		{		
		if (checkstr[i]==allowed[j] && res_temp == false)
			res_temp = true;
		}
	if (!res_temp) res = false;
	}
	return res;	
}

var slide = false;
var timestart;

//onLoad
function init(){
DoSlideMenu();
$("table.add_cart").find('tr').hover(function() {$(this).css({backgroundColor: "#e6e6e6", cursor: "pointer"});}, function() {$(this).css({backgroundColor: "#FFFFFF"});});
$("div.cart").hover(function(){$(this).css({color: "#cccccc", cursor: "pointer"});}, function(){$(this).css({color: "#FFFFFF", cursor: "default"});});
$("div.cart").click(function(){showcart();});
$("div.butt-area a[id]").hover(function(){if (timer[$(this).attr("id")]){clearTimeout(timer[$(this).attr("id")]); timer[$(this).attr("id")]=null;} showmenu($(this).attr("id"));},function(){hidemenu($(this).attr("id"));});
$("div.butt-area a").click(function(){textload($(this).attr('href')+'?nohead=1'); return false;});
$("div#menucontainer div[class^=menu]").hover(function(){hover($(this).attr("class"));},function(){hovered = false; hidemenu($(this).attr("class"));});
$("div#menucontainer div[class^=link]").hover(function(){$(this).css({backgroundColor: menubghilitecolor, color: menutxthilitecolor, cursor: menucursor})},function(){$(this).css({backgroundColor: menubgcolor, color: menutxtcolor})});
$("div#menucontainer div[class^=link]").click(function(){go($(this).find('a').attr('href'))}); //Дія на елемент меню
//Форма пошуку
$("input.search").focus(function(){if ($(this).attr("value")=="пошук") $(this).attr('value', ''); });
$("input.search").blur(function(){if ($(this).attr("value")=="") $(this).attr('value', 'пошук'); });
$("input.search").parent().submit(function(){ search = $(this).children().attr('value'); search=search.split("+").join("*"); search=search.split(" ").join("+"); textload("search.html?query="+search+"&nohead=1"); return false;});
if (brouser=='IE') $("input.search").css('margin-top','10px');
//Кінець форми пошуку
$(".bottomslice").click(function(){ if (!slide) slidedown(this); else slideup(this);});
$(".bottomslice a").click(function(){textload($(this).attr('href')+'&nohead=1'); return false;});
 $('div#text').ajaxStart(function(){
   timestart = new Date();
   document.getElementById('loading').style.visibility = 'visible';
   document.getElementById('text').style.visibility = 'hidden';
 });
 $('div#text').ajaxStop(function(){
		var timeend = new Date();
		var interval = timeend-timestart;
		if (interval < 1000)
			{ interval = 1000 - interval;}
		else interval = 1;
	setTimeout(function(){
		document.getElementById('loading').style.visibility = 'hidden';
		document.getElementById('text').style.visibility = 'visible';
	},interval);
 });
 //Admin
}

function addOption (oListbox, text, value, isDefaultSelected, isSelected)
{
  var oOption = document.createElement("option");
  oOption.appendChild(document.createTextNode(text));
  oOption.setAttribute("value", value);

  if (isDefaultSelected) oOption.defaultSelected = true;
  else if (isSelected) oOption.selected = true;

  oListbox.appendChild(oOption);
}


function change_status(oid,status)
	{
	if (confirm('Ви дійсно хочете змінити статус замовлення '+oid+' на '+status+' ?'))
		$.post("?action=change_orderstatus&oid="+oid+"&nohead=1", {"status": status}, function(data) {
				alert(data);
			});
	}

function change_pay_method(oid,method)
	{
	if (confirm('Ви дійсно хочете змінити метод оплати '+oid+' на '+method+' ?'))
		$.post("?action=change_orderpaymethod&oid="+oid+"&nohead=1", {"method": method}, function(data) {
				alert(data);
			});
	}

function change_delivery_method(oid,delivery_method)
	{
	if (confirm('Ви дійсно хочете змінити метод оплати '+oid+' на '+delivery_method+' ?'))
		$.post("?action=change_orderdeliverymethod&oid="+oid+"&nohead=1", {"delivery_method": delivery_method}, function(data) {
				alert(data);
			});
	}
	
function change_comment(oid,comment,inpevent)
	{
	var code = inpevent.which;
	if (!code)
	   code = inpevent.keyCode;
	if (code == 13)
		if (confirm('Ви дійсно хочете змінити коментар замовлення '+oid+' ?'))
		$.post("?action=change_ordercomment&oid="+oid+"&nohead=1", {"comment": comment}, function(data) {
				alert(data);
			});
	}

function get_schapter_by_cid(cid)
	{
	$("#schapter").html('');
	objSel = document.getElementById("schapter");
	objSel.options.length = 0;
	$("#schapter:disabled").removeAttr('disabled');
	$.post("?action=get_schapter_packed&nohead=1", {"cid": cid}, function(data) {
				var mystr = new String(data);
				var myarray = mystr.split('|');
				for (var i=0; i<myarray.length; i++)
					{
					var schapter = new String(myarray[i]);
					addOption(objSel, schapter.split('=')[1], schapter.split('=')[0], false);
					}
			});
	}
	
function delete_chapter(cid)
	{
	if (confirm('Ви дійсно хочете видалити розділ '+cid+'?'))
		$.post("?action=delete_chapter&nohead=1", {"cid": cid}, function(data) {
				alert(data);
			});
	}

function delete_subchapter(scid)
	{
	if (confirm('Ви дійсно хочете видалити підрозділ '+scid+'?'))
		$.post("?action=delete_subchapter&nohead=1", {"scid": scid}, function(data) {
				alert(data);
			});
	}
	
function more_attr()
	{
	var count = $("#count").html();
	count++;
	$("#attrs").append("<div id=\"attrs"+count+"\"><input type=\"text\" id=\"attr"+count+"\" style=\"width: 267px;\" /><input type=\"text\" id=\"value"+count+"\" style=\"width: 267px;\" /><br/></div>");
	$("#count").html(count);
	}

function less_attr()
	{
	var count = $("#count").html();
	$("#attr"+count).remove();
	$("#value"+count).remove();
	$("#attrs"+count).remove();
	count--;
	$("#count").html(count);
	}
	
function subm_form_add_prod()
	{
	var count = $("#count").html();
	var a = new Array;
	var b = new Array;
	for (var i=0; i<=count; i++)
		{
		a[i] = $("#attr"+i).attr('value');
		b[i] = $("#value"+i).attr('value');
		}
	$("#attr").attr('value',a.join('||'));
	$("#value").attr('value',b.join('||'));
	$("#schapterhidden").attr('value',$("select[@name=schapter_temp] option:selected").val()); //Заганяємо значення підрозділу в приховане поле для відправки на сервер
	}
	
var hovered = false;

function slidedown(item)
	{
	$("#top-menu").animate({height: "70px"},"fast");
	$(item).find('div').slideDown("fast");
	setTimeout(function(){	
		$(item).css({height: "30px"});
	//	setTimeout(function(){$(item).css({backgroundPosition: "0px 10px"}); },1000);
		$(item).css({backgroundPosition: "0px 10px"});
	},200);
	slide = true;
	}

function slideup(item)
	{
	$(item).css({backgroundPosition: "0px 0px"});
	$(item).animate({height: "10px"},"fast");
	$(item).find('div').slideUp();
	setTimeout(function(){
		$(item).animate({height: "10px"});
		$("#top-menu").animate({height: "50px"},"fast");
	//	$(item).css({backgroundPosition: "0px 0px"}); 
	},200);
	slide = false;
	}


//перевірка завантаження картинки
function img_ready(){
	if (big_img.complete) {
		document.getElementById('big_img').innerHTML = '<a class="close_btn" onclick="window.close_big_img();"></a><img id="imgz" src="'+big_img.src+'">';
		document.getElementById('imgz').style.width = '485px';
		document.getElementById('imgz').style.height = '485px';
		document.getElementById('imgz').style.padding = '8px';
	}else{
		setTimeout(arguments.callee,1000);
	}
}



//відкриваємо вікно перегляду картинок
function img_zoom(url){
    var Iheight = window.innerHeight;
	if (!Iheight) { Iheight = document.documentElement.clientHeight; $("#maincontainer").css({zIndex: "3"}); }
	if (document.body.scrollHeight>Iheight) Iheight = document.body.scrollHeight;
	$("#grayfone").css({visibility: "visible", height: Iheight+"px"});
	$("#grayfone").animate({opacity: "0.7"}, "slow");
	$("#big_img").css({display: "block"});
    $("#big_img").animate({opacity: "1"}, "slow");
	document.getElementById('big_img').innerHTML = '<a class="close_btn" onclick="window.close_big_img();"></a><img id="imgz" style="padding-top: 200px;" src="img/loading.gif">';
	big_img.src = url;
	if (brouser=="Gecko"){
		big_img.onload = img_ready();
	}else{
		img_ready();
	}	
}

//закриваємо вікно перегляду картинок
function close_big_img(){
    $("#big_img").animate({opacity: "0"}, "slow");
	$("#grayfone").animate({opacity: "0"}, "slow");
	if (brouser=="IE"){$("#maincontainer").css({zIndex: "0"});}
	setTimeout(function(){ $("#big_img").css({display: "none"}); $("#grayfone").css({visibility: "hidden"});},1000);
}

//Додаємо продукт в кошик
function add_cart(id){
	$.get("", {"action": "add_cart", "pid": id, "nohead": "1"}, function(data) {
  		$("div.cart").html("Кошик ("+data+" &#36;)");
	});
}

//Оновляэмо кошик (сумарно)
function get_cart_summary(){
	$.get("", {"action": "get_cart_summary", "nohead": "1"}, function(data) {
  		$("div.cart").html("Кошик ("+data+" &#36;)");
	});
}

//Клік на кошику
function showcart(){
	textload('?action=get_cart&sortby=pid&nohead=1');
}
//Очиста кошика
function emptycart(){
	$.get("", {"action": "empty_cart", "nohead": "1"}, function(data) {
  		get_cart_summary(); //Оновлюэмо кошик
		showcart(); //Показуэмо порожній кошик
	});
}
//Змінюємо кількість замовлених елементів
function updatecart(pid,qty) //pid = prod_id and qty = quantity is ordered already
	{
	var conf=true;
	var newqty = prompt('Введіть кількість продуктів, які ви хочете замовити:',qty);
	if(newqty!=null) //Перевірка на введення даних користувачем
	if(digitsonly(newqty) && newqty >= 0)
	   {
	   if (newqty != qty){
		if(newqty==0) conf = confirm('Ви справді хочете видалити даний продукт з кошика?');
		if(conf) //Користувач підтвертив свою дію
		textload('?action=upd_cart&pid='+pid+'&qty='+newqty+'&nohead=1');
		setTimeout(function (){get_cart_summary();},1200);
	   	}else alert('Ви не змінили значення кількості для даного продукту.');
	   }else alert('Ви ввели недопустиме значення');
	}
//Завантаження змісту в контейнер
function textload(dest){
	//$('div#text').hide("slow");
	$('div#text').load(dest);
	//$('div#text').show("slow");
}
//Показуємо меню
function showmenu(id){
	$("div#menucontainer div[class^=menu]").not("[class="+id+"]").hide();
	$("div."+id).css({left: ($('#'+id).attr('offsetLeft') + $('#top-menu').attr('offsetLeft') + 8)+'px'}); //Абсолютна координата меню
	$("div."+id+":hidden").show("slow");
}
//Курсор миші над меню
function hover(id){
	hovered = true;
}
//Ховаємо меню
function hidemenu(id){
	 timer[id] = setTimeout(function(){ if (!hovered){$("div."+id).hide("slow");} },500);
}
//Перехід на сторінку
function go(url){
	textload(url+'?nohead=1');
}
//Відправка даних форми (ініціалізація користувача)
function login(log,pass,pagegoafter)
	{
	var err = false;
	if (log.length >0 && pass.length > 0)
		{
			$.post("?action=login&nohead=1", {"login": log,"passw": pass,"pagegoafter": pagegoafter}, function(data) {
				$('div#text').html(data);
			});
		}
		else
		{err = true; alert('Логін і пароль повинні бути заповнені');};
		
	if (!err) return true; else return false;
	}
	
//Відправка даних форми (реєстрація користувача)
function register(email,pass,confpass,fname,cel,icq,country,town,shipcountry,shiptown,pagegoafter)
	{
	var err = false;
	if (email.length == 0) {err = true; alert('Поле "E-mail" не заповнено!'); return false;}
	if (pass.length < 5) {err = true; alert('Поле "пароль" не заповнено або пароль містить менше 5 символів!'); return false;}
	if ((confpass.length == 0) || (confpass != pass)) {err = true; alert('Поле вводу пароля не заповнено або пароль не збігається при перевірці!'); return false;}
	if (fname.length <= 1) {err = true; alert('Поле "ім`я" не заповнено!'); return false;}
	if ((cel.length == 0) || (cel == '+380')) {err = true; alert('Поле "номер телефону" не заповнено!'); return false;}
	if ((country.length == 0) || (town.length == 0)) {err = true; alert('Поле "домашня адреса" не заповнено!'); return false;}
	
	if (!err)
		{
			$.post("?action=register&state=2&nohead=1", {"email": email,"passw": pass,"fname": fname,"cel": cel,"icq": icq,"country": country,"town": town,"shipcountry": shipcountry,"shiptown": shiptown,"pagegoafter": pagegoafter}, function(data) {
				$('div#text').html(data);
			});
			return true;
		}
		else
			return false;
	}

//Відправка даних форми (підтвердження замовлення, крок 2->3)
function do_order(paymethod,delivery)
	{
	var err = false;
	if (paymethod.length <= 0 && delivery.length <= 0) 
		err = true;

	if (!err)
		{
		$.post("?action=order&state=3&nohead=1", {"paymethod": paymethod,"delivery": delivery}, function(data) {
				$('div#text').html(data);
			});
		return true;
		}
		else return false;
	}
