
function getBodyScrollTop() {
	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

var Scroller = function(data) {
	this.step = data.step || 30;
	this.speed = data.speed || "slow";

	this.item = data.item;
	this.maxOffset = parseInt(this.item.height()) - (data.cH?data.cH:0);
	this.offset = parseInt(this.item.css("top")) || 0;
}
Scroller.prototype = {
	scroll: function(relOffset) {
		this.offset += relOffset * this.step;

		if(this.offset > 0) {
			this.offset = 0;
		}

		if(this.offset < -this.maxOffset) {
			this.offset = -this.maxOffset;
		}

		this.item.stop().animate({"top": this.offset}, this.speed);
	}
};

var Veiler = function(data) {
	this.veil;
	this.showedVeilClass = "";
	this.scrollBefore = 0;
	this.buildVeil();
}
Veiler.prototype= {
	buildVeil: function() {
		var str = "";
		str +=	"<div class=\"veil\">";
		str +=		"<div class=\"veil-bg\"></div>";
		str +=		"<div class=\"veil-content\">";
		str +=			"<div id=\"popup-mobdev\"><div class=\"cornered\">";
		str +=				"<div class=\"t\"><div class=\"l\"></div><div class=\"r\"></div><div class=\"m\"></div></div>";
		str +=				"<div class=\"c\"><div class=\"l\"></div><div class=\"r\"></div><div class=\"cc\">";
		str +=					"<a href=\"#close-popup\" id=\"close\">закрыть</a>";
		str +=					"<h3 id=\"popup-h3\">Заголовок</h3>";
		str +=					"<div class=\"popup-pic\"><img id=\"popup-pic\" src=\"/i/v.gif\" alt=\"Картинка\" /></div>";
		str +=					"<div id=\"popup-text\">Описание</div>";
		str +=				"</div></div>";
		str +=				"<div class=\"b\"><div class=\"l\"></div><div class=\"r\"></div><div class=\"m\"></div></div>";
		str +=			"</div></div>";
		str +=		"</div>";
		str +=	"</div>";
		$("body").prepend(str);

		this.veil = $("div.veil");
		(function(tmpthis){
			tmpthis.veil.click(function(){
				tmpthis.hideVeil();
			});

			$("a#close").click(function(e){
				e.preventDefault();
				$(tmpthis.veil).trigger("click");
			});
		})(this);

		$("div.veil-content div.cornered").click(function(e) {
			return false;
		});
	},
	showVeil: function(veilname) {
		this.veil.addClass("veil-shown");

		this.scrollBefore = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);

		window.scrollTo(0, 0);

		$("." + veilname).show();
		this.showedVeilClass = veilname;

		if($.browser.msie && $.browser.version == "6.0") {
			this.veil.css({position: "relative"}).css({position: "absolute"});
		}
	},
	hideVeil: function() {
		this.veil.removeClass("veil-shown");
		$("div." + this.showedVeilClass).hide();
		$("#popup-mobdev").css({"height": "auto", "margin-top": "auto"});
		this.showedVeilClass = "";

		window.scrollTo(0, this.scrollBefore);
		this.scrollBefore = 0;
	},
	updateContent: function($elem) {
		var $info = $("div.popup-info", $elem);
		var title = $("h5", $elem).text();
		var description = $("div.description", $info).html();
		var $image = $("div.image img", $info);
		var imagewidth = $image.attr("width")>275?275:($image.attr("width"));

		$("#popup-h3").html(title);
		$("#popup-text").html(description);
		$("#popup-pic").attr({
			src: $image.attr("src"),
			alt: $image.attr("alt"),
			width: imagewidth
		});

		$('#popup-text a').click(function() {
			var target = $(this).attr('target');
			target = target.length > 0 ? target : '_self';
			window.open(this.href, target);
		});
	}
}

function checkStep1() {
	isCorrectStep = true;

	var phoneObj = $("input[name$='phone-number']");
	var validateResult = phoneObj.val().match(/^[0-9]{7}$/);

	if(!validateResult) {
		isCorrectStep = false;
		alert("Неправильно указан номер мобильного телефона");
	}

	if((validateResult) && ($('input#not_voted').val() == 0)) {
		var msisdn = $("select[name$='phone-prefix']").val() + phoneObj.val();
		isCorrectStep = false;
		$.getJSON('/survey.json', {'msisdn':msisdn}, function(data, item){
			if(data.is_voted) {
				alert("Извините, вы уже проходили опрос");
				isCorrectStep = false;
			} else {
				$('input#not_voted').val(1);
				$("button#surveysubmit").trigger('click');
			}
		});
	}
	return isCorrectStep;
}

function checkStep2() {
	var paramOrder = $('#sortable').sortable('toArray');
	var i = 1;
	for (key in paramOrder) {
		var param_key = paramOrder[key]; // eg, sortable_1
		var param_value = $("#"+param_key).find('span.param').html();
		$("input[name$='importance_"+i+"']").val(param_value);
		i++;
	}
	return true;
}
 
function checkStep3() {
	var isCorrectStep = true;
	var starsData = new Array();

	starsData['starinfo'] = 'Вы забыли поставить оценку параметру "Информация о программе"';
	starsData['starspeed'] = 'Вы забыли поставить оценку параметру "Скорость накопления бонусных баллов"';
	starsData['starassortment'] = 'Вы забыли поставить оценку параметру "Ассортимент вознаграждений"';
	starsData['staraccessibility'] = 'Вы забыли поставить оценку параметру "Доступность вознаграждений"';
	starsData['starconvenience'] = 'Вы забыли поставить оценку параметру "Удобство получения вознаграждения"';
	starsData['starnew'] = 'Вы забыли поставить оценку параметру "Новые предложения"';

	for(key in starsData) {
		var notice = starsData[key];
		$('div#step3').find("input[name$='"+key+"']").each(function(){
			if($(this).val() == 0) {
				alert(notice);
				isCorrectStep = false;
			}
		});
		if(!isCorrectStep) {
			break;
		}
	}
	return isCorrectStep;
}

function checkStep4() {
	var isCorrectStep = true;
	var radioData = new Array();

	radioData['programmlike'] = 'Пожалуйста укажите ваше отношение к программе в целом';
	radioData['programmadvice'] = 'Пожалуйста укажите вероятность рекомендации программы друзьям и знакомым';

	for(key in radioData) {
		var notice = radioData[key];
		if($('div#step4').find("input[name$='"+key+"']").length > 0) {
			if($('div#step4').find("input[name$='"+key+"']:checked").length == 0) {
				alert(notice);
				isCorrectStep = false;
			}
			if(!isCorrectStep) {
				break;
			}
		}
	}
	return isCorrectStep;
}

$(function() {
	$("body.root").each(function() {
		var newsScroller = new Scroller({
			step: $("div.news-list ul li").eq(0).height(),
			item: $("div.news-list ul"),
			cH: $("div.news-list-container").height()
		});

		$("a.control").click(function(){
			newsScroller.scroll($(this).hasClass("u")?1:-1);
			return false;
		});
	});

	$("body.faq").each(function(){
		$('dt:first-child').each(function() {
			$(this).addClass('first-child');
		});

		$("dl dt a").click(function(e){
			e.preventDefault();
			$(this).parent("dt")
				.next("dd")
				.andSelf()
				.toggleClass("shown");
		});

		$('dl dt:nth-child(-n+6) a').each(function() {
			$(this).trigger('click');
		});
	});

	$("body.devices").each(function(){
		var veil = new Veiler();

		$("ul.documents li a").click(function(e){
			e.preventDefault();
			veil.updateContent($(this).parents("li").eq(0));
			veil.showVeil("veil-content");
		});
	});

	$("body.accessories").each(function(){
		$("a.toggle").click(function() {
			$("ul.documents li.show").removeClass("show");

			if ($(this).hasClass("showall")) {
				$("ul.documents li").addClass("show");

				$(this).removeClass("showall");
				$(this).addClass("hideall");
				$(this).html("Свернуть");

			} else {
				$("ul.documents li.first").addClass("show");

				$(this).removeClass("hideall");
				$(this).addClass("showall");
				$(this).html("Полный ассортимент");
			}

			return false;
		}).trigger("click");
	});

	$("select[name=region]").change( function() {
		$('form#regions').submit();
	});

	$("body.survey").each(function(){
		/* Rating Plugin */
		$("#stars-wrapper1").stars({
			inputType: "select",
			captionEl: $("#stars-cap1")
		});
		$("#stars-wrapper2").stars({
			inputType: "select",
			captionEl: $("#stars-cap2")
		});
		$("#stars-wrapper3").stars({
			inputType: "select",
			captionEl: $("#stars-cap3")
		});
		$("#stars-wrapper4").stars({
			inputType: "select",
			captionEl: $("#stars-cap4")
		});
		$("#stars-wrapper5").stars({
			inputType: "select",
			captionEl: $("#stars-cap5")
		});
		$("#stars-wrapper6").stars({
			inputType: "select",
			captionEl: $("#stars-cap6")
		});

		/* Sortable List*/
		$(function() {
			$("#sortable").sortable();
			$("#sortable").disableSelection();
		});


		var $ol = $("#content ol.steps");
		var stepId = parseInt($('button#surveysubmit').attr('step'), 10);
		$ol.find("li").removeClass("current done").eq(stepId-1).addClass("current").prevAll().addClass("done");

		// enter key
		$('#form-survey').bind('submit', function() {
			var stepId = parseInt($('button#surveysubmit').attr('step'), 10);
			if(stepId < 6) {
				$("button#surveysubmit").trigger('click');
				return false;
			}
		});

		$("button#surveysubmit").click(function(){
			var isCorrectStep = true;

			var stepId = parseInt($(this).attr('step'), 10);
			switch(stepId) {
				case 1: isCorrectStep = checkStep1(); break;
				case 2: isCorrectStep = checkStep2(); break;
				case 3: isCorrectStep = checkStep3(); break;
				case 4: isCorrectStep = checkStep4(); break;
			}

			if(isCorrectStep) {
				var has_more = (stepId < 5);
				if(!has_more) {
					// set correct image for button
					//$('button#surveysubmit').('value', 'ok');
				}

				if((stepId+1) < 6) {
					$('div#step'+stepId).css('display', 'none');
					stepId += 1;
					$(this).attr('step', stepId);
					$("#content ol.steps").find("li.current")
						.removeClass("current")
						.addClass("done")
						.next("li")
						.addClass("current");

					if(stepId > 4) {
						$('button#surveysubmit').css('background', 'url("/i/btns/send.png") no-repeat scroll 0 0');
						$('div#remark').css('display', 'none');
					}
					$('div#step'+stepId).css('display', 'block');
				} else {
					stepId += 1;
					$(this).attr('step', stepId);
					$('#form-survey').submit();
				}
			}
		});

	});
});

$(function(){
	function insertLI($t, selectedvalue, str, optgroup) {
		var selectedtext = "";

		if(selectedvalue == $t.attr("value")) {
			selectedtext = $t.html();
		}
		var cls = (optgroup?"optgroupitem":"");
		cls += (selectedvalue == $t.attr("value")?((cls!=""?" ":"") +"current"):"");
		str.push("<li"
			+ (cls?" class=\"" + cls + "\"":"")
			+ " value=\"" + $t.attr("value")+ "\""
			+ ((selectedvalue == $t.attr("value"))?(" class=\"current\""):(""))
			+ ">" + $t.html().replace("&nbsp;", " ") + "</li>");

		return selectedtext;
	}

	$("select.dropdown-alt").bind("sync", function(e){
		var $ul = $(this).siblings("div.dropdown-alt-cont").find("ul");
		var $sp = $(this).siblings("a.dropdown-alt-value").find("span.value");

		$ul.html("");

		var selectedvalue = $(this).val();
		var selectedtext  = "";
		var str = Array();

		$(this).children().each(function(){
			var optgroup = (this.tagName.toLowerCase() == "optgroup")?1:0;
	
			if(optgroup) {
				var li = 
				[
					"<li class='optgrouphead' value='", $(this).attr('value'), "'>",
						$(this).attr('label').replace('&nbsp;', ' '),
					"</li>"
				].join('')

				str.push(li);

				$(this).children().each(function(){
					var sel = insertLI($(this), selectedvalue, str, 1);
					if(sel != "") selectedtext = sel;
				});
			} else {
				var sel = insertLI($(this), selectedvalue, str, 0);
				if(sel != "") selectedtext = sel;
			}
		});



		$sp.html(selectedtext);
		
		for(i in str) {
			$ul.append(str[i]); 
		}

		//delete dublicates
		var $li = $ul.children();

		if ($li.eq(0).html() == $li.eq(1).html()) {
			$li.eq(1).remove();
		}

		$sp.siblings("span.d-l").width(($sp.width() + parseInt($sp.css("padding-left")) + parseInt($sp.css("padding-right"))) + "px");

		$ul.find("li").hover(function(){
			$(this).addClass("hovered");
		}, function(){
			$(this).removeClass("hovered");
		}).each(function(index){
			$(this).click(function(e, data){
				$(this).addClass("current")
					.siblings("li").removeClass("current");

				var $a = $(this).parents("div.dropdown-alt-cont").eq(0)
					.siblings("a.dropdown-alt-value");
				$a
					.find("span.value")
						.html($(this).html()).end()
					.find("span.d-l")
						.width($a.width() + "px");

				var input = ["<input type='hidden' name='region' value='", $(this).attr('value'), "' />"].join('');

				$("form#regions").append(input);
				$("form#regions").trigger("submit");

				if(typeof(data) == "undefined" || typeof(data.donthide) == "undefined" || data.donthide == false) {
					$("body").trigger("click");
				}

				return false;
			});
		});

		/*$(this).trigger("change");*/

	}).each(function(){
		$(this).wrap("<div class=\"dropdown-alt\"></div>");
		$(this).removeClass("dropdown-alt");

		var name = $(this).attr("name") || "";
		$(this).parents("div.dropdown-alt").eq(0)
			.attr("id", ((name=="")?(""):("dropdown-alt-for-" + name)))
			.append("<a class=\"dropdown-alt-value\" href=\"#"+ name+ "\"></a>")
			.append("<div class=\"dropdown-alt-cont\"></div>").find("div.dropdown-alt-cont")
				.append("<div class=\"dropdown-alt-bg\"></div>")
				.append("<div class=\"scroller\"><ul class=\"dropdown-alt-values\"></ul></div>")
				/*
				")
				.append("<div class=\"dropdown-alt-scroller\"></div>").find("div.dropdown-alt-scroller")
					.append("<a href=\"#scroll-up\" class=\"scroller scroller-up\"></a>")
					.append("<a href=\"#scroll-down\" class=\"scroller scroller-down\"></a>")
					.append("<div class=\"dropdown-alt-scroller-cont\"></div>")*/;

		$(this).siblings("a.dropdown-alt-value")
			.prepend("<span class=\"d d-l\"></span><span class=\"d d-r\"></span><span class=\"value\"></span>");

		/*
		var iframe = document.createElement("iframe"); /* for ie6 select over fix 
		$(iframe).attr({"id": "fixer", "name": "fixer"})
			.load(function(){
				$(this.contentWindow.document.body).click(function(){
					$(document).trigger("click");
				});
			}).attr("src", "about:blank");
		$(this).siblings("div.dropdown-alt-cont").append(iframe);
		*/
		var settings = {
			showArrows: true,
			animateScroll: true
		};
		var pane = $('.region-select .scroller').jScrollPane(settings);
		var api = pane.data('jsp');
		
		$(this).siblings("a.dropdown-alt-value")
			.attr("tabindex", $(this).attr("tabindex"))
			.focus(function(){
				$(this).addClass("focused")
			}).blur(function(){
				$(this).removeClass("focused")
			}).click(function(e){
				e.preventDefault();
				e.stopPropagation();
			}).hover(function(){
				$(this).addClass("hovered");
			}, function(){
				$(this).removeClass("hovered");
			}).mousedown(function(e, data){
				$("#dropdown-alt-for-region").eq(0).toggleClass("dropdown-alt-shown");
				
				api.reinitialise();
				

				var $scrlr = $(this).siblings("div.dropdown-alt-cont").find("div.dropdown-alt-scroller");
			}).keydown(function(e){
				if(e.keyCode == '13') { // enter
					$(this).trigger("click");
					return false;
				}
				if(e.keyCode == '38') { // up
					var curLI = $(this).siblings("div.dropdown-alt-cont").find("li.current");
					do
						curLI = curLI.prev("li");
					while(curLI.hasClass("optgrouphead"));

					curLI.trigger("click", {"donthide": true});
					return false;
				}
				if(e.keyCode == '40') { // down
					var curLI = $(this).siblings("div.dropdown-alt-cont").find("li.current");
					do
						curLI = curLI.next("li");
					while(curLI.hasClass("optgrouphead"));

					curLI.trigger("click", {"donthide": true});
					return false;
				}
				if(e.keyCode == '9') { // tab
					$(this).parents("div.dropdown-alt").eq(0).removeClass("dropdown-alt-shown");
				}
			}).keypress(function(e){ // opera fix
				if(e.keyCode == '13') // enter
					e.preventDefault();
			}).end()
		/*.attr("disabled", "disabled")*/
		.trigger("sync");

		

		$(this).parents("div.dropdown-alt").eq(0)
			.addClass("dropdown-alt-scrolling")
			.addClass("dropdown-altered");
	});

	$("body").click(function(e){
		/*
		var $rul = $("div.dropdown-alt-shown");

		var $selinput = $(e.target).closest("a.dropdown-alt-value");
		if($selinput.length > 0)
			$rul = $rul.not($selinput.parents("div.dropdown-alt").eq(0));

		var $select = $(e.target).closest("select");
		if($select.length > 0) {
			$rul = $rul.not($select.parents("div.dropdown-alt").eq(0));
		}

		var $label = $(e.target).closest("label");
		if($label.length > 0) {
			$rul = $rul.not($("div#dropdown-alt-for-"+$label.attr("for")).eq(0));
		}
		var $optgrouphead = $(e.target).closest("li.optgrouphead");
		if($optgrouphead.length > 0) {
			$rul = $rul.not($optgrouphead.parents("div.dropdown-alt").eq(0));
		}
		$rul.removeClass("dropdown-alt-shown");
		*/
	});
});

$(function(){
	try {
		$('body > .promo-pic').each(function() {
			if(baloons.flash.length > 0) {
				$(this).prepend('<div id="baloons"></div>')
				var promo = new SWFObject(baloons.flash, 'baloonsF', '370', '503', 6, '#ffffff');
				promo.addParam('targetUrl', baloons.link);
				promo.addParam('wmode', 'opaque');
				promo.write('baloons');
			}
		});
	} catch(e) {
	}
});


