$(document).ready(function() {
	if($.flash.available) {
		$("#logo").flash({
			swf: '/swf/logo.swf',
			width: 308,
			height: 49
		});
	}
	
	$(".menu > ul > li").hover(
		function() {
			$(this).find("div.submenu").stop(true, true).slideDown();
		}, 
		function() {
			$(this).find("div.submenu").stop(true, true).slideUp();
		}
	);
	
	$(".footer_menu > ul > li").hover(
		function() {
			var $submenu = $(this).find("div.submenu");
			var $liHeight = $(this).height();
			var $submenuHeight = $submenu.height();
			if($.browser.msie && ($.browser.version == "7.0" || $.browser.version == "6.0")) {
				var $liWidth = $(this).width();
				$submenu.css({
					"margin-top":"-"+($liHeight+$submenuHeight)+"px", 
					"margin-left":"-"+($liWidth+10)+"px"
				}).stop(true, true).slideDown();
			} else {
				$submenu.css({"margin-top":"-"+($liHeight+$submenuHeight+20)+"px"}).stop(true, true).slideDown();
			}
		}, 
		function() {
			$(this).find("div.submenu").stop(true, true).slideUp();
		}
	);
	
	$(".dialog_link").click(function() {
		$($(this).attr("href")).dialog("open");
		return false;
	});
	
	$("#feedback").dialog({
		autoOpen: false, 
		width: 510, 
		minHeight: 10, 
		modal: false, 
		resizable: false, 
		draggable: true, 
		zIndex: 10000, 
		title: "Обратная связь", 
		dialogClass: "dialog dialog_feedback", 
		closeOnEscape: true, 
		position: ['right', 'bottom']
	});
	
	$("#form_feedback").submit(function() {
		$(this).find("label.red").removeClass("red");
		$(this).find(".error").addClass("hidden");
		var error;
		error = 0;
		var thisId;
		thisId = $(this).attr("id");
		var $form = $(this);
		
		$(this).find(".required").each(function() {
			if($(this).val() == '') {
				$("#"+thisId+" label[for='"+$(this).attr("id")+"']").addClass("red");
				error++;
			}
		});
		
		if(error == 0) {
			$.post("/ajax/feedback.php", $(this).serialize(), 
			function(data) {
				if(data == "success") {
					$form.replaceWith('<p>Мы приняли сообщение и скоро свяжемся с Вами</p>');
				}
			});
		} else {
			$(this).find(".error").removeClass("hidden");
		}
		
		return false;
	});
	
	$("#subscribe_from").submit(function() {
		$(this).find("label.red").removeClass("red");
		$(this).find(".error").addClass("hidden");
		var error;
		error = 0;
		var thisId;
		thisId = $(this).attr("id");
		var $form = $(this);
		
		$(this).find(".required").each(function() {
			if($(this).val() == '') {
				$("#"+thisId+" label[for='"+$(this).attr("id")+"']").addClass("red");
				error++;
			}
		});
		
		if(!isValidEmail($(this).find("#EMAIL").val())) {
			$("#"+thisId+" label[for='EMAIL']").addClass("red");
			error++;
		}
		
		if(error == 0) {
			$.post("/ajax/subscribe.php", $(this).serialize(), 
			function(data) {
				$form.replaceWith(data);
			});
		} else {
			$(this).find(".error").removeClass("hidden");
		}
		
		return false;
	});
	
	$(".scroll_left").click(
		function() {
			//$(".collection_grid").animate({left : $(".collection_grid").position().left + 200}, 200, function() {});
			if($(".collection_grid:animated").length <= 0) {
				hoverScroll($(".collection_grid"), "left", 800);
				//hoverScroll($(".collection_grid"), "left", "500");
			}
			return false;
		}
	);
	
	$(".scroll_right").click(
		function() {
			//$(".collection_grid").animate({left : $(".collection_grid").position().left + 200}, 200, function() {});
			if($(".collection_grid:animated").length <= 0) {
				hoverScroll($(".collection_grid"), "right", 800);
			}
			return false;
		}
	);
	
	/*$(".ll_grid a").click(function() {
		return true;
	});*/
	
	$(".collection_block a").click(function() {
		if($(this).parents(".ll_grid").length > 0) {
			return true;
		}
		$.ajax({
			url: $(this).attr("href"),
			dataType: "json",
			success: function(data) {
				if($(".overlay").length <= 0) {
					$(".container").append('<div class="overlay"></div>');
				}
				$(".container").append('<div class="detail_photo_item"><div class="container"><img src="/i/loading.gif" class="loading" /></div></div>');
				moveDetailCollectionItem();
				$(".detail_photo_item img.loading").css({
					"margin-top":($(".container").height() / 2 - $("img.loading").height() / 2)+"px"
				});
				loadPhotoDetail(data);
			}, 
			error: function() {
			}
		});
		return false;
	});
	
	$("a.lightbox").lightBox();
	
	$(".content table tr td:last-child").addClass("last");
	
	$("#check_discount").submit(function() {
		var $form = $(this);
		$.post($(this).attr("action"), $(this).serialize(), 
		function(data) {
			$form.hide();
			$form.before(data);
			//$form.replaceWith(data);
		});
		return false;
	});
	
	$(".collection_grid .item a img, .trends_item a img").hover(
		function() {
			/*var $imgHeight = $(this).height();
			var $imgWidth = $(this).width();
			$(this).parents(".item, .trends_item").css({
				"background": "#ffffff"
			});
			$(this).css({opacity: .8});*/
			$(".collection_grid .item img, .trends_item img").css({opacity: .4});
			$(this).css({opacity: 1});
		}, 
		function() {
			/*$(this).parents(".item").css({
				"background": "transparent"
			})
			$(this).css({opacity: 1});*/
			$(".collection_grid .item img, .trends_item img").css({opacity: 1});
		}
	);
	$("a.show_hide").click(function() {
		if($($(this).attr("href")+":visible").length > 0) {
			$($(this).attr("href")).slideUp(1000, function() {
				resizeScrollBlock();
			});
			$(this).removeClass("bold");
		} else {
			$($(this).attr("href")).slideDown(1000, function() {
				resizeScrollBlock();
			});
			$(this).addClass("bold");
		}
		return false;
	});
	
	$("#form_fr").submit(function() {
		var error = 0;
		$(this).find(".red").removeClass("red");
		$(this).find(".form_error").addClass("hidden");
		$(this).find(".form_desciption").removeClass("hidden");
		
		var fname = $(this).find("input[name='NAME']");
		var femail = $(this).find("input[name='EMAIL']");
		var fphone = $(this).find("input[name='PHONE']");
		
		if(fname.val() == '') {
			$(this).find("label[for='"+fname.attr("id")+"']").addClass("red");
			error++;
		}
		
		if(femail.val() == '') {
			$(this).find("label[for='"+femail.attr("id")+"']").addClass("red");
			error++;
		}
		
		if(fphone.val() == '') {
			$(this).find("label[for='"+fphone.attr("id")+"']").addClass("red");
			error++;
		}
		
		if(error > 0) {
			$(this).find(".form_desciption").addClass("hidden");
			$(this).find(".form_error").removeClass("hidden");
			$(this).find(".form_error").addClass("red");
			return false;
		}
		
		$.post("/ajax/fr_send.php", $(this).serialize(), 
		function(data) {
			$("#form_fr_wrap").html(data);
		});
		
		return false;
	});
	
	$(".tooltip").mouseover(function(emouse) {
		$(".tooltip_block").text($(this).attr("title"));
		$(this).data("title", $(this).attr("title")).removeAttr("title");
		$(".tooltip_block").css({left : emouse.pageX - $(".tooltip_block").width()/4 + 5, top : emouse.pageY +  15}).show();
		return false;
	}).mousemove(function(emouse){
		$(".tooltip_block").css({left : emouse.pageX - $(".tooltip_block").width()/4 + 5, top : emouse.pageY + 15});
	}).mouseout(function() {
		$(".tooltip_block").hide();
		$(this).attr({"title":$(this).data("title")});
	});
	
	$(".cottage_plan area").hover(
		function() {
		}, 
		function() {
			$("div.tooltip_block").hide();
			return false;
		}
	);
	
	$(".shops_scroll_left").click(function() {
		$(".shops_gallery img.current").fadeOut("500", function() {
			if($(this).prev("img").length > 0) {
				$(this).removeClass("current").prev().fadeIn("500").addClass("current");
			} else {
				$(this).removeClass("current");
				$(".shops_gallery img").last().fadeIn("500").addClass("current");
			}
		});
		return false;
	});
	$(".shops_scroll_right").click(function() {
		$(".shops_gallery img.current").fadeOut("500", function() {
			if($(this).next("img").length > 0) {
			$(this).removeClass("current").next().fadeIn("500").addClass("current");
			} else {
				$(this).removeClass("current");
				$(".shops_gallery img").first().fadeIn("500").addClass("current");
			}
		});
		return false;
	});
	
	$(".ll_content a").unbind("click");
});

function resizeScrollBlock() {
	$('.scroll_block').each(function() {
		var api = $(this).data('jsp');
		var throttleTimeout;
		if ($.browser.msie) {
			// IE fires multiple resize events while you are dragging the browser window which
			// causes it to crash if you try to update the scrollpane on every one. So we need
			// to throttle it to fire a maximum of once every 50 milliseconds...
			if (!throttleTimeout) {
				throttleTimeout = setTimeout(
					function()
					{
						api.reinitialise();
						throttleTimeout = null;
					},
					50
				);
			}
		} else {
			api.reinitialise();
		}
	});
}

function loadPhotoDetail(data) {
	var newHtml;
	myImage = new Image();
	myImage.src = data.IMAGE;
	myImage.onload = function() {
		newhtml = '<img src="'+myImage.src+'" class="collection_image hidden" />';
		$(".detail_photo_item .container").fadeOut("400", function() {
			$(this).remove();
			$(".detail_photo_item").html('<div class="container">'+newhtml+'</div>');
			var newWidth = myImage.width * $(".detail_photo_item").height() / myImage.height;
			$(".detail_photo_item").animate({
				"width": newWidth+"px", 
				"left": ($(".wrap .container").width() / 2 - newWidth / 2) + "px"
			}, function() {
				$("img.collection_image").css({
					"height": $(".detail_photo_item").height()+"px", 
					"width": newWidth+"px"
				}).fadeIn(400);
				
				if(data.NEXT != undefined) {
					$(".detail_photo_item .container").append('<a href="'+data.NEXT+'" class="scroll_right"></a>');
				}
				if(data.PREV != undefined) {
					$(".detail_photo_item .container").append('<a href="'+data.PREV+'" class="scroll_left"></a>');
				}
				$(".detail_photo_item .scroll_left, .detail_photo_item .scroll_right").each(function() {
					$(this).css({
						"top" : ($(this).parent().height() / 2 - $(this).height() / 2)+"px"
					});
				});
				
				$(".detail_photo_item .container").append('<div class="detail_photo_info clearfix"><div class="left"><a href="/ajax/like.php?ID='+data.ID+'" class="like_item_collection"><img src="/i/i_like.png" /></a> <span class="like_item_collection_result">('+data.LIKE+')</span></div><ul class="right"></ul></div>');
				$(".detail_photo_info").css({
					"left": ($(".detail_photo_info").parent().width() / 2 - ($(".detail_photo_info").width() + 40) / 2) + "px"
				});
				if(data.PREVIEW_TEXT != undefined) {
					$(".detail_photo_item .container div.detail_photo_info ul.right").append('<li><a href="#" class="show_detail_photo_info"></a></li>');
					$(".detail_photo_item .container").append('<div class="detail_photo_info_detail hidden"><a href="#" class="close"></a><h1>'+data.NAME+'</h1>'+data.PREVIEW_TEXT+'</div>');
					if($(".detail_photo_info_detail").width() + 80 > $(".detail_photo_info_detail").parent().width()) {
						$(".detail_photo_info_detail").width($(".detail_photo_info_detail").parent().width() - 80);
					}
					$(".detail_photo_info_detail").css({
						"left": ($(".detail_photo_info_detail").parent().width() / 2 - ($(".detail_photo_info_detail").width() + 40) / 2) + "px"
					});
				}
				$(".detail_photo_item .container div.detail_photo_info ul.right").append('<li><a href="#" class="share"></a></li><li><a href="#" class="full_size"></a></li><li class="last"><a href="#" class="close"></a></li>');
				$(".detail_photo_item .container").append('<div class="detail_photo_info_share hidden"><a href="#" class="close"></a><!-- AddThis Button BEGIN --><div class="addthis_toolbox_s addthis_default_style addthis_32x32_style"><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a><a class="addthis_counter addthis_bubble_style"></a></div><!-- AddThis Button END --></div>');
				addthis.init();
				addthis.toolbox(".addthis_toolbox_s");
				if($('meta[property="og:image"]').length > 0) {
					$('meta[property="og:image"]').attr({"content":myImage.src});
				} else {
					$("head").prepend('<meta property="og:image" content="'+myImage.src+'">');
				}
				if($(".detail_photo_info_share").width() + 80 > $(".detail_photo_info_share").parent().width()) {
					$(".detail_photo_info_share").width($(".detail_photo_info_share").parent().width() - 80);
				}
				$(".detail_photo_info_share").css({
					"left": ($(".detail_photo_info_share").parent().width() / 2 - ($(".detail_photo_info_share").width() + 40) / 2) + "px"
				});
				//$(".detail_photo_item .container div.detail_photo_info ul.right").append('<li><a href="#" class="full_size"></a></li><li class="last"><a href="#" class="close"></a></li>');
				
				$(".detail_photo_item a.scroll_left, .detail_photo_item a.scroll_right").click(function() {
					$("div.detail_photo_item div.container").html('<img src="/i/loading.gif" class="loading" />');
					moveDetailCollectionItem();
					$(".detail_photo_item img.loading").css({
						"margin-top":($(".container").height() / 2 - $("img.loading").height() / 2)+"px"
					});
					$.ajax({
						url: $(this).attr("href"),
						dataType: "json",
						success: function(data) {
							loadPhotoDetail(data);
						}, 
						error: function() {
						}
					});
					
					return false;
				});
				
				$(".detail_photo_item .detail_photo_info a.close, .overlay").click(function() {
					$('meta[property="og:image"]').remove();
					$(".detail_photo_item").remove();
					$(".overlay").remove();
					return false;
				});
				
				$(".detail_photo_item .detail_photo_info a.like_item_collection").click(function() {
					if(!$(this).hasClass("disabled")) {
						$.ajax({
							url: $(this).attr("href"),
							success: function(data) {
								$(".detail_photo_item .detail_photo_info a.like_item_collection").addClass("disabled");
								if(data) {
									$(".detail_photo_item .detail_photo_info span.like_item_collection_result").text("("+data+")");
								}
							}
						});
					}
					return false;
				});
				
				$(".detail_photo_item .detail_photo_info a.show_detail_photo_info").click(function() {
					$(".detail_photo_item .detail_photo_info").slideUp(400, function() {
						$(".detail_photo_item .detail_photo_info_detail").slideDown(400);
						$(".detail_photo_item .detail_photo_info_detail a.close").click(function() {
							$(".detail_photo_item .detail_photo_info_detail").slideUp(400, function() {
								$(".detail_photo_item .detail_photo_info").slideDown(400);
							});
							return false;
						});
					});
					return false;
				});
				
				$(".detail_photo_item .detail_photo_info a.share").click(function() {
					$(".detail_photo_item .detail_photo_info").slideUp(400, function() {
						$(".detail_photo_item .detail_photo_info_share").slideDown(400);
						$(".detail_photo_item .detail_photo_info_share a.close").click(function() {
							$(".detail_photo_item .detail_photo_info_share").slideUp(400, function() {
								$(".detail_photo_item .detail_photo_info").slideDown(400);
							});
							return false;
						});
					});
					return false;
				});
				
				$(".detail_photo_item .detail_photo_info a.full_size").click(function() {
					$(".main .wrap").append('<div class="detail_photo_zoom_outer"></div>');
					
					$(".detail_photo_zoom_outer").height($(".detail_photo_zoom_outer").height() + 61).html('<div class="container"><img src="'+data.IMAGE+'" class="collection_image_zoom" /></div><a href="#" class="detail_photo_zoom_close"></a>');
					
					$(".detail_photo_zoom_outer .container").mousemove(function(e) {
						var cursor_pos_x = e.pageX;
						var cursor_pos_y = e.pageY;
						var bl_pos_x = $(this).offset().left;
						var bl_pos_y = $(this).offset().top;
						var left = (e.pageX - bl_pos_x) * ($(this).find("img").width() - $(this).width()) / $(this).width();
						$(this).scrollLeft(left);
						var top = (e.pageY - bl_pos_y) * ($(this).find("img").height() - $(this).height()) / $(this).height();
						$(this).scrollTop(top);
					});
					
					$(".detail_photo_zoom_close").click(function() {
						$(".detail_photo_zoom_outer").remove();
					});

					return false;
				});
			});
		});
	};
}
function hoverScroll(scrollBlock, direction, speed) {
	var $positionLeft = scrollBlock.position().left;
	var $childWidth = scrollBlock.children(":first").width();
	var $floorLeft = Math.floor($positionLeft / $childWidth);
	
	var $realCount = parseInt(scrollBlock.attr("rel"));
	var $firstChild = scrollBlock.children(":first");
	var $lastChild = scrollBlock.children(":last");
	var $lastChildClass = $lastChild.attr("class");
	
	var $scrollLength = $("body").width() / 3;
	
	if(direction == "left") {
		if(scrollBlock.hasClass("fixed_scroll")) {
			if(Math.abs($positionLeft) - $childWidth > 0) {
				$scrollLength = ((Math.abs($positionLeft) - $childWidth) >= $scrollLength)?$scrollLength:(Math.abs($positionLeft) - $childWidth);
			}
			if(Math.abs($positionLeft) - $childWidth <= 0) {
				return false;
			}
		}
		scrollBlock.stop().animate({left:$positionLeft + $scrollLength}, speed, function() {
			//hoverScroll(scrollBlock, direction, speed);
			if($floorLeft >= -1 && scrollBlock.children().length > $realCount + 1) {
				scrollBlock.children().slice(1, $realCount+1).remove();
			}
			if($floorLeft >= -1 && scrollBlock.children().length <= $realCount + 1) {
				if (apis.length) {
					$.each(
						apis,
						function(i) {
							this.destroy();
						}
					)
					apis = [];
				}
				scrollBlock.children(":first").before(scrollBlock.children().slice(0,$realCount).clone(true));
				scrollBlock.css({"left":(scrollBlock.position().left - $childWidth * $realCount)+"px"});
				$('.scroll_block').each(function() {
					apis.push($(this).jScrollPane({
						verticalDragMinHeight: 40,
						verticalDragMaxHeight: 40, 
						horizontalBar: 0, 
						horizontalTrack: 0, 
						horizontalTrackWidth: 0, 
						horizontalDragWidth: 0, 
						animateScroll: true
					}).data().jsp);
				});
			}
		});
	} else if(direction == "right") {
		if(scrollBlock.hasClass("fixed_scroll")) {
			if(Math.abs($positionLeft) + $(".main > .wrap > .container").width() < $childWidth * 2) {
				$scrollLength = ($childWidth * 2 - (Math.abs($positionLeft) + $(".main > .wrap > .container").width()) >= $scrollLength)?$scrollLength:$childWidth * 2 - (Math.abs($positionLeft) + $(".main > .wrap > .container").width());
			}
			if(Math.abs($positionLeft) + $(".main > .wrap > .container").width() >= $childWidth * 2) {
				return false;
			}
		}
		scrollBlock.stop().animate({left:$positionLeft - $scrollLength}, speed, function() {
			//hoverScroll(scrollBlock, direction, speed);
			if($floorLeft < -$realCount) {
				scrollBlock.css({"left":($positionLeft + $childWidth * $realCount - $scrollLength)+"px"});
				//scrollBlock.children().slice(1, $realCount+1).remove();
			}
			
			if($floorLeft < -1 && scrollBlock.children().length <= $realCount + 1) {
				if (apis.length) {
					$.each(
						apis,
						function(i) {
							this.destroy();
						}
					)
					apis = [];
				}
				scrollBlock.children(":last").after(scrollBlock.children().slice(1, $realCount+1).clone(true));
				$('.scroll_block').each(function() {
					apis.push($(this).jScrollPane({
						verticalDragMinHeight: 40,
						verticalDragMaxHeight: 40, 
						horizontalBar: 0, 
						horizontalTrack: 0, 
						horizontalTrackWidth: 0, 
						horizontalDragWidth: 0, 
						animateScroll: true
					}).data().jsp);
				});
			}
		});
	}
}

function moveDetailCollectionItem() {
	$(".detail_photo_item").css({"left" : ($(".container").width() / 2 - $(".detail_photo_item").width() / 2)+"px"});
}

function isValidEmail(email) {
	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}
