$(function() {
	emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	phoneReg = /^[0-9]{10,10}?$/;
	anyReg = /^.*$/;
	//textReg = /^[А-Яа-я]*$/;

	var regulerPatterns = {
		email : emailReg,	
		phone : phoneReg,	
		def : anyReg	
	};
	
	
	$("a#ajaxItems").click(function() {
		var key = false;
		$.getJSON("/?random="+Math.random(),
        function(data){
			$.each(data, function(i,value){
				key = i+1;
				$("div#product_month"+key).html(value);
			});
			$("a#ajaxItems").removeClass('pressed');
        });
		$(this).addClass('pressed');
		return false;		
	});
		
	
	$("form.autovalidate").each(function() {
		var form = $(this);
		var formId = form.attr('id');
		var inputs = form.find('input, textarea').not(".ignore, [type='submit'], [type='button']");
		var inputs_ign = form.find('input.ignore');
		var submitBtn = form.find("input#submit");
		var ajax = form.attr("ajax");
		var errors = {};
		
		//console.log(inputs);
		
		/*inputs_ign.keyup(function(){
			var id = $(this).attr('id');
			var value = $.trim($(this).val());							
			var valid = textReg.test(value);
			//console.log(value, req, hasVal, regPatern, valid);
			if (valid){
				$(this).removeClass('error');
				delete (errors[id]);
			} else {
				$(this).addClass('error');
				errors[id] = 1;
			}
			return true;
		});*/
		
		inputs.each(function(){
			var id = $(this).attr('id');			
			var req = $(this).attr('required') == 1 || $(this).attr('req') == 1;
			var ok_mark = $(this).parent().parent().find("div.ok_form");			
			var regPatern = (regulerPatterns[id]) 
				? regulerPatterns[id]
				: regulerPatterns.def;	
			//console.log(id, regPatern);	
			$(this).keyup(function(){
				var value = $.trim($(this).val());				
				var hasVal = !req || value;				
				var valid = hasVal && regPatern.test(value);	
				//console.log(value, req, hasVal, regPatern, valid);
				if (valid && $(this).val()!=""){
					if (hasVal){
						ok_mark.fadeIn(100);
					}					
					$(this).removeClass('error');
					$(this).parent().next().children("div.no_form").hide();
					delete (errors[id]);
				} else {
					ok_mark.fadeOut(100);
					$(this).addClass('error');
					errors[id] = 1;
				}
				return true;
			});
			var valueOnStart = $.trim($(this).val());	
			var validOnStart = !req || valueOnStart && regPatern.test(valueOnStart);
			//console.log(id, valueOnStart, validOnStart);
			if (validOnStart){
				if (valueOnStart && $(this).val()!="") {
					ok_mark.show();
					$(this).parent().next().children("div.no_form").hide();
				}				
			} else {
				ok_mark.hide();
				errors[id] = 1;
				if (valueOnStart) {
					$(this).addClass('error');
				}
			}
			//console.log(errors);
		});	
		//console.log(errors);
		$(this).keyup(function(){
			//console.log(errors);
			if (!jQuery.isEmptyObject(errors) && $(this).val()==""){
				//console.log(errors);
				//submitBtn.addClass('noactive');
			} else {
				//submitBtn.removeClass('noactive');
			}
		});
		$(this).keyup();		
		
		scsFunction = (formId == 'contacts') ? messageSent : null;			
		
		$(this).submit(function(){
			inputs.keyup();			
			if (jQuery.isEmptyObject(errors)){
				$("div.no_form").hide();
				if (ajax){
					var formInput = $(this).serialize();
					$.post(
						$(this).attr('action'),
						formInput,
						scsFunction
					);
				}else{
					return true;
				}
			} else {
				//console.log(errors);
				$(this).find(".error").parent().next().children("div.ok_form").hide();
				$(this).find(".error").parent().next().children("div.no_form").fadeIn(100);
				$(this).find(".error:first").focus();
				return false;
			}
		});
	});
	
		
	function messageSent(data){
		$("span#postRequire").html("<h2>Ваше сообщение успешно отправлено!</h2>");
	}
	
	$("form#contacts").submit(function() {
		var fields = $(this).find(":input").serializeArray();
		var hasError = false;
		$.each(fields, function(i, field){ 
			if(field.name == "email" ) {
				if(!emailReg.test($.trim(field.value)) || field.value == "") {
					hasError = true;
				}
			}else if(field.name == "message") {
				if(field.value == "") {
					hasError = true;
				}
			} else {
				$("form#basket").find("div.ok_form").fadeIn(100);
			}
		});
		if(!hasError) {
			if($(this).attr('id') == "contacts") {
				var formInput = $(this).serialize();
				$.post($(this).attr('action'),formInput, function(data){
					$("span#postRequire").html("<h2>Ваше сообщение успешно отправлено!</h2>");
				});
			}else if($(this).attr('id') == "basket") {
				$(this).submit();
			}
		}
		return false;
	});
	
	$("form#address").submit(function() {
		if($("input#adress").val().length > 0 || $('#type_delivery2').is(':checked')) {
			return true;
		} else {
			$("input#adress").addClass("error");
			return false;
		}
	});

	$("input#adress").keyup(function() {
		if($(this).val().length > 0) {
			$("input[class*='noactive']").removeClass("noactive").addClass("active");
			$(this).removeClass("error");
		} else {
			$("input[class*='active']").removeClass("active").addClass("noactive");
			$(this).addClass("error");
		}
	});
	
	$("div.b_left_n2 input[type=radio]").click(function() {
		var delivery = parseFloat($(this).parent().find("input[type=hidden]").val());
		var total_price = parseFloat($("div#total_price").text());
		if(total_price > 2000) total_price -= 200;
		var newsum = delivery+total_price;
		$("div.sum span.big").text(newsum);
		delivery = (delivery == 0)
			? "бесплатно"
			: delivery + ' руб.';
		$("div.b_left_n1 span.attention").text(delivery);
	});
	
	$("div.type_delivery input").click(function() {
		var total_price = parseFloat($("div#total_price").text());
		var newsum = Math.ceil(total_price*0.95);		
		if($(this).attr("id") == "type_delivery2") {
			$('tr.delivery_details').hide();
			$('tr.discount', 'table.total_list').show();			
			$("div.sum span.big").text(newsum);
			$("input#adress").attr("disabled",true);
			$("div.b_left_n2 input").attr("disabled",true);
			$("div.b_left_n1 span.attention").text("бесплатно");
			$("input[class*='noactive']").removeAttr("disabled").removeClass("noactive").addClass("active");
			$("span#with_deliv").hide();
		} else {
			if(total_price > 2000) total_price -= 200;
			$('tr.delivery_details').show();
			$("span#with_deliv").show();
			$('tr.discount', 'table.total_list').hide();
			var delivery = parseFloat($("div.b_left_n2 :input[checked]").parent().find("input[type=hidden]").val());
			newsum = total_price+delivery;
			$("div.sum span.big").text(newsum);
			delivery = (delivery == 0)
				? "бесплатно"
				: delivery + ' руб.';
			$("div.b_left_n1 span.attention").text(delivery);
			$("input#adress").removeAttr("disabled");
			$("div.b_left_n2 input").removeAttr("disabled");
			if($("input#adress").val().length == 0) {
				$("input[class*='active']").removeClass("active").addClass("noactive");
			}
		}
	});	
	$("div.type_delivery input:checked").click();
		
	
	if($("#dinamic_menu").length > 0){
		var topSpace = -350;
		var botoomSpace = 200;
		
		//var topLimit = $("#dinamic_menu").offset().top;
	    var topLimit = 0;
	    //var bottomLimit = $("#content").offset().top + $("#content").height() - $("#dinamic_menu").height() - botoomSpace ;
	    var bottomLimit = $("#content").height() - $("#dinamic_menu").height() - botoomSpace ;
	    
	    $(window).scroll(function() {
	    	var pos = $(window).scrollTop() + topSpace;
	    	if(pos < topLimit){
	    		$("#dinamic_menu").stop(true).animate({top:topLimit});
	    	}else if (pos > bottomLimit) {
	    		$("#dinamic_menu").stop(true).animate({top:bottomLimit});
	        } else {            
	            $("#dinamic_menu").stop(true).animate({top:pos});
	        }
	    });
	    $(window).scroll();
    }
	
	var basket = $('#basket');
	var basket_price = $('#ItemsSum',basket);
	var basket_count = $('#ItemsCount',basket);
	
	$('.good_icons').each(function(){
		var item_id = $(this).attr('item');
		var plus = $('.plus',this); 
		var minus = $('.minus',this); 
		var set = $('.add_to_basket',this); 
		var rem = $('.remove_from_basket',this); 
		var count = $('.count_val',this); 
		$(this).data('plus',plus);
		$(this).data('minus',minus);
		$(this).data('count',count);
		$(this).data('rem_but',rem);
		$(this).data('set_but',set);
				
		plus.click(function(){
			count.text(parseInt(count.text())+1);
			minus.show();
		});
		minus.click(function(){
			var val = parseInt(count.text());
			if (val > 1){
				count.text(val-1);
			}
			if (val == 2){
				$(this).hide();
			}
		});
		if (parseInt(count.text()) < 2){
			minus.hide();
		}
		set.click(function(){
			$.post(
				'/catalog/ajax',
				{	action:'setToBasket', 
					item:item_id, 
					count:parseInt(count.text())
				},
				rebuildBasket,
				'json'
			);
			return false;
		});
		rem.click(function(){
			$.post(
				'/catalog/ajax',
				{	action:'removeFromBasket', 
					item:item_id 
				},
				rebuildBasket,
				'json'
			);
			return false;
		});
	});
	
	$('.plus').click(function(){return false;});
	$('.minus').click(function(){return false;});
	
	
	$('.more_info').click(function(){
		var info = $(this).parents('.recipe_block').eq(0);
		if ($(this).hasClass('opend')){	
			$('.short_text',info).delay(210).fadeIn(200);
			$('.full_text',info).fadeOut(200);	
			$('.show_info',info).delay(210).fadeIn(200);
			$('.hide_info',info).delay(200).fadeOut(0);		
			$(this).removeClass('opend');			
		} else {
			$('.short_text',info).fadeOut(200);
			$('.full_text',info).delay(210).fadeIn(200);	
			$('.hide_info',info).delay(210).fadeIn(200);
			$('.show_info',info).delay(200).fadeOut(0);
			$(this).addClass('opend');
		}
		return false;
	});
	
	$("td.count input").click(function() {
		$(this).select();
	});
	
	$("td.price a.close").click(function() {
		var href = $(this).attr("href");
		$.post(href, function(data) {
			$("a[href|='"+href+"']").parent().parent().parent().remove();
			var sum = $("table.table_list").find("td.price b").get();
			var newsum = 0;
			$.each(sum, function() {
				newsum -= $(this).text();
			});
			$("div.sum span.big").text(newsum*-1);
			
			if(data == "empty") {
				$("div.outtable_list").html("<h2 style='color:#fff;'>Корзина пуста!</h2>");
			}
		});
		return false;
	});
	
	$("td.count input").keyup(function() {
		var price = $(this).parent().parent().find("td span.this_price").text();
		var count = $(this).val();
		var nm = /^[0-9 ]+$/;
		if(!nm.test($.trim(count)) || count < 1) {
			$(this).val("1");
			count = price;
		} else {
			count = price*count;
		}
		$(this).parent().parent().find("td.price b").text(count);
		var sum = $("table.table_list").find("td.price b").get();
		var newsum = 0;
		$.each(sum, function() {
			newsum -= $(this).text();
		});
		$("div.sum span.big").text(newsum*-1);
	});
	
	hs.registerOverlay({
		html: '<div class="closebutton" onclick="return hs.close(this)" title="Закрыть"></div>',
		position: 'top right',
		fade: 2 // fading the semi-transparent overlay looks bad in IE
	});
	
   $.fn.alignCenter = function() {
      //get margin left
      var marginLeft =  - $(this).width()/2 + 'px';
      //get margin top
      var marginTop =   ($(window).height()-$(this).height())/2+$(document).scrollTop() + 'px';
      //return updated element
	  if ($(this).hasClass('fixed'))
	  {
		var marginTop =  - $(this).height()/2 + 'px';
		}
      return $(this).css({'margin-left':marginLeft, 'margin-top':marginTop});
   };
	
   $.fn.togglePopup = function(n){
     if($(this).find('.popup').hasClass('hidden') && n != true)
     {
       //hidden - then display
       //when IE - fade immediately
      $(this).find('.overlay').height($(document).height()).removeClass('hidden').fadeTo('slow', 0.7).click(function(){$(this).togglePopup();});
	  $(this).find('.popup').removeClass('hidden');
	  
		$(this).find('.popup_rounded').alignCenter();
		//$('#popup_content').html($(this).html());
		if($(this).find('.popup_rounded').hasClass('hidden')) {$(this).find('.popup_rounded').removeClass('hidden');};
     }
     else
     {
       //visible - then hide
	   $(this).find('.overlay').fadeOut('slow', 0);
       $(this).find('.popup').addClass('hidden');
	   //$('#popup_content').html('');
	   $(this).find('.popup_fixed').html('');
	   $(this).find('.popup_rounded').addClass('hidden');
	   //setTimeout("$('.overlay').toggleClass('hidden').removeAttr('style').unbind('click');",500);
     }
 };
	
	var cat_id_href = /[0-9]+/.exec(window.location.href);
	var catid = "" + cat_id_href;
	var ln_catid = catid.length;
	if (window.location.href.slice(length-11-ln_catid)=="recipes#cat"+cat_id_href) {
		$("#cat0").parent("li").removeClass("active");
		$("#cat"+cat_id_href).parent("li").addClass("active");
		$("div.recipe_items").hide();
		$("div#show"+cat_id_href).show();
	}
 
	$("ul#menu_recipes a").click(function() {
		$(this).parent().parent().find("li").removeClass("active");
		$(this).parent().addClass("active");
		var cat_id = /[0-9]+/.exec($(this).attr("id"));
		if(cat_id > 0) {
			$("div.recipe_items").hide();
			$("div#show"+cat_id).show();
			if (window.location.href.slice(length-7)=='recipes') {
				window.location.href=window.location.href+"#cat"+cat_id;
			}
			else {
				var cat_id_href = /[0-9]+/.exec(window.location.href);
				var catid = "" + cat_id_href;
				var ln_catid = catid.length;
				window.location.href=window.location.href.slice(0,length-ln_catid)+cat_id;
			}
		} else {
			$("div.recipe_items").show();
		}		
		return false;
	});
	
	$('a.noreload').click(function(){return false;}); // оставлять в самом низу
});

function rebuildBasket(data){
	if (data.error == 1){
		var mess = "Ошибка при обработке запроса: \n " + data.errors.join("\n");
		alert(mess);
	};
	var item = $('#item_'+data.item.id+'_basket');	
	if (item.length > 0){
		count = item.data('count');
		if (data.item != undefined){
			if (item.find("a.close.remove_from_basket").css("display")=="none") $("div#inbasket_"+data.item.id).find("b").text("0");
			if (item.data('time') == undefined || item.data('time') < data.item.time){
				item.data('time',data.item.time);
				if (data.item.del == true){
					count.text(1);
					item.data('minus').hide();
					item.data('rem_but').hide();
					$("div#inbasket_"+data.item.id).css("display","none");
					$("div#inbasket_"+data.item.id).find("b").text("0");
				}else{
					if ($("div#inbasket_"+data.item.id).css("display","block").find("b").text()!=data.item.count) { 
						item.data('rem_but').parent().parent().prev().children("div.good_img").children("div.add_circle").fadeIn(1000).delay(100).fadeOut(2000);
					}
					count.text(data.item.count);
					$("div#inbasket_"+data.item.id).css("display","block").find("b").text(data.item.count);
					item.data('rem_but').show();					
				}				
			}else{
				console.log('item out of time: '+item.data('time')+' > '+data.item.time);
			}
		}else{
			console.log('item undefined in responce');
		}
	}else{
		alert('Товар '+data.item.id+' не найден в каталоге');
	}
	
	var basket = $('#basket');	
	if (basket.length > 0){
		if (data.order != undefined){
			if (basket.data('time') == undefined || basket.data('time') < data.order.time){
				basket.data('time',data.order.time);
				$('#ItemsSum',basket).text(data.order.total_price);
				$('#ItemsCount',basket).text(data.order.total_count);
				$('#word_items',basket).text(data.order.word_items);
				if (data.order.total_count > 0){
					basket.find('#basket_run_order').show();
				}else{
					basket.find('#basket_run_order').hide();
				}
			}else{
				console.log('order out of time: '+basket.data('time')+' > '+data.order.time);
			}
		}else{
			console.log('order undefined in responce');
		}
	}else{
		console.log('basket not found');
	}
	
}
