var curArtist, globalItem;
var songList = new Array();
var itemURL = new Array();
var c = 0;
var oldLet = '';
var SLsorted = false;
var sortingDone = false;
var sorted = '';
var unsorted = '';

function expBand(e) {
	bandID = e.parentNode.id;
	if ($("#s" + bandID).css("display") == 'none') {
		$("#s" + bandID).show();
		$("#" + bandID + " a").css("background", "url(/img/sl-c.gif) no-repeat");
		$("#" + bandID + " a").attr("title", "Свернуть");
	} else {
		$("#s" + bandID).hide();
		$("#" + bandID + " a").css("background", "url(/img/sl-e.gif) no-repeat");
		$("#" + bandID).attr("title", "Развернуть");
	}
}

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 expandFactForm(id) {
	$("#" + id + "-factText").css("height", "200px");
	$("#" + id + "-factText").css("width", "90%");
	$("#" + id + " *").show();
}

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

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

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

function sendFEForm(type, id) {
	function checkFact() {
		check = $("#" + id + "-factText").attr("value");
		if (check.length > 10) {
			query += 'id=' + id;
			fields.push('factText', 'factSource', 'factUserName', 'factUserEmail');
		} else {
			alert('Заполните поле "текст"');
		}
	}

	function checkTranslation() {
		check = $("#" + id + "-text").attr("value");
		if (check.length > 10) {
			typeCheck = new Array("meaning", "rythmic", "cover");
			jQuery.each(typeCheck, function() {
				if ($("#" + id + "-type-" + this).attr("checked")) {
					query += '&type=' + this;
				}
			});
			query = query + '&id=' + id;
			fields.push('text', 'authorName', 'authorSite');
		} else {
			alert('Заполните поле "текст"');
		}
	}

	query = '';
	fields = new Array();
	if ((globalItem == 'band') && ($("#bandName").attr("value").length < 3)) {
		alert("Укажите название группы или исполнителя");
	} else {
		if ((type == 'addFact') || (type == 'addArtistFact')) {
			checkFact();
		}
		if (type == 'addTranslation') {
			checkTranslation();
		}
		if (type == 'addLyrics') {
			check = $("#" + id + "-text").attr("value");
			if (check.length > 10) {
				query += 'id=' + id;
				fields.push('text');
			} else {
				alert('Заполните поле "текст"');
			}
		}
		if (type == 'addAny') {
			check1 = false;
			check2 = false;
			check3 = false;
			check = $("#" + id + "-factText").attr("value");
			if (check.length > 10) {
				check1 = true;
				checkFact();
				query = query + '&addSwitch=fact';
			}
			check = $("#" + id + "-text").attr("value");
			if (check.length > 10) {
				check2 = true;
				checkTranslation();
				query = query + '&addSwitch=translation';
			}
			check = $("#" + id + "-lyrics").attr("value");
			if (check.length > 10) {
				check3 = true;
				fields.push('lyrics');
				query = query + '&addSwitch=lyrics';
			}
			if (check1 || check2 || check3) {
			} else {
				fields = '';
				query = '';
				alert("Напишите факт, текст песни или перевод");
			}
			if ($("#songTitle").attr("value").length < 3) {
				fields = '';
				alert('Введите название песни');
			}
		}
		if (fields) {
			if ((type != 'addLyrics') && (type != 'addArtistFact')) {
				if (($("#bandID").length > 0) && ($("#bandName").length > 0)) {
					bandIDCheck = $("#bandID").attr("value").length;
					bandNameCheck = $("#bandName").attr("value").length;
					if ((bandIDCheck > 0) || (bandNameCheck > 2)) {
						query = query + '&bandID=' + $("#bandID").attr("value");
						query = query + '&bandName=' + $("#bandName").attr("value");
						query = query + '&songTitle=' + $("#songTitle").attr("value");
					} else {
						alert("Укажите название группы или имя исполнителя");
						fields = array();
						query = '';
					}
				}
			}
		} else {
			query = '';
		}
	}
	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 == '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") {
		$("#startPageAddItem").html("<p class='thankYouPopUp'>Спасибо!</p>");
		switch (type) {
		case 'addComment':
			setTimeout("this.location.reload(true);", 1000);
			break;
		case 'subscribeFacts':
			$("#" + id + "-msg").html("Вы успешно подписаны.");
			$("#" + id + "-submit").hide("");
			break;
		default:
			setCookie("display=thankYou");
			setCookie("action=" + data.action);
			setTimeout("this.location.reload(true);", 1000);
		}
	} else {
		alert(data.reason);
		$("#" + id + "-msg").html("");
		$("#" + id + "-fields").show("");
	}
}

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

function addItemSW(item) {
	$("#addFormFields>div").addClass("invisible");
	$("#" + item + "Fields").removeClass("invisible");
	$("#addItemSW>span").removeClass("active");
	$("#addItemSW-" + item).addClass("active");

}

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

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

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

function giveMePopupAddNew() {
	loadPopup();
	$("#popupAddItem").fadeIn();
	centerPopup();
};

$(document).ready(function() {
	$("#popupCommonClose").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);
	}
	giveMePopupAddNew();
	if ((item == "song") && (itemID.length > 0)) {
		$("#newBand").hide();
	}
}

function addFactOnArtist() {
	loadPopup();
	$("#popupAddArtistFact").fadeIn();
	centerPopup();
}

function addBandSelect() {
	$v = $("#bandSelector").attr("value");
	if (($v != '') && ($v != 'new')) {
		$("#bandID").attr("value", 'band-' + $v);
	}
	if ($v == 'new') {
		$("#bandID").attr("value", "band-new");
		$("#newBandName").show();
		globalItem = 'band';
	} else {
		$("#newBandName").hide();
		globalItem = 'song';
	}
}

/*-------------*/
function sortByTitle(a, b) {
	var x = a.ttl.toLowerCase();
	var y = b.ttl.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function printOneSong(song) {
	songLink = '';
	let = song.ttl.substring(0, 1);
	if (oldLet != let) {
		if (c > 0) {
			songLink = '<p>&nbsp;</p>';
		}
		oldLet = let;
	}
	c++;
	songLink += '<p><a href="/song/' + itemURL[curArtist] + '/' + song.url + '/">' + song.ttl + '</a>&nbsp;<span class="factsCount">(' + song.NOF + ')</span></p>';
	return songLink;
}

function sortSongListHasFacts() {
	if (curArtist == 'band-1') {
		$("#songList-" + curArtist + " #songListCont").html('');
		callMode = $("#callMode").attr("value");
		if (callMode == 'artistPage') {
			$("#songListCont").html('');
		}
		mode = $("#songListHasFacts").attr("checked");
		songListHTML = '';
		$.each(songList, function() {
			if (this.item + '-' + this.id == curArtist) {
				if ((mode == true) && (this.NOF == 0)) {
				} else {
					songListHTML += printOneSong(this);
				}
			}
		});
		$("#songList-" + curArtist + " #songListCont").html(songListHTML);
		if (callMode == 'artistPage') {
			$("#songListCont").html(songListHTML);
		}
	}
}

/* ------------------- */
function displayCommentsReplyForm(id) {
	$("#comments .replyForm").html('');
	$("#replyForm-" + id).html($("#commentsAddForm").html());
	$("#replyForm-" + id + " .FEForm").css("margin-top", "10px");
	$("#replyForm-" + id + " h3").replaceWith('Ответить на комментарий:');
	$("#replyForm-" + id + " .ancestor").attr("value", id);

}

/* --------------------------------- */
/* 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>' + data.resultRating + '</div>');
}

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

/* --------------------------------- */
/* Seach Caption */
/* --------------------------------- */

function inpCap(input, value, cssC, cssE) {
	var tC = this
	this.Input = input
	this.Value = value
	this.SO = (input.value == value)
	this.cssC = cssC
	this.cssE = cssE
	this.sEv(this.Input, 'focus', function() {
		return tC.onFocus()
	})
	this.sEv(this.Input, 'blur', function() {
		return tC.onBlur()
	})
	this.sEv(this.Input, 'keydown', function() {
		return tC.onKeyDown()
	})
	if (input.value == '')
		this.onBlur();
	return this
}

inpCap.prototype.sEv = function(elem, eventType, handler) {
	if (elem.attachEvent) {
		elem.attachEvent('on' + eventType, handler)
	}
	if (elem.addEventListener) {
		elem.addEventListener(eventType, handler, false)
	}
}

inpCap.prototype.onFocus = function() {
	if (!this.SO && this.Input.value == this.Value) {
		this.Input.value = ''
	} else {
		this.Input.className = ''
	}
}

inpCap.prototype.onKeyDown = function() {
	this.Input.className = ''
}

inpCap.prototype.onBlur = function() {
	if (this.Input.value == '' || this.Input.value == this.Value) {
		this.Input.value = this.Value
		this.Input.className = this.cssE
	} else {
		this.Input.className = this.cssC
	}
}

/* --------------------------------- */
/* / Search Caption */
/* --------------------------------- */

function toBlog(id, songTitle, songURL, bandName, bandURL) {
	loadPopup();
	$("#popupToBlog").fadeIn();
	centerPopup();

	code = '<table cellpadding="10px" style="background-color:#E9FFE5; width: 450px; display: table; font-family:Tahoma,Verdana,Arial; font-size:10pt;"><tr><td><p><strong>Интересный факт о ';
	if (songTitle) {
		code += 'песне <a href="http://music-facts.ru/song/' + bandURL + '/' + songURL + '/">' + songTitle + '</a>';
		code += ' &mdash; <a href="http://music-facts.ru/artist/' + bandURL + '/">' + bandName + '</a></strong></p>';
	} else {
		code += ' исполнителе <a href="http://music-facts.ru/artist/' + bandURL + '/">' + bandName + '</a></strong>';
	}
	src = $("#fact-" + id + " .fi").attr("src");
	if (!src) {
		src = $("#fi").attr("src");
		if (src) {
			src = src.replace('/songs/', '/songs/_thumbs/');
		}
	}
	if (src) {
		code += '<img src="http://music-facts.ru' + src + '" style="float: left; margin: 0px 10px 10px 0px;">';
	}
	code += $("#fact-" + id + " .pureText").html();
	if ($("#fact-" + id + " .fm").attr("href")) {
		code += '<p><a href="http://music-facts.ru' + $("#fact-" + id + " .fm").attr("href") + '">Скачать MP3: ' + $("#fact-" + id + " .fm").text() + '</a></p><br/>';
	}
	if (songTitle) {
		code += '<p>Другие факты о <a href="http://music-facts.ru/song/' + bandURL + '/' + songURL + '/">песне ' + songTitle + '</a>';
	} else {
		code += '<p>Другие факты на странице исполнителя <a href="http://music-facts.ru/artist/' + bandURL + '/">' + bandName + '</a>';
	}
	code += '.</p></td></tr></table>';

	$("#codeToBlog").attr('value', code);

	document.getElementById("codeToBlog").onclick = function() {
		document.getElementById("codeToBlog").select();
	}
}

function initBandList() {
	$("#startPageSongList>div>span:even").html('<a class="expander" href="/" onclick="expBand(this); return false;" title="Развернуть"></a>');
}

function swTr(id) {
	$("#tr" + id).toggle();
}

/**
 * @author Falchenko Maxim aka be3
 * @plugin_page http://tops.net.ua/jquery_addtocopy/
 * @desc Adds a link to the copied text
 * @version 1.2
 * @example $("#content").addtocopy();
 * @license free
 */
jQuery.fn.addtocopy = function(usercopytxt) {
	var options = {
		htmlcopytxt : '<br>More: <a href="' + window.location.href + '">' + window.location.href + '</a><br>',
		minlen : 25,
		addcopyfirst : false
	}
	$.extend(options, usercopytxt);
	var copy_sp = document.createElement('span');
	copy_sp.id = 'ctrlcopy';
	copy_sp.innerHTML = options.htmlcopytxt;
	return this.each(function() {
		$(this).mousedown(function() {
			$('#ctrlcopy').remove();
		});
		$(this).mouseup(function() {
			if (window.getSelection) { // good times
					var slcted = window.getSelection();
					var seltxt = slcted.toString();
					if (!seltxt || seltxt.length < options.minlen)
						return;
					var nslct = slcted.getRangeAt(0);
					seltxt = nslct.cloneRange();
					seltxt.collapse(options.addcopyfirst);
					seltxt.insertNode(copy_sp);
					if (!options.addcopyfirst)
						nslct.setEndAfter(copy_sp);
					slcted.removeAllRanges();
					slcted.addRange(nslct);
				} else if (document.selection) { // bad times
					var slcted = document.selection;
					var nslct = slcted.createRange();
					var seltxt = nslct.text;
					if (!seltxt || seltxt.length < options.minlen)
						return;
					seltxt = nslct.duplicate();
					seltxt.collapse(options.addcopyfirst);
					seltxt.pasteHTML(copy_sp.outerHTML);
					if (!options.addcopyfirst) {
						nslct.setEndPoint("EndToEnd", seltxt);
						nslct.select();
					}
				}
			});
	});
}

$(document).ready(function() {
	if ($("#selfAd")) {
		$.post('/ajax/self-ad/', '', function(json) {
			$("#selfAd").html(json.ad);
		}, 'json');
	}
	if ($(".factText")) {
		$(".factText").addtocopy( {
			htmlcopytxt : '<br>Источник: <a href="' + window.location.href + '">' + window.location.href + '</a>',
			minlen : 35,
			addcopyfirst : false
		});
	}
});
