$("html").addClass("js");

var map;

function loadmap(x,y,zoom,container) {
	
	var point = new google.maps.LatLng(x, y);
	var myOptions = {
    	zoom: zoom,
    	center: point,
    	mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    
    map = new google.maps.Map(document.getElementById(container), myOptions);
} 

function drawpoint(x,y) {
	
	var point = new google.maps.LatLng(x, y);
	
 	var beachMarker = new google.maps.Marker({
      position: point,
      map: map,
      icon: "/i/icon.png"
  	});
}  


$(document).ready(function() {
	
	/* map layer*/
	$("#address").delegate(".salon-link", "click", function() {
		var el = $(this);
		var number = $('#address').find(".salon-link").index(this);
		
		fillfon();
		var obj = [];
		obj.response = $("<div style=\"padding: 20px 0\"><div id=\"address-box\"><div class=\"inner_close\"></div><div id=\"address-box-fon\">"+$("#salons-text div.address-text:eq("+number+")").html()+"<div id=\"dynamic_map\"></div></div></div></div>");
		obj.done = 1;
		show_dynamic_content(obj, 'local');
		
		
		var x = parseFloat(el.parent().find(".x_coord").attr("value"));
		var y = parseFloat(el.parent().find(".y_coord").attr("value"));
		var zoom = parseFloat(el.parent().find(".z_coord").attr("value"));
		zoom = zoom ? zoom:10;
		if(x && y) {
			loadmap(x, y, zoom, "dynamic_map");
			drawpoint(x, y);
		}
		return false;
	});
	
	/* imgs */
 	$('a[rel="colorbox"]').live("click", function() {
 	// смотрим загружен ли фон, елси да, то ничего не делаем
		var resize = true;
		if(!$("#precontainer").length) {
			resize = false;
			fillfon();
		} else {
			show_indicator();
		}
			
		var el = $(this);
		var path = $(this).attr('href');
		var number = $('a[rel="colorbox"]').index(el);
		var data =  $('a[rel="colorbox"]');
			
		/* "/"+$(this).attr('name')+'/' */
		$.getJSON(
		"/ajax/", {
  			show_photo: true,
  			path: path,
  			type: $(this).attr('name'),
  			title: $(this).attr('title'),
  			height: $(window).height()
 		},
 		function(obj) {
 		
 			$("<img/>").bind("load", function() {
 				if (show_dynamic_content(obj, 'dynamic' , 'fade', 'slow')) {
 					$("#close_dynamic").show();
 					var content = $("#dynamic-content").find("#gallery-img");
					if($("#prev_photo").length) {
						$("#prev_photo").show().height(content.height()).find('a').height(content.height());
					}
					if($("#next_photo").length) {
						$("#next_photo").show().height(content.height()).find('a').height(content.height());
					}	
					if(resize) dynamic_content_resize();					
 				}
			}).attr("src",path);
 		});
		return false;
 	});
 	
 	/* filtr */
 	$("#colors").delegate("li", "click", function() {
 		$(this).find("img:eq(1)").toggleClass("filtr").toggleClass("filtr_active");
 	});
 	
 	/* pager */
 	$("#more").click(function() {
 		
 		var page = parseInt($("#current_page").attr('value'));
 		
 		var params = [];
 		
 		params["loader_class"] = "catalogue-wheel";
 		params["disabled_class"] = "catalogue-disabled";
 		params["loader_delta_top"]= $(this).height() + 10;
 		params["loader_delta_left"]=-$(this).width()/2 -5;
 		
 		show_indicators($(this), params);

 		$.getJSON(
		window.location.href, {
  			pager: true,
  			page: page
 		},
 		function(obj) {
 			if(obj.done==1) {
 				hide_indicators();
 				$("#list ul").append(obj.response);
 				$("#current_page").attr('value',page+1);
 				if(obj.disable) $("#more").addClass("disabled");
 			}
 		});
		return false; 		
 	});
 	
 	/* basket */
 	
 	$("#tobasket, .tobasket").click( function() {
 		var el = $(this);
 		
 		var params = [];
 		
 		params["loader_class"] = "catalogue-wheel";
 		params["disabled_class"] = "catalogue-disabled";
 		params["loader_delta_top"]= el.height() + 10;
 		params["loader_delta_left"]=-el.width()/2 -5;
 		
 		show_indicators(el, params);
 		
 		
 		/* "size": $("#sizes").val() */
 		
 		$.getJSON(
		el.attr("href"), {
 		},
 		function(obj) {
 			hide_indicators();
 			if(obj[0]) {
 				
 				$("#basket_count").text(obj[1]);
 				
 				if(obj[1]>0) {
 					$("#basket_count").parents("span:eq(1)").addClass("active");
 				} else {
 					$("#basket_count").parents("span:eq(1)").removeClass("active");
 				}
 				
 				if(el.hasClass("tobasket")) {
 					el.parent().remove();
 					
 					if(obj[1]==0) window.location = window.location;
 					
 				} else {
 					el.toggleClass("out");
 				}
 			
 			}
 		});
 		
		return false; 		
 	});
 	
 	/* size-salon */
 	$("#catalogue_id").delegate("select[name='sizes']", "change", function() {
 		// потом переделать по порядковому номеру!
		var number =  $(this).val();

		$(this).parents(".salon_sizes").find(".cities").find("span").hide().end().find("#sizesalon"+number).show();			
 	});
	
	/* salons page maps */
	if($("#salons_table").length) {
		$(".map_container").each( function() {
			var el = $(this);
			var x = parseFloat(el.attr("x"));
			var y = parseFloat(el.attr("y"));
			var zoom = parseInt(el.attr("zoom"));
			zoom = zoom ? zoom:10;
			loadmap(x, y, zoom, el.attr("id"));	
			drawpoint(x, y);		
		});
	}
	
	/* consult form */
	$("#close_consult_link, .inner_close").live("click", function() {
		close_dynamic();
	});
	
	/* sort */
	$("#sort-block li span").click( function() {
		var parent = $(this).parent();
		
		if(parent.hasClass("active")) {
			// чтобы повторное нажатие на кнопку убирало сортировку!
			$("input[name='sort_type']").attr("value","cat_left_key");
		} else {
			$("input[name='sort_type']").attr("value",$(this).attr("value"));
		}
 		$("form[id='sort_form']").submit();
 		
	});
	
	/* gallery */
	if($("#index-gallery").length) {
			$('#projects-carousel').glebsn_carousel('');
			
			var img = $("#photo-container").find("img");
			$("#gallery-loader").show();
			
			$("<img/>").bind("load", function() {
				img.css("visibility","visible");
				$("#gallery-loader").hide();
  			}).attr("src", img.attr("src"));
  			
  			// запускаем автомат
  			function slider_automat() {
  				var data = $("#carousel-list li");
  				var length = data.length;
  				var slider_number = 0;
  				if(length>1) {
  				
  					var number = 0;
  					$.each(data, function (key,val) {
						if($(val).hasClass("selected")) {
							slider_number = key;
						}
					});
				
					slider_number = slider_number + 1;
					if(!$("#carousel-list li:eq("+slider_number+")").length) {
						slider_number = 0;
  					}
					$("#carousel-list li:eq("+slider_number+") a").trigger("click", true);
				
  				}
  			}
  			
  			var slider_action = setInterval(slider_automat, 8000);
 			
 			$("#carousel-list").delegate("a", "click", function(event, param) {
 				if(!param) clearInterval(slider_action);
 				
 				var el = $(this);
 				var href = el.attr("href");
 				var parent = el.parent();
 				// предварительные ласки
 				parent.siblings().removeClass("selected").end().addClass("selected");
 				img.css("visibility","hidden");
 				$("#gallery-loader").show();
 				
 				// подгружаем фотку
 				$("<img/>").bind("load", function() {
					img.css("visibility","visible").attr("src",href).attr("alt", el.find("img").attr("alt"));
					$("#gallery-loader").hide();
					
					// разбираемся со ссылкой
					if(parent.find("a.hide").length) {
						// если есть у нажатого
						var lnk = parent.find("a.hide").attr("href");
						if(img.parent().attr("href")) {
							// есть у того который висел
							// просто меняем href
							img.parent().attr("href", lnk);
						} else {
							// нет у того который висел
							img.wrap("<a href=\""+lnk+"\">");
						}
					} else {
						// если нет ссылки у нажатого 
						if(img.parent().attr("href")) {
							// есть у того который висел
							img.unwrap("<a>");
						} else {
							// нет у того который висел
							//ничего не делаем
						}
					}
					
  				}).attr("src", href);
 				
 				return false;
 			});
	}
	
	/* leaders carousel */
	if($("#leaders-carousel").length) {
		var leaders_length = $("#leaders-carousel-list").find("li").length;
		var leaders_item_width = $("#leaders-carousel-list").find("li").width() + 0; // margin: 0
		var leaders_carousel_width = leaders_item_width*leaders_length;
		var leaders_first_item =  $("#leaders-carousel-list li:first"); 
		var leaders_last_item =  $("#leaders-carousel-list li:last"); 
	
		$("#leaders_buttons").delegate("a", "click", function() {
			var el = $(this);
			if(!el.hasClass("disabled")) {
				if(el.hasClass("pause")) {
					el.removeClass("pause").addClass("play");	
				} else if(el.hasClass("prev")) {
					var left = parseInt($("#leaders-carousel-list").css("left"));
					if(left<0) {
						$("#leaders_buttons a").addClass("disabled");
						$("#leaders-carousel-list").animate({"left": left+leaders_item_width+"px"}, "medium", function() {
							$("#leaders_buttons a").removeClass("disabled");
						});
					} else {
						$("#leaders_buttons a").addClass("disabled");
						$("#leaders-carousel-list").prepend("<li>"+leaders_last_item.html()+"</li>").css("left",-leaders_item_width+"px");
						$("#leaders-carousel-list").animate({"left": left+"px"}, "slow", function() {
							$("#leaders_buttons a").removeClass("disabled");
							$(this).find("li:first").remove().end().css("left",-leaders_carousel_width+leaders_item_width+"px");
						});
					}
				} else if(el.hasClass("next")) {
						var left = parseInt($("#leaders-carousel-list").css("left"));
						if(-left<leaders_carousel_width-leaders_item_width) {
							$("#leaders_buttons a").addClass("disabled");
							$("#leaders-carousel-list").animate({"left": left-leaders_item_width+"px"}, "medium", function() {
								$("#leaders_buttons a").removeClass("disabled");
							});
						} else {
							$("#leaders_buttons a").addClass("disabled");
							$("#leaders-carousel-list").append("<li>"+leaders_first_item.html()+"</li>");
							$("#leaders-carousel-list").animate({"left": left-leaders_item_width+"px"}, "slow", function() {
								$("#leaders_buttons a").removeClass("disabled");
								$(this).css("left",0).find("li:last").remove();
							});
						}
				}
			}
			return false;
		});
	
	}
		
	/* advise carousel */
	if($("#advise-carousel").length) {
		var advise_length = $("#advise-carousel-list").find("li").length;
		var advise_item_width = $("#advise-carousel-list").find("li").width() + 0; // margin: 0
		var advise_carousel_width = advise_item_width*advise_length;
		var advise_first_item =  $("#advise-carousel-list li:first"); 
		var advise_last_item =  $("#advise-carousel-list li:last"); 
	
 		function automat() {
			var left = parseInt($("#advise-carousel-list").css("left"));
			if(-left<advise_carousel_width-advise_item_width) {
				$("#advise_buttons a").addClass("disabled");
				$("#advise-carousel-list").animate({"left": left-advise_item_width+"px"}, "medium", function() {
					$("#advise_buttons a").removeClass("disabled");
				});
			} else {
				$("#advise_buttons a").addClass("disabled");
				$("#advise-carousel-list").append("<li>"+advise_first_item.html()+"</li>");
				$("#advise-carousel-list").animate({"left": left-advise_item_width+"px"}, "slow", function() {
					$("#advise_buttons a").removeClass("disabled");
					$(this).css("left",0).find("li:last").remove();
				});
			}
 		}
 		
		if(advise_length>1) var id = setInterval(automat, 5000);
	
		$("#advise_buttons").delegate("a", "click", function() {
			var el = $(this);
			if(!el.hasClass("disabled")) {
				if(el.hasClass("pause")) {
					clearInterval(id);
					el.removeClass("pause").addClass("play");	
				} else if(el.hasClass("prev")) {
					// похуй блять!
					if($("#advise_buttons .play").length) {
					
						var left = parseInt($("#advise-carousel-list").css("left"));
						if(left<0) {
							$("#advise_buttons a").addClass("disabled");
							$("#advise-carousel-list").animate({"left": left+advise_item_width+"px"}, "medium", function() {
								$("#advise_buttons a").removeClass("disabled");
							});
						} else {
							$("#advise_buttons a").addClass("disabled");
							$("#advise-carousel-list").prepend("<li>"+advise_last_item.html()+"</li>").css("left",-advise_item_width+"px");
							$("#advise-carousel-list").animate({"left": left+"px"}, "slow", function() {
								$("#advise_buttons a").removeClass("disabled");
								$(this).find("li:first").remove().end().css("left",-advise_carousel_width+advise_item_width+"px");
							});
						}
					
					}					
				} else if(el.hasClass("next")) {
					if($("#advise_buttons .play").length) {
					
						var left = parseInt($("#advise-carousel-list").css("left"));
						if(-left<advise_carousel_width-advise_item_width) {
							$("#advise_buttons a").addClass("disabled");
							$("#advise-carousel-list").animate({"left": left-advise_item_width+"px"}, "medium", function() {
								$("#advise_buttons a").removeClass("disabled");
							});
						} else {
							$("#advise_buttons a").addClass("disabled");
							$("#advise-carousel-list").append("<li>"+advise_first_item.html()+"</li>");
							$("#advise-carousel-list").animate({"left": left-advise_item_width+"px"}, "slow", function() {
								$("#advise_buttons a").removeClass("disabled");
								$(this).css("left",0).find("li:last").remove();
							});
						}
					
					}
				} else {
					// play
					id = setInterval(automat, 5000);
					el.removeClass("play").addClass("pause");
				}
			}
			return false;
		});
	
	}
	
	/* news carousel */
	if($("#news-carousel").length) {
		var news_length = $("#news-carousel-list").find("li").length;
		var news_item_width = $("#news-carousel-list").find("li").width() + 0; // margin: 0
		var news_carousel_width = news_item_width*news_length;
		var news_first_item =  $("#news-carousel-list li:first"); 
		var news_last_item =  $("#news-carousel-list li:last"); 
	
 		function news_automat() {
			var left = parseInt($("#news-carousel-list").css("left"));
			if(-left<news_carousel_width-news_item_width) {
				$("#news_buttons a").addClass("disabled");
				$("#news-carousel-list").animate({"left": left-news_item_width+"px"}, "medium", function() {
					$("#news_buttons a").removeClass("disabled");
				});
			} else {
				$("#news_buttons a").addClass("disabled");
				$("#news-carousel-list").append("<li>"+news_first_item.html()+"</li>");
				$("#news-carousel-list").animate({"left": left-news_item_width+"px"}, "slow", function() {
					$("#news_buttons a").removeClass("disabled");
					$(this).css("left",0).find("li:last").remove();
				});
			}
 		}
 		
		if(news_length>1) var news_id = setInterval(news_automat, 5000);
	
		$("#news_buttons").delegate("a", "click", function() {
			var el = $(this);
			if(!el.hasClass("disabled")) {
				if(el.hasClass("pause")) {
					clearInterval(news_id);
					el.removeClass("pause").addClass("play");	
				} else if(el.hasClass("prev")) {
					// похуй блять!
					if($("#news_buttons .play").length) {
					
						var left = parseInt($("#news-carousel-list").css("left"));
						if(left<0) {
							$("#news_buttons a").addClass("disabled");
							$("#news-carousel-list").animate({"left": left+news_item_width+"px"}, "medium", function() {
								$("#news_buttons a").removeClass("disabled");
							});
						} else {
							$("#news_buttons a").addClass("disabled");
							$("#news-carousel-list").prepend("<li>"+news_last_item.html()+"</li>").css("left",-news_item_width+"px");
							$("#news-carousel-list").animate({"left": left+"px"}, "slow", function() {
								$("#news_buttons a").removeClass("disabled");
								$(this).find("li:first").remove().end().css("left",-news_carousel_width+news_item_width+"px");
							});
						}
					
					}					
				} else if(el.hasClass("next")) {
					if($("#news_buttons .play").length) {
					
						var left = parseInt($("#news-carousel-list").css("left"));
						if(-left<news_carousel_width-news_item_width) {
							$("#news_buttons a").addClass("disabled");
							$("#news-carousel-list").animate({"left": left-news_item_width+"px"}, "medium", function() {
								$("#news_buttons a").removeClass("disabled");
							});
						} else {
							$("#news_buttons a").addClass("disabled");
							$("#news-carousel-list").append("<li>"+news_first_item.html()+"</li>");
							$("#news-carousel-list").animate({"left": left-news_item_width+"px"}, "slow", function() {
								$("#news_buttons a").removeClass("disabled");
								$(this).css("left",0).find("li:last").remove();
							});
						}
					
					}
				} else {
					// play
					news_id = setInterval(news_automat, 5000);
					el.removeClass("play").addClass("pause");
				}
			}
			return false;
		});
	
	}
	
	
	
	/* */
	
	$("#logo_link").hover( function() {
		$("#hovered_logo").fadeIn();
	}, function() {
		$("#hovered_logo").fadeOut();
	});
	
	/* dynamic content */
	
	$("#ask_question, #ask_question_bottom").click( function() {
		fillfon();
		var obj = [];
		obj.response = $("#consult-form-box");
		obj.done = 1;
		show_dynamic_content(obj, 'local');
		/*
		setTimeout( function() { 
  			$("#cname").focus(); 
		} , 30);
		*/
		return false;
	});
	
	/* reg && enter */
	$("#reg_link").click( function() {
		$("#registration-form").toggle();
		return false;
	});
	
	/* logout */
	$("#logout").click( function() {
 		$.getJSON(
 		"/ajax/",
 		{
 	 		submit_logout: true
 		},
 		function(obj)
 		{
 			/*
  			$.cookie("id_user_cookie", null);
  			$.cookie("password_cookie", null);
  			*/
  			window.location = "/";	
 		}); 
 		return false;
 	});
		
	/* focus fields */
 	if((".form-field").length) {
		var data = $(".form-field");
		$.each(data, function (key,val) {
			if(val.value) $("#"+val.id+"_value").parents('.default-field').hide();
		});
 	}
	
 	$(".default-field").live("click", function() {
	 	/*$(this).hide();*/
	 	var id = new String($(this).find('span').attr('id'));
	 	var field = id.replace("_value","");
	 	$("#"+field).focus();
 	});
 
 	$(".form-field").live("focus", function() {

		$(this).removeClass("form-field-notice"); /* for shop */
		var parent = $(this).parents('span');
		if(parent.length) parent.removeClass("form-field-notice"); /* for textarea */
	
		var id = new String($(this).attr('id'));
	
		var parent_ = $("#"+id+"_value").parents('.default-field').hide();
		
 	}).live("blur", function() {
		
		if($(this).attr("value")=='') {
			var id = $(this).attr('id');
			var parent = $("#"+id+"_value").parents('.default-field');
		
			if(parent.hasClass('default-field-notice')) {
				
				$(this).addClass("form-field-notice"); /* for shop */
				var span_parent = $(this).parents('span');
				span_parent.addClass("form-field-notice"); /* for textarea */
			}
			parent.show();
		}
		
 	});	
	
});

function loadform(alias)
{
 $('#'+alias).ajaxForm(
 { 
  dataType:  'json', 
  beforeSubmit: function(arr, $form, options) {
  		$(".order_alert").empty().hide();
  		$(".form-field-notice").removeClass("form-field-notice");
  		$(".default-field-notice").removeClass("default-field-notice");
 		
  		// http://jquery.malsup.com/form/#options-object
 		var alias = $form.attr('id');
 		var clicked = $("#"+alias).find(".form_submit");
 		
 		if(clicked.length) {
 			//$("#submit_data");
 			var params = [];
 		
 			params["loader_class"] = alias+"-wheel";
 			params["disabled_class"] = alias+"-disabled";
 			params["loader_delta_top"]=-2;
 			params["loader_delta_left"]=20;
 		
 			show_indicators(clicked, params);
 			
 		}
  },
  success: function(data) {
  	
  	hide_indicators();
  	
  	if(data.items) $(data.items).addClass("form-field-notice");
  	if(data.divs) $(data.divs).addClass("default-field-notice");
  	
  	//выводим все алерты
  	if(data.notes) {
  		for(var i in data.notes) {
  			if($("#"+i+"_alert").length) $("#"+i+"_alert").html("<span>"+data.notes[i]+"</span>").show();
  		}
  	} 
  	
  	dynamic_content_resize();

  	if(data.done==0) {
  		if($("#captcha-img").length) {
  			// && data.notes['captcha']
  			$("#captcha-img").attr("src","/CaptchaSecurityImages.php?width=100&height=30&characters=6&"+Math.random());
  		}
  	}
  	
	if(data.done==1) {
  			$("#formajaxloader").show();
  			setTimeout(function(){window.location = window.location}, 2500);
  	}
  	
  	if(data.done==2) {
  			if(data.link) {
  				setTimeout(function(){window.location = data.link}, 500);
  			} else {
  				setTimeout(function(){window.location = window.location}, 500);
  			}
  	}
  	
  	if(data.done==3) {
  	 		 	 	
  			var pre_height = parseInt($("#pre-send-order").css("height"));
  			
  			$("#pre-send-order").hide();
  			$("#post-send-order").html(data.response);
  			$("#pre-send-order").empty();
  			
  			/*
  			var top = parseInt($(window).scrollTop());
  			var post_height = parseInt($("#post-send-order").css("height"));
  			alert(top);
  			$(window).scrollTop(top+post_height-pre_height);
  			*/
  			
  			dynamic_content_resize();
  	}
  	
  	// for new version of jquery and jquery.form
  	if(data.done==5) {
    	$.getJSON(
 		"/ajax/", {
 	 		show_html_after_form_submit: true,
 	 		type: data.type,
 	 		params: data.params
 		},
 		function(obj) {
 			
 			if(obj.done) {
   			
  				$("#dynamic-content .pre-send-order").hide();
  				$("#dynamic-content .post-send-order").html(obj.response);
  				$("#dynamic-content .pre-send-order").empty();
  			
  				dynamic_content_resize();	
  			
 			}	
 		});		
  	}
  	
  	
  	if(data.done==4) {
  		$.getJSON(
 		"/ajax/", {
 	 		show_html_after_file_upload: true,
 	 		id: data.json['id']
 		},
 		function(obj) {
   			
  			$("#pre-send-order").hide();
  			$("#post-send-order").html(obj.response);
  			$("#pre-send-order").empty();
  			
  			dynamic_content_resize();		
 		});
  	}
  }
 });	
}

function CountClick(id,link) {
 $.getJSON('/ajax/', {
 	id: id,
  	link: link,
  	count_clicks: true
 }, function(obj) {
  	window.location=obj.result;
 });	
}
