/*
 * jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
 *
 * Uses the built In easIng capabilities added In jQuery 1.1
 * to offer multiple easIng options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// t: current time, b: begInnIng value, c: change In value, d: duration

jQuery.extend( jQuery.easing,
{
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

(function ($) {
	$.fn.delayedHover = function (over, out, delay) {
		if ( ! delay) {
			var delay = 500;
		}
		var timerIn = false;
		var timerOut = false;
		return this.hover(function(){
			clearTimeout(timerIn);
			clearTimeout(timerOut);
			var el = this;
			if ($.isFunction(over)) {
				timerIn = setTimeout(function(){ over.apply(el) }, delay);
			}
		}, function(){
			clearTimeout(timerIn);
			clearTimeout(timerOut);
			var el = this;
			if ($.isFunction(out)) {
				timerOut = setTimeout(function(){ out.apply(el) }, delay);
			}
		})
	}
})(jQuery);

// Загружает скрипт с использования кеша браузера
function getScript(url, success) {
	$.ajax({
		url: url,
		cache: true,
		dataType: "script",
		success: success
	});
}

function CustomAnimation(callback, duration, swing, comlete)
{
	if ((typeof duration != 'number') || (typeof callback != 'function') || (typeof swing != 'boolean')) {
		return false;
	}
	var _startTime = (new Date()).getTime();

	var _Timer = setInterval(function(){
		var _inWork = (new Date()).getTime() - _startTime;
		var X = _inWork / duration;
		X = X > 1 ? 1 : X;
		if (swing) {
			X = ((-Math.cos(X*Math.PI)/2) + 0.5);
		}
		callback(X);
		if (_inWork >= duration) {
			clearInterval(_Timer);
			if (typeof comlete == 'function') {
				comlete();
			}
		}
	}, 1);
}

function parseStr(s) {
	var rv = {}, decode = window.decodeURIComponent || window.unescape;
	(s == null ? location.search : s).replace(/^[?#]/, "")
		.replace(/([^=&]*?)((?:\[\])?)(?:=([^&]*))?(?=&|$)/g, function ($, n, arr, v) {
			if (n == "") {
				return;
			}
			n = decode(n);
			v = decode(v);
			if (arr) {
				if (typeof rv[n] == "object") {
					rv[n].push(v);
				} else {
					rv[n] = [v];
				}
			} else {
				rv[n] = v;
			}
		});
	return rv;
}

function inputPlaceholder (input, color)
{
	if ( ! input)
		return null;

	/**
	* Webkit browsers already implemented placeholder attribute.
	* This function useless for them.
	*/
	if (input.placeholder && ! $.browser.msie)
		return input;

	var color = color || '#AAA';

	if (input.value === '' || input.value == input.getAttribute('placeholder')) {
		input.value = input.getAttribute('placeholder');
		input.style.color = color;
	}

	input[/*@cc_on'attachEvent'||@*/'addEventListener'](/*@cc_on'on'+@*/'focus', function(){
		input.style.color = '';
		if (input.value == input.getAttribute('placeholder')) {
			input.value = '';
		}
	}, false);

	input[/*@cc_on'attachEvent'||@*/'addEventListener'](/*@cc_on'on'+@*/'blur', function(){
		if (input.value === '') {
			input.value = input.getAttribute('placeholder');
			input.style.color = color;
		} else {
			input.style.color = '';
		}
	}, false);

	return input;
};

function InstallSearch()
{
	$('#header form.search .field').each(function() {
		inputPlaceholder(this);
	});
}

function InstallCityList()
{
	var list = $('#city-list');

	list.delayedHover(false, function(){
			list.removeClass('open');
		});
	list.find('.current').click(function(){
			list.toggleClass('open');
			return false;
		});
}

function InstallNewsFilter()
{
	var links = $("a.filter-link");
	
	links.click(function() {
		$(".blog-list > a").not(this).removeClass('current')
			.parent().find('div.item-list').removeClass('open');
		$(this).toggleClass('current')
			.parent().find('div.item-list').toggleClass('open');
		return false;
	});
	
}

function InstallBlogCityList()
{
	var list = $('#blog-city-list > a');
	var clist = $('#blog-cntry-list > a');

	list.click(function(){
			list.parent().find('div.item-list').toggleClass('open');
			list.toggleClass('current');
			clist.parent().find('div.item-list').removeClass('open');
			clist.removeClass('current');
			return false;
		});
	
	clist.click(function(){
			clist.parent().find('div.item-list').toggleClass('open');
			clist.toggleClass('current');
			list.parent().find('div.item-list').removeClass('open');
			list.removeClass('current');
			return false;
		});
}

function InstallBlogAddForm()
{
	var $fType= $('#blogs-add-form-type input');
	var $fCity = $('#blogs-add-form-city');
	var $fCountry = $('#blogs-add-form-country');

	$fType.change(function(){			
			var $this = $(this);	
			
			$fCountry.toggleClass('hide');
			$fCity.toggleClass('hide');			
		});
}

function InstallNotMemberCityList()
{
	var list = $('#index-awards');

	list.delayedHover(false, function(){
			list.removeClass('open');
		});
	list.find('.current').click(function(){
			list.toggleClass('open');
			return false;
		});
	
	$('#index-awards .float a').click(function(){
		var params = this.hash.substr(1);
		if (params) {
			$.ajax({
					url: '/ajax/index-leaders/?' + params,
					success: function(responce){
						list.replaceWith(responce);
						InstallNotMemberCityList();
					}
				});
			$('#index-awards .float').fadeOut(300);
		}
		return false;
	});
}

function InstallLoginForm()
{
	var form = $('#login-form');
	$('#login-link').click(function(){
		//form.toggleClass('open');
		form.addClass('open').css({left: '78%',top: 10});
		form.find('form').each(function(){
			this.reset();
		});
		form.find('form:visible :text:first').focus();
			
		return false;
	});
	$('.login-link').click(function(){
		var offset = $(this).offset();
		$('#login-form')
			.addClass('open float')
			.css({left: offset.left,top: offset.top})
			.find('form').each(function(){this.reset();});
		return false;
	});
	form.bind('hide-float', function(){
		form.removeClass('open float');
		form.find('form').each(function(){
			this.reset();
		});
	});
	form.find('.cancel').click(function(){
		form.triggerHandler('hide-float');
		return false;
	});
	form.find('a.login').click(function(){
		$(this).addClass('off');
		form.find('a.registration').removeClass('off');
		form.find('form.login').show().find(':text:first').focus();
		form.find('form.registration').hide();
		return false;
	});
	form.find('a.registration').click(function(){
		$(this).addClass('off');
		form.find('a.login').removeClass('off');
		form.find('form.login').hide();
		form.find('form.registration').show().find(':text:first').focus();
		return false;
	});
	
	$('body').click(function(e){
		var parents = $(e.target).parents().andSelf().filter('#login-form, .vote');
		if (parents.length == 0){
			form.triggerHandler('hide-float');   
		}
	});
}

function InstallIndexPage()
{
	var indexNews = $('#index-articles');
	if (indexNews.length) {
		var photos = indexNews.find('.news-images .item');
		var items = indexNews.find('.news-list .item').delayedHover(function(){
			var $next = $(this);
			var $this = items.filter('.open');
			if ($next.data('_i') != $this.data('_i')) {
				var $nextInfo = $next.find('.info'); 
				var $thisInfo = $this.find('.info');
				var $thisInfoHeight = $thisInfo.height();
				var $nextInfoHeight = $nextInfo.height();
				$nextInfo.show().height(0);
				CustomAnimation(function(x) {
					$thisInfo.height($thisInfoHeight*(1-x));
					$nextInfo.height($nextInfoHeight*x);
				}, 250, true, function(){
					$thisInfo.hide().height('auto');
					$nextInfo.height('auto');
					$this.removeClass('open');
					$next.addClass('open');
					photos.removeClass('open')
						.eq($next.data('_i'))
						.addClass('open');
				});
			}
		}, false, 300).each(function(i) {
			$(this).data('_i', i);
		});
	}
}

function InstallPagination()
{
	$(document).keydown(function(D) {
		D = D || window.event;
		var A = D.keyCode;
		if (D.ctrlKey) {
			var E = (D.target || D.srcElement).tagName;
			if (E != "INPUT" && E != "TEXTAREA") {
				var C;
				if (A == 37) {
					C = $("#prev_page")[0]
				}
				if (A == 39) {
					C = $("#next_page")[0]
				}
				if (C) {
					location.href = C.href
					return false;
				}
			}
		}
	});
}

function InstallFancybox()
{
	$('div.gallery-list a, '
	+ '#page > .center-plane a.fancybox').fancybox({
			zoomSpeedIn: 300,
			zoomSpeedOut: 300,
			overlayOpacity: 0
		});
}

function InstallFixes()
{
	/*
	 * All Internet explorers
	 */
	if ($.browser.msie){

	}

	/*
	 * Internet explorer <= 7
	 */
	if ($.browser.msie && $.browser.version <= 7){

	}

	/*
	 * Internet explorer <= 6
	 */
	if ($.browser.msie && $.browser.version <= 6){
		$('#nominacii ins.bot ins, '
		+ '#nominacii ins.top ins, '
		+ '#inner-clouds #controls .fixpng6, '
		+ '.nc_votings_form .fixpng6, '
		+ '#nominacii .vote .fixpng6').each(function(){
			fixPNG(this);
		});
	}
}

function InstallFormVoting() {
	if(!$(".nc_votings").length) return;
	
	$(".nc_votings_form").each(function(){
		var $this 		= $(this),
			$form 		= $this.find("form"),
			$results 	= $this.find(".nc_votings_results"),
			$loader		= $this.find(".nc_votings_loader");
			
		$form.find("button[name='result']").unbind().bind("click", function(e){
			$form.hide();
			$loader.show();
			$.post($form.attr("action") + "?isNaked=1", $form.serialize(), function(data){
				$loader.hide();
				$results.show()
					.css({height: "auto"})
					.html(data + "<p><a href='#' class='nc_votings_show_poll'>Вернуться к опросу</a></p>")
					.find(".nc_votings_show_poll").bind("click", function(){
						$results.hide();
						$form.show();
						return false;
					});
			});
			return false;
		});
			
		$form.unbind().bind("submit", function(e){
			var error = 0;
			$form.find(".item").each(function(){
				if(!$(this).hasClass("form-required")) {
					return;
				}

				var $p = $(this).find(".error-message").hide();
				if(!$(this).find("input[checked]").length && !($(this).find("input[type='text']").length && $(this).find("input[type='text']").attr("value") != "")) {
					$p.show().html("Пожалуйста, ответьте на этот вопрос");
					error++;
				}
				
			});
			
			if(error) {
				return false;
			}
			
			$form.hide();
			$loader.show();
			$.post($form.attr("action") + "?isNaked=1&submit", $form.serialize(), function(data){
					$loader.hide();
					$form.parents(".item").html(data);
					InstallFormVoting();
			});
			return false;
		});
			
		$form.find(".text_name").show();
		$form.find(".item").each(function(){
			var $inputRadio = $(this).find("input[type='radio']");
			var $inputText = $(this).find(".text_name").find("input");
			
			if(!$inputText.length) return;
			
			$inputText.unbind()
				.bind("click", function(){
					$inputRadio.removeAttr("checked");
				});
				
			$inputRadio.unbind()
				.bind("click", function(){
					$inputText.attr("value", "");
				});
		});	
	});
}

function InstallSocialPlugins() {
	if ($('#vk-plugin').length) {
		getScript('http://userapi.com/js/api/openapi.js?47', function() {
			VK.Widgets.Group('vk-plugin', {mode: 0, width: 220}, 28584529);
		});
	}
	if ($('#fb-plugin').length) {
		getScript('http://connect.facebook.net/ru_RU/all.js', function() {
			FB.XFBML.parse();
		});
	}
}

var loading_highcharts = false;
function DisplayChart(id, inputData) {
	var show = function(){
		var sizeY = parseInt((100 / $("#"+id).height()) * 200);
		var sizeX = parseInt((100 / $("#"+id).width()) * 200);
		var chart = new Highcharts.Chart({
			chart: {
				renderTo: id,
				margin: [0, 0, 0, 0]
			},
			title: {
				text: ''
			},
			plotArea: {
				shadow: null,
				borderWidth: null,
				backgroundColor: null
			},
			tooltip: {
				formatter: function() {
					return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
				}
			},
			plotOptions: {
				pie: {
					center: [parseInt(sizeX/2)+'%', parseInt(sizeY/2)+'%'],
					size: sizeY+'%',
					dataLabels: {
						enabled: true,
						formatter: function() {
							if (this.y > 5) return this.point.name;
						},
						color: 'white',
						style: {
							font: '13px Trebuchet MS, Verdana, sans-serif'
						}
					}
				}
			},
			legend: {
				layout: 'vertical',
				style: {
					left: 'auto',
					bottom: '10px',
					right: '0px',
					top: 'auto'
				}
			},
			series: [{
				type: 'pie',
				name: '',
				data: inputData
			}]
		});
	};
	if(typeof Highcharts == "undefined") {
		if (!loading_highcharts) {
			getScript('/js/highcharts.js', show);
			loading_highcharts = true;
		} else {
			var timer = setInterval(function(){
				if(typeof Highcharts != "undefined") {
					clearInterval(timer);
					show();
				}
			}, 500);
		}
	} else {
		show();
	}
}

$(function() {
	InstallSearch();
	InstallCityList();
	InstallBlogCityList();
	InstallNewsFilter();
	InstallBlogAddForm();
	InstallNotMemberCityList();
	InstallLoginForm();
	InstallIndexPage();
	InstallPagination();
	InstallFormVoting();
	InstallBecomeAChef();
	InstallSocialPlugins();
	InstallFancybox();
	InstallFixes();
});

function responseVote(post,vote) {
	$.getJSON('vote?post='+post+'&vote='+vote, function(data) {
		$(".blog-votings span").show();
		if (data.like) $(".blog-votings .like").text(data.like);
		if (data.dislike) $(".blog-votings .dislike").text(data.dislike);
		if (data.voted) $(".blog-votings .vote").removeClass('vote').removeAttr('onClick').addClass('voted');
	});
}

function InstallBecomeAChef() {
	var $become_a_chef = $('#become-a-chef');
	if (!$become_a_chef.length) return
	
	$('.vote-button a', $become_a_chef).click(function() {
		var $this = $(this);
		$.getJSON($this.attr('href'), function(data) {
			$this.parents('.item').find('.votes b').text(data['votes']);
			$this.parent().html('<p>Ваш голос учтен.</p>');
				/*.unbind('click').click(function() {return false;})
				.find('img').attr('src','/igold2/graybutton.png');*/
		});
		return false;
	});
}

function InstallVotesRefresher(cityId)
{
	$('#votes-refresher').each(function(){
		var $refresher = $(this);
		var $arrow = $refresher.find('.votes-refresher__arrow');
		var currentTimer = false;
		var criticalSection = false;
		var nominations = {};
		var nomination_ids = [];
		var start = false;

		function update(e) {
			if (e) {
				e.preventDefault();
			}
			if (criticalSection) {
				return;
			}
			criticalSection = true;
			if (currentTimer) {
				clearInterval(currentTimer);
				currentTimer = false;
			}

			$.when($refresher.animate({
					opacity: 0
				}, {
					duration: 500,
					easing: 'easeOutCubic'
				}),
				$.ajax({
					url: '/ajax/realtime-votes/',
					type: 'get',
					dataType: 'json',
					data: {
						city: cityId,
						nominations: nomination_ids
					},
					success: function(data) {
						for (var i = data.length - 1; i >= 0; i--) {
							var nomination = data[i];
							if (nomination.ID in nominations) {
								var $members = $("<ol></ol>");
								$.each(nomination.Members, function() {
									var $item = $("<li></li>")
										.append($('<span class="name"></span>')
											.text(this.Name))
										.append('&nbsp; ')
										.append($('<span class="votes"></span>')
											.text(this.Votes));
									$members.append($item);
								});
								nominations[nomination.ID].replaceWith($members);
								nominations[nomination.ID] = $members;
							}
						};
					}
				}))
				// При успешном и неуспешном завершении загрузки и анимации
				.always(function() {
					criticalSection = false;
					$refresher.animate({
							opacity: 1
						}, {
							duration: 1000,
							easing: 'easeInCubic'
						});
					autoUpdate();
				});
		}
		
		function autoUpdate() {
			$arrow.scrollLeft(0);
			var start = new Date;
			currentTimer = setInterval(function() {
					// 100 — кол-во кадров
					var frame = Math.floor((new Date - start) / 10000 * 90);
					$arrow.scrollLeft(frame * 26);
					if (frame >= 89) {
						frame = 89;
						update();
					}
				}, 10);
		};

		$('#index-awards .award').each(function() {
			var id = $(this).data('nomination-id');
			var $list = $(this).find('ol');
			if (id && $list.length) {
				nomination_ids.push(id);
				nominations[id] = $list;
				start = true;
			}
		});

		if (start) {
			autoUpdate();
			$arrow.click(update);
			$refresher
				.css({opacity: 0, display: 'block'})
				.animate({opacity: 1}, {duration: 1000});
		}
	});
}
