function setCookie(vars) {
	today = new Date();
	ddate = new Date(today.getTime() + 63072000000);
	document.cookie = vars + "; expires=" + ddate.toGMTString() + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for ( var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length, c.length);
	}
}

function expandSubscriptionForm(id) {
	$("#" + id + "-mail").attr("value", "");
	$("#" + id + "-invisiblePart").show("slow");
}

function expandCommentForm(id) {
	$("#" + id + "-text").css("height", "200px");
	$("#" + id + "-text").css("width", "90%");
	$("#" + id + " *").show();
}

function sendFEForm(type, id) {
	query = '';
	fields = new Array();
	if (type == 'addComment') {
		check = $("#" + id + "-text").attr("value");
		if (check.length > 10) {
			setCookie("usermail=" + $("#" + id + "-userEmail").attr("value"));
			fields = new Array('text', 'userName', 'userEmail', 'entityType', 'itemID', 'ancestor');
			if ($("#cSubscr").attr("checked")) {
				if ($("#" + id + "-userEmail").attr("value").length > 3) {
					query += '&cSubscr=yes';
				} else {
					fields = '';
					alert("Укажите ваш мейл, если хотите подписаться на комментарии");
				}
			}
		} else {
			alert('Заполните поле "текст"');
		}
	}
	if (type == 'addFeedback') {
		check = $("#" + id + "-text").attr("value");
		if (check.length > 10) {
			fields = new Array('text', 'userEmail');
		} else {
			alert('Заполните поле "текст"');
		}
	}
	if (type == 'subscribeFacts') {
		check = $("#" + id + "-mail").attr("value");
		if (check.length > 3) {
			typeCheck = new Array("sSong", "sBand", "sAll");
			setCookie("usermail=" + check);
			jQuery.each(typeCheck, function() {
				if ($("#" + id + "-type-" + this).attr("checked")) {
					query = '&type=' + this;
				}
			});
			query = query + '&id=' + id;
			fields = new Array('mail', 'bandID', 'songID');
			if ($("#sComments").attr("checked")) {
				query += '&sComments=yes'
			}
		} else {
			alert('Заполните поле "мейл"');
		}
	}
	if (fields) {
		jQuery.each(fields, function() {
			value = $("#" + id + "-" + this).attr("value");
			value = value.replace("&", ";amp;");
			query = query + '&' + this + '=' + value;
		});
	}
	if (query.length > 0) {
		$("#" + id + "-msg").html("Секундочку...");
		$("#" + id + "-fields").hide();
		$.post('/ajax/FEForm/' + type + '/', query, function(data, textStatus) {
			displaySubmissionResults(data, id, type)
		}, 'json');
	}
}

function displaySubmissionResults(data, id, type) {
	if (data.result == "ok") {
		switch (type) {
		case 'addFeedback':
			$("#feedbackForm").html('<p>Спасибо! Мы обязательно прочитаем Ваше сообщение.</p>');
			break;
		case 'addComment':
			setTimeout("this.location.reload(true);", 1000);
			break;
		case 'subscribeFacts':
			$("#" + id + "-msg").html("Вы успешно подписаны.");
			$("#" + id + "-submit").hide("");
			break;
		default:
			setTimeout("this.location.reload(true);", 1000);
		}
	} else {
		if (data.result == "zorex") {
			alert(data.reason);
			setTimeout("this.location.reload(true);", 1000);
		} else {
			$("#" + id + "-msg").html("");
			$("#" + id + "-fields").show("");
		}
	}
}

function refreshComments() {

}

function value(a, b) {
	if (a[1] < b[1])
		return -1;
	if (a[1] > b[1])
		return 1;
	return 0;
}

/*-------------*/
var popupStatus = 0;
function loadPopup() {
	if (popupStatus == 0) {
		$("#backgroundPopup").css( {
			"opacity" : "0.7"
		});
		$("#backgroundPopup").fadeIn();
		$("#popupAddForm").fadeIn();
		popupStatus = 1;
	}
}

function disablePopup() {
	if (popupStatus == 1) {
		$("#backgroundPopup").fadeOut();
		$("#popupAddForm").fadeOut();
		popupStatus = 0;
	}
}

function centerPopup() {
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupAddForm").height();
	var popupWidth = $("#popupAddForm").width();
	$("#popupAddForm").css( {
		"position" : "absolute",
		"top" : windowHeight / 2 - popupHeight / 2,
		"left" : windowWidth / 2 - popupWidth / 2
	});
	$("#backgroundPopup").css( {
		"height" : windowHeight
	});
}

function giveMePopup() {
	centerPopup();
	loadPopup();
};

$(document).ready(function() {
	$("#popupAddFormClose").click(function() {
		disablePopup();
	});
	$("#backgroundPopup").click(function() {
		disablePopup();
	});
	$(document).keypress(function(e) {
		if (e.keyCode == 27 && popupStatus == 1) {
			disablePopup();
		}
	});
});

/*-------------*/

function addNew(item, itemID) {
	globalItem = item;
	if ((item == "song") && (itemID.length > 0)) {
		$("#newBandPatch").html("<p>Исполнитель: " + $("#" + itemID + "-SW").text() + "</p>");
		$("#bandID").attr("value", itemID);
	}
	/*if (item=="band") {
	    $("#newBandPatch").addClass("invisible");
	    $("#newBand").show("fast");
	    $("#bandID").attr("value", "band-new");
	}*/
	giveMePopup();
	if ((item == "song") && (itemID.length > 0)) {
		$("#newBand").hide();
	}
}

/* ------------------- */
function displayCommentsReplyForm(id) {
	if ($("#replyForm-" + id).html() == '') {
		$("#comments .replyForm").html('');
		$("#replyForm-" + id).html($("#commentsReplyForm").html());
		$("#replyForm-" + id + " .FEForm").css("margin-top", "10px");
		$("#replyForm-" + id + " h3").replaceWith('');
		$("#replyForm-" + id + " .ancestor").attr("value", id);

		expandCommentForm("FEForm-addComment-article-0-reply")

	} else {
		$("#replyForm-" + id).html('');
	}
}

/* --------------------------------- */
/* rating -------------------------- */
/* --------------------------------- */

function changeRating(entity, id, action) {
	if (markuser == 'yes') {
		setCookie('userid=' + userid);
	}
	check = readCookie('userid');
	if (userid == check) {
		query = '';
		$.post('/ajax/change-rating/' + entity + '/' + id + '/' + action + '/', query, function(data, textStatus) {
			changeRatingAction(entity, id, action, data)
		}, 'json');
	} else {
		alert('Для голосования необходимо включить поддержку cookie в браузере');
	}
}

function changeRatingAction(entity, id, action, data) {
	$("#rating-" + entity + "-" + id).html('<div class="ratingValue">' + data.resultRating + '</div>');
}

/*
 * jQuery UI Stars v2.1.1
 * Copyright (c) 2009 Orkan (orkans@gmail.com)
 * $Rev: 114 $
 */

(function($) {
	$.widget("ui.stars", {
		_init : function() {
			var self = this, o = this.options, id = 0;

			o.isSelect = o.inputType == "select";
			this.$form = $(this.element).closest("form");
			this.$selec = o.isSelect ? $("select", this.element) : null;
			this.$rboxs = o.isSelect ? $("option", this.$selec) : $(":radio", this.element);

			this.$stars = this.$rboxs.map(function(i) {
				var el = {
					value : this.value,
					title : (o.isSelect ? this.text : this.title) || this.value,
					isDefault : (o.isSelect && this.defaultSelected) || this.defaultChecked
				};

				if (i == 0) {
					o.split = typeof o.split != "number" ? 0 : o.split;
					o.val2id = [];
					o.id2val = [];
					o.id2title = [];
					o.name = o.isSelect ? self.$selec.get(0).name : this.name;
					o.disabled = o.disabled || (o.isSelect ? $(self.$selec).attr("disabled") : $(this).attr("disabled"));
				}

				if (el.value == o.cancelValue) {
					o.cancelTitle = el.title;
					return null;
				}

				o.val2id[el.value] = id;
				o.id2val[id] = el.value;
				o.id2title[id] = el.title;

				if (el.isDefault) {
					o.checked = id;
					o.value = o.defaultValue = el.value;
					o.title = el.title;
				}

				var $s = $("<div/>").addClass(o.starClass);
				var $a = $('<a/>').attr("title", o.showTitles ? el.title : "").text(el.value);

				if (o.split) {
					var oddeven = (id % o.split);
					var stwidth = Math.floor(o.starWidth / o.split);
					$s.width(stwidth);
					$a.css("margin-left", "-" + (oddeven * stwidth) + "px");
				}

				id++;
				return $s.append($a).get(0);
			});
			o.items = id;
			o.isSelect ? this.$selec.remove() : this.$rboxs.remove();
			this.$cancel = $("<div/>").addClass(o.cancelClass).append($("<a/>").attr("title", o.showTitles ? o.cancelTitle : "").text(o.cancelValue));
			o.cancelShow &= !o.disabled && !o.oneVoteOnly;
			o.cancelShow && this.element.append(this.$cancel);
			this.element.append(this.$stars);
			if (o.checked === undefined) {
				o.checked = -1;
				o.value = o.defaultValue = o.cancelValue;
				o.title = "";
			}

			this.$value = $('<input type="hidden" name="' + o.name + '" value="' + o.value + '" />');
			this.element.append(this.$value);
			this.$stars.bind("click.stars", function(e) {
				if (!o.forceSelect && o.disabled)
					return false;

				var i = self.$stars.index(this);
				o.checked = i;
				o.value = o.id2val[i];
				o.title = o.id2title[i];
				self.$value.attr( {
					disabled : o.disabled ? "disabled" : "",
					value : o.value
				});

				fillTo(i, false);
				self._disableCancel();
				self._showCap("");
				!o.forceSelect && self.callback(e, "star");
			}).bind("mouseover.stars", function() {
				if (o.disabled)
					return false;
				var i = self.$stars.index(this);
				fillTo(i, true);
			}).bind("mouseout.stars", function() {
				if (o.disabled)
					return false;
				fillTo(self.options.checked, false);
				self._showCap("");
			});

			this.$form.bind("reset.stars", function() {
				!o.disabled && self.select(o.defaultValue);
			});

			$(window).unload(function() {
				self.$cancel.unbind(".stars");
				self.$stars.unbind(".stars");
				self.$form.unbind(".stars");
				self.$selec = self.$rboxs = self.$stars = self.$value = self.$cancel = self.$form = null;
			});

			function fillTo(index, hover) {
				if (index != -1) {
					var addClass = hover ? o.starHoverClass : o.starOnClass;
					var remClass = hover ? o.starOnClass : o.starHoverClass;
					self.$stars.eq(index).prevAll("." + o.starClass).andSelf().removeClass(remClass).addClass(addClass);
					self.$stars.eq(index).nextAll("." + o.starClass).removeClass(o.starHoverClass + " " + o.starOnClass);
					self._showCap(o.id2title[index]);
				} else
					fillNone();
			}
			;
			function fillNone() {
				self.$stars.removeClass(o.starOnClass + " " + o.starHoverClass);
				self._showCap("");
			}
			;

			this.select(o.value);
			o.disabled && this.disable();

		},

		_disableCancel : function() {
			var o = this.options, disabled = o.disabled || o.oneVoteOnly || (o.value == o.cancelValue);
			if (disabled)
				this.$cancel.removeClass(o.cancelHoverClass).addClass(o.cancelDisabledClass);
			else
				this.$cancel.removeClass(o.cancelDisabledClass);
			this.$cancel.css("opacity", disabled ? 0.5 : 1);
			return disabled;
		},
		_disableAll : function() {
			var o = this.options;
			this._disableCancel();
			if (o.disabled)
				this.$stars.filter("div").addClass(o.starDisabledClass);
			else
				this.$stars.filter("div").removeClass(o.starDisabledClass);
		},
		_showCap : function(s) {
			/*var o = this.options;
			if (o.captionEl) {
				o.captionEl.text(s);
			}*/
		},

		value : function() {
			return this.options.value;
		},
		select : function(val) {
			var o = this.options, e = (val == o.cancelValue) ? this.$cancel : this.$stars.eq(o.val2id[val]);
			o.forceSelect = true;
			e.triggerHandler("click.stars");
			o.forceSelect = false;
		},
		selectID : function(id) {
			var o = this.options, e = (id == -1) ? this.$cancel : this.$stars.eq(id);
			o.forceSelect = true;
			e.triggerHandler("click.stars");
			o.forceSelect = false;
		},
		enable : function() {
			this.options.disabled = false;
			this._disableAll();
		},
		disable : function() {
			this.options.disabled = true;
			this._disableAll();
		},
		destroy : function() {
			this.options.isSelect ? this.$selec.appendTo(this.element) : this.$rboxs.appendTo(this.element);
			this.$form.unbind(".stars");
			this.$cancel.unbind(".stars").remove();
			this.$stars.unbind(".stars").remove();
			this.$value.remove();
			this.element.unbind(".stars").removeData("stars");
		},
		callback : function(e, type) {
			var o = this.options;
			o.callback && o.callback(this, type, o.value, e);
			o.oneVoteOnly && !o.disabled && this.disable();
		}
	});

	$.extend($.ui.stars, {
		version : "2.1.1",
		getter : "value",
		defaults : {
			inputType : "radio", // radio|select
			split : 0,
			disabled : false,
			cancelTitle : "Cancel Rating",
			cancelValue : 0,
			cancelShow : true,
			oneVoteOnly : false,
			showTitles : false,
			captionEl : null,
			callback : null, // function(ui, type, value, event)

			starWidth : 16,
			cancelClass : 'ui-stars-cancel',
			starClass : 'ui-stars-star',
			starOnClass : 'ui-stars-star-on',
			starHoverClass : 'ui-stars-star-hover',
			starDisabledClass : 'ui-stars-star-disabled',
			cancelHoverClass : 'ui-stars-cancel-hover',
			cancelDisabledClass : 'ui-stars-cancel-disabled'
		}
	});

})(jQuery);

function selfAd() {
	$.post('/ajax/self-ad/', '', function(data, textStatus) {
		$('#selfAdv').html(data);
	}, 'html');
}

var dquery;

function domaStep2() {
	$("#intro").hide();
	var i, val;
	dquery = '';
	var ok = true;
	for (i = 1; i <= 8; i++) {
		val = $("input[name='q" + i + "']:checked").val();
		if (val) {
			dquery += "&q" + i + "=" + val;
		} else {
			ok = false;
		}
	}
	if (ok) {
	$("#domaStep1").fadeOut();
	$("#domaDiseases").fadeIn();
	} else {
		alert ("Надо заполнить все поля")
	}
}

function domaGetResult() {
	if (markuser == 'yes') {
		setCookie('userid=' + userid);
	}
	$("#domaDiseases").fadeOut();
	pr = $("#resultsReceipts");
	pr2 = $("#printResults");
	pr.html('Загрузка...');
	
	var i=0;
	for (i = 1; i <= 19; i++) {
		if ($("#i"+i).attr("checked")) {
			dquery+='&i'+i+'=checked';
		}
	}
	$.post('/ajax/doma-getresult/', dquery, function(data, textStatus) {
		pr.html('<h1>Рекомендуемые Вам средства для лечения похмелья</h1><p class="head">Количество звёздочек указывает на то, насколько лекарство подходит вам сейчас</p>');
		for ( i = 0; i < data.rec.length; ++i) {
			if (data.rec[i].alw==true) {
			pr.append('<div id="rec'+i+'"><div class="leftColumn"><div class="squares">&nbsp;</div></div><div class="rec">'+$("#"+data.rec[i].id).html()+'</div></div>');
			$("#rec"+i+" div.squares").css("width", 14*data.rec[i].sc);
			}	
		}
		if (data.confl.length>0) {
			appendix = '<div id="appendix"><h2>Внимание! Некоторые из указанных средств несовместимы или дублируют друг друга.</h2>';
			for ( i = 0; i < data.confl.length; ++i) {
				confl='<p>Не сочетаются: ';
				for (di=0; di<data.confl[i].length; ++di) {
					confl+=''+$("#"+data.confl[i][di]+" .title ").html()+'';
					if (di < data.confl[i].length-1	) {
						confl+=', ';
					}
				}
				confl+='. Выберите что-нибудь одно из этих средств.</p>';
				appendix+= confl;
			}
		}
		if (data.orderNotice==true) {
			appendix += '<h2>Внимание!</h2><p>Если Вы будете чистить желудочно-кишечный тракт (промывание желудка или клизма), то это надо делать <strong>перед</strong> приёмом сорбентов (активированный уголь, «Полифепан», «Лиферан», «Лигносорб», «Фильтрум», «Полисорб», «Смекта» и другие).</div>';			
		}
		appendix += '<br/><br/><span class="lf"><a href="#" class="buttonStyle" onclick="domaPrintResult(); return false;">Версия для печати</a></span><p class="comment head">(откроется в новом окне)</p><br/><br/><br/><br/><p>Если у вас есть вопросы или пожелания, <a href="mailto:pavel@gubarev.ru">пишите</a>, постараемся ответить.</p><br/><p>Если Вам помогло, поставьте ссылку на эту страницу у себя в блоге или соцсети, пригодится друзьям:  <nobr><a href="http://pohmelje.ru/lechenie-doma/">http://pohmelje.ru/lechenie-doma/</a></nobr></p>';
		pr2.append(appendix);
	}, 'json');
}

function makeStarsOnStartPage() {
	var whichstar;
	$(".strs").each(function() {
		rating = $(this).text();
		id = $(this).attr("id");
		whichstar = Math.round(rating);
		stars = '<div id="stars-wrapper'+id+'" class="stars"><select name="selrate">';
		for (i=1;i<=5;i++) {
			stars+='<option value="'+i+'"';
			if (i==whichstar) {
				stars+=' selected="selected"';
			}
			stars+='></option>';
		}
		stars+='</select></div>';
		$(this).html(stars);
		cmd = '$("#stars-wrapper"+id).stars({ inputType: "select", oneVoteOnly: true,captionEl: null, disabled:';
		cmd+= ($(this).attr("title")=='1') ? 'true' : 'false';
		cmd+= ', callback: function(ui, type, value){changeRating("articles","'+id+'",value);}});';
		eval (cmd);
	});
}

function domaPrintResult() {
	printWindow = window.open('/print.html','domaPrint', 'width=600, height=500, scrollbars=yes, menubar=yes');
	printWindow.document.title = 'pohmelje.ru Ваши средства от похмелья';
}

function putContent() {
	printVersion = '<h1>Ваши средства для лечения похмелья</h1><ol>';
	$("#resultsReceipts .rec").each( function() {
		printVersion+='<li>'+$(this).html()+'</li>';
	});
	printVersion+='</ol>';
	printVersion+= $("#appendix").html();
	printVersion+= '<br/><p>&copy; pohmelje.ru</p>';
	printWindow.document.getElementById('bodyHere').innerHTML = printVersion;
	printWindow.print();
}
 
