jQuery.fn.watch = function(val, state, callback){
	return this.each (function(){
		var self = this;
		var watchInterval = setInterval(function(){
			if ( self[val] == state ) {
				clearInterval (watchInterval);
				callback.call(self);
			}
		}, 10);
	});
};

$(function(){
	if ( !$("#photo ol li").hasClass(".active") ) {
		
		$("#photo ol li").mouseover(function(){
			$(this).prevAll().andSelf().addClass("half-active");
			$(this).nextAll(".active").removeClass("active").addClass("half-active");
			
			clearTimeout(this.timeout);
			
			var self = this;
			this.timeout = setTimeout(function(){
				$(self).siblings().andSelf().removeClass("active half-active");
				$(self).prevAll().andSelf().addClass("active");
			}, 40);
		}).each(function(i){
			this.mark = i+1;
		}).click(function(){
			
			
			// Формируем хотя бы то, что есть
			var member_id = window.member_id || false;
			var mark = this.mark || false;
			var code = window.code || false;
			var invitation_code = window.invitation_code || false;
			
			var voteHash = {
				member_id: member_id,
				mark: mark,
				code: code,
				invitation_code: invitation_code
			};
			for ( var obj in voteHash ) {
				if ( !voteHash[obj] ) {
					delete voteHash[obj];
				}
			};
			
			$.get("http://2010.211.ru/nsk/vote.php", voteHash, function(data){
				if ( data ) {
					$("#rate").fadeOut("slow", function(){
						$(this).show().html('<div class="already">Вы проголосовали</div>');
					});
				}
			});
			return false;
		});
		$("#photo ol").mouseleave(function(){
			var self = this;
			
			$(this).find(".active, .half-active").removeClass("active").addClass("half-active");
			
			clearTimeout(this.timeout);
			
			this.timeout = setTimeout(function(){
				$(self).find(".active, .half-active").removeClass("active half-active");
			}, 40);
		});
		
	}
	
	
	var photoNav = $("#photo-nav li");

	photoNav.click(function(event){
		photoNav.removeClass("active");
		var a = $(this).addClass("active").find("a");
		
		$("#current-photo .fx")
			.unbind("load")
			.stop()
			.css ({
				opacity: 0,
				display: "block"
			})
			.attr ("src", a.attr("href"))
			.watch ("complete", true, function(){
				$(this).animate({
					opacity: 1
				}, 200, function(){
					
					$("#current-photo img:not(.fx)").attr ({
						src: a.attr("href"),
						title: a.attr("title"),
						alt: a.attr("title")
					});
					$(this).css({
						opacity: 0,
						display: "none"
					}).unbind("load");
				});
			});
		$(this).find("a").blur();
		return false;
	});
	
	// Переход на якорную фотку
	if (document.location.hash) {
		var currentPhoto = Number(document.location.hash.replace(/\D/g, ""));
		if (currentPhoto > 0)
			$("#photo-nav li").eq(currentPhoto-1).click();
	}
	
	
	// Объект для хранения переменных для разных страниц
	var Pages = {
		Participate: {
				
				url: "nsk/participate", // *required   —  к какой странице привязать
				
			email: $("[name*=email]").get(0) || false,
			phone: $("[name*=phone]").get(0) || false,
			fname: $("[name=fname]").get(0) || false,
			submit: $("#participate-form .submit").get(0) || false,
			
			// Отработка ошибки
			fieldError: function ( obj, text ) {
				if ( !obj ) {
					return false;
				}
				var error = $( obj ).parent().find(".error:eq(0)").show();
				if (text) {
					error.html( text );
				}
				this.submit.disabled = true;
			},
			
			// Отработка удачного прохождения валидации
			fieldAccept: function ( obj ) {
				if ( !obj ) {
					return false;
				}
				$( obj ).parent().find(".error:eq(0)").hide();
			},
			
			// Проверка заполненности полей
			checkFields: function () {
				if ( !this.email ) {
					return false;
				}
				if ( Validation.email( this.email ) && Validation.phone( this.phone ) && jQuery.trim(this.fname.value) ) {
					this.submit.disabled = false;
					return true;
				}
				this.submit.disabled = true;
				
				return false;
			},
			// Подсветка незаполненных полей
			hilightFields: function () {
				if (!this.checkFields ()) {
					if ( !Validation.email(this.email) && $.trim( this.email.value ).length ) {
						this.fieldError( this.email );
					}
					if ( !Validation.phone(this.phone) && $.trim( this.phone.value ).length ) {
						this.fieldError( this.phone );
					}
					if ( !jQuery.trim(this.fname.value) ) {
						this.fieldError( this.fname );
					}
					return false;
				}
				return true;
			},
			init: function () {
				$(Pages.Participate.phone).blur(function(){
					Pages.Participate.hilightFields();
					this.value = Validation.phone(this) || this.value;
					if ( Validation.phone(this) ) {
						Pages.Participate.fieldAccept (this);
					}
					Pages.Participate.checkFields();
				});
				$(Pages.Participate.email).blur(function(){
					Pages.Participate.hilightFields();
					if ( Validation.email(this) ) {
						Pages.Participate.fieldAccept (this);
					}
					Pages.Participate.checkFields();
				});
				$(Pages.Participate.fname).blur(function(){
					Pages.Participate.hilightFields();
					if ( jQuery.trim(this.value) ) {
						Pages.Participate.fieldAccept (this);
					}
					Pages.Participate.checkFields();
				});
				$(":input").keyup(function(){
					Pages.Participate.checkFields();
				});
				Pages.Participate.checkFields();
				$("#participate-form").submit(function(){
					if ( Pages.Participate.checkFields ) {
						var self = Pages.Participate.submit;
						
						self.disabled = true;
						self.oldValue = self.value;
						self.value = "Секундочку...";
						$.post("/nsk/participate.php",{
							email: Pages.Participate.email.value,
							phone: Pages.Participate.phone.value,
							fname: Pages.Participate.fname.value
						}, function (data) {
							if ( parseInt(data) == 1 ) {
								jqDialog.notify ("<div style='margin-top:50px;'><div class='icon accept'></div><p>С вами свяжутся в ближайшее время</p></div>", 3);
								$("#participate-form").html("<b>Спасибо за участие!</b>");
								
							}else {
								jqDialog.notify ("<div style='margin-top:50px;'><div class='icon warning'></div><p><b>"+ data +"</b></p></div>", 5);
								self.disabled = false;
								self.value = self.oldValue;
							}
						});
					}
					return false;
				});
			}
		},
		Participant: {
			url: "nsk/participant", // *required   —  к какой странице привязать
			init: function(){
				$(".jqConfirm").click(function(){
					
					$("#jqDialog_yes").get(0).disabled = true;
					
					var bonus_count_formated = String(bonus_count);
					
					bonus_count_formated = bonus_count_formated.split("").reverse().join("");
					bonus_count_formated = bonus_count_formated.replace(/(\d{3})/g, function(a){return a+" "});
					bonus_count_formated = bonus_count_formated.split("").reverse().join("");
					
					
					jqDialog.confirm('<p>Бонусы будут списаны с Паспорта <b>'+ username +'</b></p><p>Укажите количество бонусов,<br/>которым вы хотите проголосовать <input type="text" id="countOfBonuses"> из '+ bonus_count_formated +' доступных</p><small>Участник получивший наибольшее количество бонусов выиграет в номинации «<b>Бонус 2010</b>»</small>', function(){
						if ( member_id && bonus_code ) {
							$.get("/nsk/pay_for.php", {
								bonus: $("#countOfBonuses").val(),
								participant: member_id,
								code: bonus_code
							}, function(data){
								$("#jqDialog_yes").hide();
								if ( data ) {
									switch ( data ) {
										case "1": {
											setTimeout(function() {
												jqDialog.notify ("<div style='margin-top:50px;'><div class='icon accept'></div><p>Спасибо за ваш голос. Бонусы будут списаны в ближайшее время.</p></div>", 3);
											}, 500);
											return true;
										}
										case "5": {
											setTimeout(function() {
												jqDialog.notify ("<div style='margin-top:50px;'><div class='icon warning'></div><p style='line-height:44px;'><b>Ататат! <img src='http://forum.211.ru/style_emoticons/default/nono.gif' style='position:relative; top:5px'/></b> Нет у вас столько бонусов!</p></div>", 5);
											}, 500);
											return true;
										}
									}
								}
								setTimeout(function() {
									jqDialog.notify ("<div style='margin-top:50px;'><div class='icon warning'></div><p>Произошла какая-то лютая ошибка!</p><p>На всякий случай попробуйте <strong>обновить страницу</strong> после исчезновения этого окна.</p></div>", 5);
								}, 500);
							})
							
						} 
						
						
					}, function(){
						
					}, {
						strYes: 'Проголосовать',
						strNo: 'Закрыть'
					});
					$("#countOfBonuses").bind("blur keyup", function(){
						$("#jqDialog_yes").get(0).disabled = !this.value;
					});
					return false;
				});
				
			}
		}
	}
	// Распределятор страниц
	for (var page in Pages) {
		var path = document.location.pathname.toLowerCase();
		if ( path.indexOf(Pages[page].url.toLowerCase()) > -1 ) {
			Pages[page].init();
			break;
		}
	}
	
	
});
Cookies = {
	get: function (name) {
		var cookie = " " + document.cookie;
		var search = " " + name + "=";
		var setStr = null;
		var offset = 0;
		var end = 0;
		if (cookie.length > 0) {
			offset = cookie.indexOf(search);
			if (offset != -1) {
				offset += search.length;
				end = cookie.indexOf(";", offset)
				if (end == -1) {
					end = cookie.length;
				}
				setStr = unescape(cookie.substring(offset, end));
			}
		}
		return(setStr);
	},
	set: function (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
	}
}
var Validation = {
	email: function(obj){
		if ( obj ) {
			obj.value = obj.value.toLowerCase().replace(" ", ""); //Без пробелов и в нижнем регистре
			return /^[0-9a-z][a-z0-9_.\-]*@[0-9a-z][0-9a-z_.\-]*[.]([a-z]{2,4}$)/i.test(obj.value); //А сейчас мы тебя проверим!
		}
	},
	phone: function (obj) {
		var digit = obj.value.replace (/\D/g, "");
		if ( digit.length==11 ) { //Если мобильный
			var num1 = digit.slice (0, 1);
			var num2 = digit.slice (1, 4);
			var num3 = digit.slice (4, 7);
			var num4 = digit.slice (7, 9);
			var num5 = digit.slice (9, digit.length);
			if (num1=="8") {
				num1 = "7";
			}
			return "+"+num1+" "+num2+" "+num3+"-"+num4+"-"+num5;
		}else if ( digit.length==7 ) { //Если домашний
			var num1 = digit.slice (0, 3);
			var num2 = digit.slice (3, 5);
			var num3 = digit.slice (5, digit.length);
			return num1+"-"+num2+"-"+num3;
		}else if (digit.length==10) {
			var firstNum = digit.slice (0, 1);
			
			if (firstNum!="8" && firstNum!="7") {
				var num2 = digit.slice (0, 3);
				var num3 = digit.slice (3, 6);
				var num4 = digit.slice (6, 8);
				var num5 = digit.slice (8, digit.length);
				return "+7"+" "+num2+" "+num3+"-"+num4+"-"+num5;
			}
			return false;
		}
		//Фигню какую-то набрал
		return false;
	}	
}


Cufon.replace('h2, #nav li a b, h3, h4');