var now = 0, zindex = 1000, minweight = 1, uaVers = false;
var src_flash_img = 'img/1.jpg';
var flash_map = "<p><img src='/img/nofla/dadio.gif' alt=''></img></p>"

$(document).ready(function(){

	window.setTimeout(function(){
		sifr_enable();
		menu_enable();
		$("div.pods").hide();
		if ($("div.yarus_cont").length) yarus();		
	}, 500);
	
	$("input:checkbox").each(function(){
		if ($(this).attr("checked")) $(this).next("label").addClass("act");
		else $(this).removeClass("act");
	}).change(function(){
		if ($(this).attr("checked")) $(this).next("label").addClass("act");
		else $(this).next("label").removeClass("act");
	});
	
	$("label.other").click(function(){
		$(this).parents("p").next(".txt_hide").toggle("normal");
	});

	$("input:radio").each(function(){
		if ($(this).attr("checked")) $(this).next("label").addClass("active");
		else $(this).removeClass("active");
	}).change(function(){
		$("input:radio[name=" + $(this).attr("name") + "]").next("label").removeClass("active");
		$(this).next("label").addClass("active");
		if ($(this).parents("div.rasf").length) {
			calculate();
			calculate_wedding(true);
		}
	});
	
	$("div.nach label img").click(function(){
		$(this).parents(".nach").find("input:radio").attr("checked", "checked").change();									   
	});
	
	$("div.nach").bind("mouseover", function(){
		$(this).find("div.hint").css("visibility", "visible");	
	}).bind("mouseleave", function(){
		$(this).find("div.hint").css("visibility", "hidden");	
	});
	
	$("div.nach div.hint a").click(function(){
		__open($(this).attr("href"));
		return false;
	});

	$("input:checkbox, input:radio").css({"position":"absolute", "left": "-10000px"});

	$("select").each(function(){
		bind_select($(this));
	});

	prev();
	
	$("table.contentHolder tr:even td").css("background-color", "#2A1307");
	
	if ($("div.rank").length) alt($("div.rank img"));
	if ($("img.del_item").length) alt($("img.del_item"));	
	if ($(".editPr").length) alt($(".editPr"));

	
	$("label.imHover").bind("mouseover", function(){
		imHover($(this), $(this).next("input").val());
	}).bind("mouseout", function(){
		imUnHover($(this));
	});
	
	// bind calculator
	if ($(".calculate").length) $(".calculate").bind("change", function (e) { calculate(); calculate_wedding(true); });

	// bind wedding calculator
//	if ($("#people").length) $("#people").bind("change", function (e) { calculate_wedding(false); });
	if ($("#customweight").length) $("#customweight").bind("change", function (e){
		if ($(this).val() < minweight) {
			$("#customweight").val(minweight);
			alert("Указанный вес не соответствует выбранному количеству ярусов.");
		}
		calculate_wedding(true);
	});
	if ($("div.nach").length) $("div.nach input:radio").change(function(e) {calculate_wedding(true);})
	
	$("table.vanila input:text").bind("change", function(){
		var td = $(this).parents("td");
		td.next("td").text(parseInt(td.prev("td").text()) * parseInt($(this).val()));
	});
	
	wid();
	$(window).resize(function(){wid()});
	
	if ($("select#packing").length) packing_hover();
	
	if (window.navigator.userAgent.indexOf ("MSIE") >= 0){
		ua = 'Explorer';
		uaVers = window.navigator.userAgent.substr(window.navigator.userAgent.indexOf("MSIE")+5,3);
	}
	
	if (uaVers == 6) $("a.inputenter").not(".nothref").removeAttr("href");
	if ($("#form_id_4").length) $("#form_id_4").change(function(){
		$("div.nostandart").fadeOut();
		$("div.standart").fadeIn();
	});
	
	$("input[name=" + $("#form_id_4").attr("name") + "]").not("#form_id_4").change(function(){
		$("div.nostandart").fadeIn();
		$("div.standart").fadeOut();
	});

	not_flash();
	
});

function wid(){
	if ($(window).width() < 980) $("div.minheight").hide();
	else $("div.minheight").show();
}

function menu_enable(){
	$("div.menu ul li ul").each(function(){
		$(this).css({top: "0px", display:"none"});
	});

	$("div.menu ul li").not("div.menu ul li ul li").bind("mouseover", function(){
		$(this).find("ul").show();
	}).bind("mouseout", function(){
		$(this).find("ul").hide();
	});
	
	$("div.menu ul li").not("div.menu ul li ul li").each(function(){
		if ($(this).find("span").not("span span").length == 2) {
			$(this).find("span").not("span span").eq(0).css("top", "1px");
			$(this).find("span").not("span span").eq(1).css({"top": "20px", "position": "absolute", "left": "0px"});
		}
	});
	
	
} 

function sifr_enable(){
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({
			sSelector:"div.menu ul li span",
			sFlashSrc:"img/aquarelle.swf",
			sColor:"#FFFFFF",
			sLinkColor:"#FFFFFF",
			sHoverColor:"#FFFFFF",
			nPaddingTop:0,
			nPaddingBottom:0,
			sWmode:"transparent",
			sFlashVars:"textalign=center&offsetTop=0"
		}));	
		
		sIFR.replaceElement(named({
			sSelector:"h1",
			sFlashSrc:"img/aquarelle.swf",
			sColor:"#c8ad91",
			sLinkColor:"#c8ad91",
			sHoverColor:"#c8ad91",
			nPaddingTop:0,
			nPaddingBottom:0,
			sWmode:"transparent",
			sFlashVars:"textalign=left&offsetTop=0&offsetLeft=3"
		}));
		
		sIFR.replaceElement(named({
			sSelector:"h2",
			sFlashSrc:"img/aquarelle.swf",
			sColor:"#c8ad91",
			sLinkColor:"#c8ad91",
			sHoverColor:"#c8ad91",
			nPaddingTop:0,
			nPaddingBottom:0,
			sWmode:"transparent",
			sFlashVars:"textalign=left&offsetTop=0"
		}));		
		
		sIFR.replaceElement(named({
			sSelector:"div.tel",
			sFlashSrc:"img/acquest.swf",
			sColor:"#a08161",
			sLinkColor:"#a08161",
			sHoverColor:"#a08161",
			nPaddingTop:0,
			nPaddingBottom:0,
			sWmode:"transparent",
			sFlashVars:"textalign=left&offsetTop=0"
		}));
		
		
	}	
}

function page(el) {
	$("div.prev div").not("div.item").hide();
	$("div.prev div").not("div.item").eq(parseInt(el.text()) - 1).show();
	$("div.cart div.pager a.active").removeClass("active");
	el.addClass("active");
}

function prev() {
	
	$("div.prev div.item").bind("mouseover", function (){
		$(this).css("border", "1px solid #A08161");
	}).bind("mouseout", function(){
		$(this).css("border", "1px solid #fff");
	});
	
	$("div.prev div").not("div.item").not(":first").hide();
	$("div.cart div.pager a:first").addClass("active");	
	
	$("div.prev a").click(function(){
		var n = numfoto($("div.prev a"), $(this).attr("href"));	
		show_image(n);
		return false;
	});
	
	var nmFoto = numfoto($("div.prev div.item a"), $("div.prev div.active a").attr("href"));
	
	if (nmFoto == 0) $("a.prev_img").attr("id", "Fdis");
	else $("a.prev_img").removeAttr("id"); 
	
	if (nmFoto == $("div.prev a").length - 1) $("a.next_img").attr("id", "Ldis");
	else $("a.next_img").removeAttr("id", "Ldis");
	

	$("a.next_img").bind("click", function(){
		if (!$(this).attr("id")) {
			var n = numfoto($("div.prev a"), $("div.image img").attr("src"));
			show_image(n + 1);
		}
		return false;		
	});

	$("a.prev_img").bind("click", function(){
		if (!$(this).attr("id")) {										   
			var n = numfoto($("div.prev a"), $("div.image img").attr("src"));							   
			show_image(n - 1);
		}
		return false;
	});
}

function numfoto (links, src) {
	for (var i = 0; i < links.length; i++) {
		if (links.eq(i).attr("href") == src) return i;
	}
	return false;
}

function show_image(n){
	var mar_new = parseInt($("div.prev div.item").eq(n).css("margin-right").split("px")[0]);
	var mar_old = parseInt($("div.prev div.item.active").css("margin-right").split("px")[0]);
	
	if (mar_new == mar_old) var dx = 0;
	else var dx = 1;
	
	if (uaVers == 6) dx = 0;
	
	if (mar_old) $("div.prev div.item.active").css("margin-right", mar_old - dx + 'px');
	$("div.prev div.item.active").removeClass("active");
	
	if (mar_new) $("div.prev div.item").eq(n).css("margin-right", mar_new + dx + 'px');
	$("div.prev div.item").eq(n).addClass("active");	
	
	
	$("div.image img").hide();
	var href = $("div.prev a").eq(n).attr("href");
	imgPreloader = new Image();
	imgPreloader.src = href;
	imgPreloader.onload = function(){
		$("div.image img").attr("src", href).fadeIn();
	}
	
	if (n == 0) $("a.prev_img").attr("id", "Fdis");
	else $("a.prev_img").removeAttr("id"); 
	
	if (n == $("div.prev a").length - 1) $("a.next_img").attr("id", "Ldis");
	else $("a.next_img").removeAttr("id", "Ldis");
	
	now = n;
}

function del_from_cart(id) {
        target = document.getElementById('cartcmd');
	target.value = 'del';
	target = document.getElementById('cartid');
	target.value = id;
	document.cartform.submit();
}
function clr() {
	target = document.getElementById('cartcmd');
	target.value = 'clear';
	document.cartform.submit();
}

function filter_products() {
	var fselector='';
	$(".filter").each(function(e) {
		if ($(this).attr("checked")) fselector+=".filter_" + $(this).val() +",";
	});
	$(".item").css("opacity", "0.3");
	$(fselector).css("opacity", "1");
	$.cookie("filter", fselector, { path: '/'});
/*
	$("#filter_form").ajaxSubmit({success:function (d) {
		$(".product_holder").html($(d).next().next());
	}
	});
*/
}

function setPageId(id){
	$("#pagerId").val(id);
	filter_products();
}

function yarus(){
	$("div.yarus_cont").not(":first").hide();
	
/*	$("select.yarus").change(function(){
		alert($(this).val());
	});*/
}

function show_yarus(num) {
	$("div.yarus_cont").hide();
	$("div.yarus_cont").slice(0, num).show();
	if (num > 1){
		$("div.form").fadeOut();
		$("div.nostandart").fadeIn();
		$("div.standart").fadeOut();
	}
	else {
		$("div.form").fadeIn();
		if ($("#form_id_4").attr("checked")) {
			$("div.nostandart").fadeOut();
			$("div.standart").fadeIn();
		} 		
	}
	// pod or cake on cake
	$("div.pods p").hide();
	$("div.pods label").removeClass("active");
	switch (parseInt(num)) {
		// metal pod only
		case 7:
			$("div.pods").show();$("div.pods p:eq(2)").show(); 
			$("#podstavka2").next().addClass("active");
			$("#podstavka2").attr("checked", "checked");
			break;
		// pod or cake on cake
		case 2:
			$("div.pods").show();$("div.pods p:lt(2)").show(); 
			$("#tort").next().addClass("active");
			$("#tort").attr("checked", "checked");
			break;
		case 1:
			$("div.pods").hide();
			$("input[name='podstavka']").removeAttr("checked");
			break;
		// pod only
		default:
			$("div.pods").show();$("div.pods p:eq(0)").show(); 
			$("#podstavka").next().addClass("active");
			$("#podstavka").attr("checked", "checked");
			break;
		
	}
	$("div.footer").css("bottom", "0px");
}

function bind_select(sel){						   
	zindex = zindex - 1; 
	sel.wrap("<div class=head_sel style=z-index:" + zindex + "></div>").hide();
	sel.hide();
	var head = sel.parent();	
	head.append("<span></span><div class=opt_sel></div>");
	
	var cont = head.children().eq(2);
	cont.width(head.width());
	var span = head.children().eq(1);
	
	var num_selected = 0;
	var i = 0;

	sel.children().each(function(){
		cont.append("<div id=" + $(this).val() + ">" + $(this).text() + "</div>");
		if ($(this).attr("selected")) num_selected = i;
		i++;
	});
	
	span.text(sel.children().eq(num_selected).text());	
	
	var opt = cont.children();
	
	cont.find(":first").css("padding-top", "4px");
	cont.find(":last").css({"padding-bottom": "2px", "margin-bottom": "1px"});	
	
	span.bind("click", function(){
		cont.toggle("normal");
	});	
	
	opt.bind("click", function(){
		sel.val($(this).attr("id"));
		sel.change();
				
		if (sel.attr("class") == 'yarus'){
			show_yarus($(this).attr("id"));
			if ($(this).attr("id") > 1){
				$("div.packing").hide();
			}
			else $("div.packing").show();
			minweight = parseInt(sel.next().next("div.opt_sel").children().filter("div#" + sel.val()).text().split("от ")[1]);
			$("input#customweight").val(minweight);
			calculate_wedding(true);
		}
		
		span.text($(this).text()).attr("class", $(this).attr("id"));
		$(this).parent().hide("normal");
  	});
}

function flashVersion() {
      var ua = navigator.userAgent.toLowerCase();
      var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);
      var version = 0;
      var lastVersion = 11;
      var i;
      if (isIE) {
            try {
                  for (i = 3; i <= lastVersion; i++) {
                        if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')) {
                              version = i;
                        }
                  }
            } catch(e) {}
      } else {
            for (i = 0; i < navigator.plugins.length; i++) {
                  if (navigator.plugins[i].name.indexOf('Flash') > -1) {
                        version = (parseInt(navigator.plugins[i].description.charAt(16)) > version) ? parseInt(navigator.plugins[i].description.charAt(16)) : version;
                  }
            }
      }
      return version;
}

function order (button) {
	if ($("input.weight").val() == '0') {
		if (!button.parents(".big").next(".alert").length)
			button.parents(".big").after("<p class='alert'>Пожалуйста, укажите желаемый вес торта, чтобы оформить заказ.</p>");
	}
	else button.parents("form").get(0).submit();
}
function orderconfirm (button) {
	if (($("input[name='name']").val() == '') || ($("input.[name='email']").val() == '') || ($("input.[name='address']").val() == '')) {
		if (!button.parents(".big").next(".alert").length)
			button.parents(".big").after("<p class='alert'>Пожалуйста, заполните все обязательные поля.</p>");
	}
	else button.parents("form").get(0).submit();
}
function orderweight (button) {
	if ($("input[name='countproducts']").val() < minweight) {
		if (!button.parents(".buy").next(".alert").length)
			button.parents(".buy").after("<p class='alert'>Вес меньше минимального.</p>");
	}
	else button.parents("form").get(0).submit();
}


function callei() {
	thisMovie("map").print_map();
}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) return window[movieName]; else return document[movieName]
}

function alt(img) {
	img.bind("mouseover", function(){
		var code = '<div class="alt">' + $(this).attr("alt") + '</div>';
		$("body").append(code);
		$("div.alt").css({left: (getLeft(this) + 15), top: (getTop(this) + 15), display: "block"});
	}).bind("mouseout", function(){
		$("div.alt").fadeOut("normal", function(){
			$(this).remove();
		});	
	});
}


function getLeft(element) {
	result = element.offsetLeft;
	if (element.offsetParent) result += getLeft(element.offsetParent);
	return result;
}

function getTop(element) {
	result = element.offsetTop;
	if (element.offsetParent) result += getTop(element.offsetParent);
	return result;
}

function imHover(label, src){

		var code = '<div class="imBhover"><img src="' + src + '" /></div>';
		$("body").append(code);
		
		label.mousemove(function(e){
			$("div.imBhover").css({"left":e.pageX+11, "top":e.pageY+22});
		});
}

function imUnHover(label){
		$("div.imBhover").hide().remove();
		label.unbind("mousemove");
}

function calculate() {
	if (!$("#countproducts").length) return;
	var sum = 0;
	var sum_old = 0;
	// get amount
	var amount = parseInt($("#countproducts").val());
	// check portions select
	var pack_amount=amount;
	if (countporc && $("div.rasf").length && $("div.rasf input:checked").val() == 3) {
		// use portions
		sum=(price/countporc)*amount;
		sum_old=(price_old/countporc)*amount;
		pack_amount=1;
		$("span.cost span").text(Math.ceil(price/countporc));
	} else {
		// whole cake
		sum=price*amount;
		sum_old=price_old*amount;
		$("span.cost span").text(price);		
	}
	// add packing price
	//var pi = $("select[name='packing']");
	
	var pi = $("div.rasf input:checked");
	
	if (pi.length) {
		var psum=packing[parseInt(pi.val())];
		if (psum) {
			sum+=pack_amount*psum;
			sum_old+=pack_amount*psum;
		}
	}
	// show
	$("span.price").text(Math.ceil(sum).toFixed(0));
	$("span.price-old").text(Math.ceil(sum_old).toFixed(0));
}

function calculate_wedding(useWeight) {
	if (!$("#customweight").length) return;
	var weight=$("#customweight").val();
	var sum=$("input[name='fill']:checked").next().next().val();
	var discount=$("input[name='discount']").val();
	var people=$("#people").val();
	var weight_per_people=0.17;
	if (useWeight) {
		sum=weight*sum;
		people=Math.round(weight/weight_per_people);
	} else {
		weight=Math.ceil(people*weight_per_people*10)/10;//.toFixed(1)
		sum=weight*sum;
	}
	if (discount) {
		sum_old=sum;
		sum=(100-discount)/100*sum;
	}
	// add packing price
	var pi=$("select[name='packing']");
	if (pi.length) {
		var psum=packing[pi.val()];
		if (psum) {
			sum+=psum;
			sum_old+=psum;
		}
	}
	// child cake with non-standart form
	if ($("input[name='cakeform']").length && $("input[name='cakeform']:checked").val()==4) {
		$("#total_calc").hide();
		$("#child_form").show();
	} else {
		// show
		$("#total_calc").show();
		$("#child_form").hide();
		$("span.price").text(Math.ceil(sum).toFixed(0));
		$("span.price-old").text(Math.ceil(sum_old).toFixed(0));
	}
	
	if ((useWeight == false) && (weight < minweight)) {
//		alert(weight);
//		alert("Количество людей не соответствует выбранному количеству ярусов.");
		$("#customweight").val(minweight);
		calculate_wedding(true);
		return;
	}

	if (useWeight) $("#people").val(people);
	$("#customweight").val(weight);
}

function packing_hover(){
	var sel = $("select#packing");
	var span = sel.parents("div.head_sel").find("span");
	span.bind("mouseover", function(){
		if ($(this).attr("class").length){
			var src = $("#pack_img_" + $(this).attr("class")).val();
			if (src) imHover($(this), src);
		}
	}).bind("mouseout", function(){
			imUnHover($(this));
	});
	var option = span.next();
	option.children().each(function(){
		var opt = $(this);
		opt.bind("mouseover", function(){
			if ($(this).attr("id").length) {
				var src = $("#pack_img_" + $(this).attr("id")).val();
				if (src) imHover($(this), src);
			}
		}).bind("mouseout", function(){
			imUnHover($(this));
		});
	});
	
}

function flashVersion() {
      var ua = navigator.userAgent.toLowerCase();
      var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);
      var version = 0;
      var lastVersion = 11;
      var i;
      if (isIE) {
            try {
                  for (i = 3; i <= lastVersion; i++) {
                        if (eval('new ActiveXObject("ShockwaveFlash.ShockwaveFlash.'+i+'")')) {
                              version = i;
                        }
                  }
            } catch(e) {}
      } else {
            for (i = 0; i < navigator.plugins.length; i++) {
                  if (navigator.plugins[i].name.indexOf('Flash') > -1) {
                        version = (parseInt(navigator.plugins[i].description.charAt(16)) > version) ? parseInt(navigator.plugins[i].description.charAt(16)) : version;
                  }
            }
      }
      return version;
}

function not_flash(){
	if (flashVersion() == 0){
		$("div.flash").children().remove().end().html("<img src='" + src_flash_img + "' />");
		$("h1").css("height", "auto");
		$("div.tel").css("margin-top", "0px");
		$("div.conttel").css("margin", "0.5em 0em").find(".tel").css("font-size", "21px");
		$("p.flash_map").replaceWith(flash_map);
	}
	else return false;
}
