var litera;
var subMenuClick = 0;
var lastSongs = '';
var tmpVar = new Array;
var userNotLoggedId = 0;
var userLogged = 0;
var lpath = '';
var done = new Array;

var mylib = {
	abstractPage : {
		init : function() {

			$('body').click(function() { 
				$(".headSelectAll").hide("500");
			}); 
			
			$('.headSelectAll').click(function(event){ 
				event.stopPropagation(); 
			}); 

			$(".headSelectLi").click(function(){
				$(".headSelectAll").toggle("500");
				return false;
			});

			$('#fastSearch').example('Поиск по сайту');

			$("#formUpload").attr("action", "http://emerald-lyrics.org/uploader_external.php");
			
			$("div.trackListLink").click(function(){
				$(".tracklist").toggle("500");
				$(".arr-u").toggle();
				$(".arr-d").toggle();
			});

			$("a.artistList").click(function(){
				litera = $(this).attr("id");
				if ($(this).hasClass("shown")) {
					//$("#allArtists"+litera).show();
				} else {
					$(this).html("загрузка...");
					$(this).addClass("artistListLoading");
					getAllArtists(litera);
				}
				return false;
			});

			$("#toTwitter").hover(function(){ $(".showTwitter h4").show(); }, 
								  function() { $(".showTwitter h4").hide();	});

			$("#toKontakt").hover(function(){ $(".showKontakt h4").show(); }, 
								  function() { $(".showKontakt h4").hide();	});

			$("#toBrouser").hover(function(){ $(".showBrouser h4").show(); }, 
								  function() { $(".showBrouser h4").hide();	});

			$("#toFacebook").hover(function(){ $(".showFacebook h4").show(); }, 
								   function() {	$(".showFacebook h4").hide(); });

			$("#toLj").hover(function(){ $(".showLj h4").show(); }, 
							 function() { $(".showLj h4").hide(); });

			$(".showTtAlbum").hover(function(){	$(".tolltipAlbum").show(); }, 
									function() { $(".tolltipAlbum").hide();	});

			$(".showTtAbc").hover(function(){ $(".tolltipAbc").show(); }, 
								  function() { $(".tolltipAbc").hide();	});

			$(".showTtRating").hover(function(){ $(".tolltipRating").show(); }, 
									 function() { $(".tolltipRating").hide(); });

			$(".setLiked").live( {
				mouseenter: function(){ $(this).attr('src', "/images/heart_fill.png"); },
				mouseleave: function(){ $(this).attr('src', "/images/heart.png"); }
				}
			);

			$(".setLiked").live('click', function(){ 
				setSongLike($(this).attr('id'), 'like');
			});

			$(".setUnliked").live('click', function(){ 
				setSongLike($(this).attr('id'), 'unlike');
			});

			$(".allLiterasDiv").hover(function(){
				$(this).stop().animate({left:0});
			}, function() {
				$(this).stop().animate({left:-37});
			});

			$("a.gotoLitera").click(function () {
				var anc = $(this).attr("href").substring(1);
				$("html:not(:animated)"+( ! $.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop: $("#"+anc).position().top});	
				return false;
			});

			var thisSite = $("#site").val();

			$("#fastSearch").autocomplete({
				serviceUrl: "/php/fastSearch.php",
				minChars: "3", 
				maxHeight: "400",
				width: 350,
				zIndex: "9999",
				loaderImg: "searchLoader",
				params: {site: thisSite},
				deferRequestBy: "300",
				onSelect: function(data, value){ 
					//pageTracker._trackPageview("/fastSearch/" + value);
					document.location.href=value;
					return false;
				}
			});
			
			var origShown = 0;

			//if ($.cookie("artistList") == "origList"){
			//	showOrig();
			//	origShown = 1;
			//}

			$(".showOrigin").click(function(){
				if (origShown == 0) {
					showOrig();
					origShown = 1;
				} else {
					$("#rus_artist").hide();
					$("#eng_artist").show();

					$("#rus_liters").hide();
					$("#eng_liters").show();

					$(".showRus").removeClass("notLink");
					$(".showOrigin").addClass("notLink");

					setOrigCoockie();
				}				
			});

			$(".showRus").click(function(){
				$("#rus_artist").show();
				$("#eng_artist").hide();

				$("#rus_liters").show();
				$("#eng_liters").hide();

				$(".showRus").addClass("notLink");
				$(".showOrigin").removeClass("notLink");

				setRusCoockie();
			});

			parseAuth();

			var eventLink = $(".eventBlock a");
			eventLink.each(function(){
				$(this).attr('href', $(this).attr('href') + '?from=eventBlock');
			});

		}
	},

// - - - - - - - - - - - - - - - - - - - Index - - - - - - - - - - - - - - - - - - - 

	index : {
		init : function() {

			$("#indexShow").click(function(){
				var flip = 0;
				var id = $("#megaHitId").val();
				$("#layoutText").toggle(500);
				if (flip == 0) {
					getNewText(id);
				}
			});

			$(".expandImg").click(function(){
				$("#firstColumn").hide();
				$("#textColumn").attr("colspan", "2");
				$(".expandImg").hide();
				$(".compressImg").show();
				return false;	
			});

			$(".compressImg").click(function(){
				$("#firstColumn").show();
				$("#textColumn").attr("colspan", "1");
				$(".compressImg").hide();
				$(".expandImg").show();
				return false;
			});

		}
	},

// - - - - - - - - - - - - - - - - - - - Search - - - - - - - - - - - - - - - - - - - 

	search : {
		init : function() {

			$("#showAllFoundInTitle").click(function(){
				$(".foundInTitle").show();
				$(this).hide();
				return false;
			});

			$("#showAllFoundInText").click(function(){
				$(".foundInText").show();
				$(this).hide();
				return false;
			});

			$("#showAllFoundInAlbum").click(function(){
				$(".foundInAlbum").show();
				$(this).hide();
				return false;
			});

		}
	},

// - - - - - - - - - - - - - - - - - - - Game - - - - - - - - - - - - - - - - - - - 

	game : {
		init : function() {

			var thisSite = $("#site").val();

			$("#searchArtist").autocomplete({
				serviceUrl: "/php/searchArtist.php",
				minChars: "3", 
				maxHeight: "400",
				width: 300,
				zIndex: "9999",
				loaderImg: "searchLoader2",
				params: {site: thisSite},
				deferRequestBy: "300",
				onSelect: function(data, value){ 
					document.location.href=value;
					return false;
				}
			});

		}
	},

// - - - - - - - - - - - - - - - - - - - Donate - - - - - - - - - - - - - - - - - - - 

	donate : {
		init : function() {

			$("#linkTextfr").bind("keyup mouseup focus blur input paste change", function(){
				$("#textLinkOutput").text("<a href='http://fr-lyrics.ru'>"+this.value+"</a>");
			});	

			$("#linkTextit").bind("keyup mouseup focus blur input paste change", function(){
				$("#textLinkOutput").text("<a href='http://it-lyrics.ru'>"+this.value+"</a>");
			});	

			$("#linkTextes").bind("keyup mouseup focus blur input paste change", function(){
				$("#textLinkOutput").text("<a href='http://es-lyrics.ru'>"+this.value+"</a>");
			});	

			$("#linkTextde").bind("keyup mouseup focus blur input paste change", function(){
				$("#textLinkOutput").text("<a href='http://de-lyrics.ru'>"+this.value+"</a>");
			});

			$("#linkTexten").bind("keyup mouseup focus blur input paste change", function(){
				$("#textLinkOutput").text("<a href='http://en-lyrics.ru'>"+this.value+"</a>");
			});	

			$(".getBouutonfr").focus(function(){
				$("#imgLinkOutput").text("<a href='http://fr-lyrics.ru'><img src='http://fr-lyrics.ru/images/fr/"+this.value+".gif' style='border:none;'/></a>");
			});

			$(".getBouutonit").focus(function(){
				$("#imgLinkOutput").text("<a href='http://it-lyrics.ru'><img src='http://it-lyrics.ru/images/it/"+this.value+".gif' style='border:none;'/></a>");
			});

			$(".getBouutones").focus(function(){
				$("#imgLinkOutput").text("<a href='http://es-lyrics.ru'><img src='http://es-lyrics.ru/images/es/"+this.value+".gif' style='border:none;'/></a>");
			});

			$(".getBouutonde").focus(function(){
				$("#imgLinkOutput").text("<a href='http://de-lyrics.ru'><img src='http://de-lyrics.ru/images/de/"+this.value+".gif' style='border:none;'/></a>");
			});

			$(".getBouutonen").focus(function(){
				$("#imgLinkOutput").text("<a href='http://en-lyrics.ru'><img src='http://en-lyrics.ru/images/en/"+this.value+".gif' style='border:none;'/></a>");
			});
		}
	},

// - - - - - - - - - - - - - - - - - - - AddSong - - - - - - - - - - - - - - - - - - - 

	addSong : {
		init : function() {
			checkArtist();

			$("#artist").autocomplete({
				serviceUrl: "../php/getArtist.php",
				minChars: "2", 
				maxHeight: "400",
				width: "310",
				loaderImg: "artistLoader",
				zIndex: "9999", 
				deferRequestBy: "300",
				onSelect: function(data, value){
					getAlbums(data);
					return false;
				}
			});

			var	sentArtist = '';

			$("#artist").bind("blur input change keyup", function(){

				var getByArtist = $(this).val();		

				if (getByArtist.length > 3) {
					getAlbums(getByArtist);
				} else {
					var list = $("#selectAlbum");
					list.empty();
					list.hide();			
					$("#newAlbum").show();
					$("#ruArtistTr").show();
				}
				return false;
			});	

			$("#selectAlbum").change(function(){
				setFields();
			});

			$("textarea#comment").bind("input paste change keyup", function(){
				if ($(this).val().length > 150){
					$(this).attr("style", "height:400px;");
				}
			});
		}
	},

// - - - - - - - - - - - - - - - - - - - googleTranslate - - - - - - - - - - - - - - - - - - - 

	googleTranslate : {
		init : function() {
			google.load("language", "1");
		    google.setOnLoadCallback(initTranslate);

			$("#trLink").click(function(){
				submitChange();
				$("#results").html("<span>Переводим...</span>");
				return false;
			});			

		}
	},

// - - - - - - - - - - - - - - - - - - - Devotion - - - - - - - - - - - - - - - - - - - 

	devotion : {
		init : function() {

			$("#useBonus").click(function(){
				var devotionId = $("#devotionId").val();
				var bonus = $("#bonus").val();

				$("#loadingBonus").show();

				checkBonus(devotionId, bonus);
				return false;
			});

			$('#formSender').example('Заголовок');
			$('#formText').example('Поздравительный текст');
			$('#formEmail').example('E-mail');
			$('#formText').maxlength();

			$("#sender").text($("#formSender").attr("value"));
			$("#recipient").text($("#formRecipient").attr("value"));
			$("#text").text($("#formText").attr("value"));

			$("#formSender").bind("keyup mouseup focus blur input paste change", function(){
				$("#sender").text($("#formSender").attr("value"));
			});

			$("#formText").bind("keyup mouseup focus blur input paste change", function(){
				var text = $("#formText").attr("value");
				text = replace_string(text, "\n", "<br/>");
				$("#text").text(text);
			});

			$("#formRecipient").bind("keyup mouseup focus blur input paste change", function(){
				$("#recipient").text($("#formRecipient").attr("value"));
			});

			$(".selectIcon").click(function(){
				var selectedId = $(this).attr("id");
				var selectedImg = $(this).attr("src");

				$("#devotionImage").attr("src", selectedImg);
				$("#selectedIcon").attr("value", selectedId);
				$("#allImages").hide();
			});

			$('body').click(function() { 
				$("#allImages").hide("500");
			}); 
			
			$('#allImages').click(function(event){ 
				event.stopPropagation(); 
			}); 

			$(".showAllImages").click(function(){
				$("#allImages").show(500);
				return false;
			});

			$("#operators").change(function(){
				$("#value").html($(this).attr("value"));
			});

			$("#country").change(function(){
				setOperators();
			});

			$(".howToBetBonus").click(function(){
				$("#howToGet").show('700');
			});

			setOperators();
		}
	},

// - - - - - - - - - - - - - - - - - - - Song - - - - - - - - - - - - - - - - - - - 

	song : {
		init : function() {

			$("textarea.errorForm").bind("input paste change keyup", function(){
				if ($(".errorForm").val().length > 100){
					$(".errorForm").attr("style", "height:400px;");
				}
			});

			$(".expandImg").click(function(){
				$("#firstColumn").hide();
				$("#textColumn").attr("colspan", "2");
				$(".expandImg").hide();
				$(".compressImg").show();
				return false;	
			});

			$(".compressImg").click(function(){
				$("#firstColumn").show();
				$("#textColumn").attr("colspan", "1");
				$(".compressImg").hide();
				$(".expandImg").show();
				return false;
			});

			$('body').click(function() { 
				$("#codeDiv").hide("500");
			}); 
			
			$('#codeDiv').click(function(event){ 
				event.stopPropagation(); 
			}); 

			$("#showCode").click(function(){
				$("#codeDiv").toggle("500");
				return false;
			});

			$("#tacode").click(function(){
				$(this).select();
			});

			$(".changeButtons").live('click', function(){
				var id = $(this).attr("id");
				var prev = $("#prev").attr("value");

				showVar(id, prev);

				if ($("#buttons").html() != '') {
					htmlBlock = $("#buttons").html();
				} else {
					htmlBlock = $("#buttonsBottom").html();
				}
			});

			$("#foundErrorLink").click(function(){
				$(".successSend").hide();
				$(".sendErrorDiv").show("500");
				return false;
			});
			
			$("#sendError").click(function(){
				if (!($(this).hasClass("artistListLoading"))) {
					$(this).html("отправка сообщения...");
					$(this).addClass("artistListLoading");
					sendErrorReport();
					return false;
				}
			});

			var varId = location.hash;
			var varId = varId.slice(2, 4);
			if (is_numeric(varId)) {
				var id = "var" + varId;
				var prev = "var1";
				showVar(id, prev);
			}

			var htmlBlock = $("#buttons").html();

			$(window).scroll(function() {
			if ($(window).scrollTop() > $("#buttons").parent().offset().top) {
				$("#buttons").removeClass('buttons');
				$("#buttons").addClass('buttons2');
			} else {
				$("#buttons").addClass('buttons');
				$("#buttons").removeClass('buttons2');
			}

			var scrollBottom = $(window).scrollTop() + $(window).height();
			if (scrollBottom > $("#buttonsBottom").offset().top) {
				$("#buttonsBottom").html(htmlBlock);
				$("#buttons").html('');
				$("#buttons").hide();
			} else {
				$("#buttonsBottom").html('');
				$("#buttons").html(htmlBlock);
				$("#buttons").show();
			}
			});

			videoBarTop = Math.ceil($("#videoBarHead").offset().top - 400);

			if (!$.browser.msie) {
				$(".resultDiv_gsvb img").live('click', function(){
					$(".floatingPlayerBox_gsvb").css('top', videoBarTop+'px');
					$(".floatingPlayer_gsvb").css('top', videoBarTop+'px');
				});
			}

			var section = 'tr.fontChange';
			var originalFontSize = $(section).css('font-size');  

			$(".resetFont").click(function(){
				$(section).css('font-size', originalFontSize);
			});
			 
			$("#increaseFont").click(function(){
				var currentFontSize = $(section).css('font-size');
				var currentFontSizeNum = parseFloat(currentFontSize, 10);
				var newFontSize = currentFontSizeNum + 1;
				$(section).css('font-size', newFontSize);
				return false;
			});
			 
			$("#decreaseFont").click(function(){
				var currentFontSize = $(section).css('font-size');
				var currentFontSizeNum = parseFloat(currentFontSize, 10);
				var newFontSize = currentFontSizeNum - 1;
				$(section).css('font-size', newFontSize);
				return false;
			});

			$("#playerFix").click(function(){
				if ($("#player").hasClass('playerFixed')) {
					$("#player").removeClass('playerFixed');
					$("#playerFix").addClass('outset');
					$("#playerFix").removeClass('inset');
				} else {
					$("#player").addClass('playerFixed');
					$("#playerFix").removeClass('outset');
					$("#playerFix").addClass('inset');
				}
				return false;
			});

			$('#showHelp').hover(function(event){ 
				$(".likeHelp").toggle();
			}); 

			$(".likeHelp").hover(function(){
				$(".likeHelp").toggle();
			});

			$(".likeHelp").html('<p>Отметьте какие песни вам нравятся и <a href="http://lyrsense.com/radio" target="_blank">персональное радио</a> сможет лучше ориентироваться в ваших вкусах.</p><p><a href="/likedSongs">Все ваши любимые песни</a>.</p>');

			checkLikedSong();
			setFootNotes();			
			checkEditSong('var1');

		}
	},

// - - - - - - - - - - - - - - - - - - - Feedback - - - - - - - - - - - - - - - - - - - 

	feedback : {
		init : function() {
			$("#reason").change(function(){
				setTr();
			});

			$("#reason").change(function(){
				setTexts();
			});

			setFields();
			setTr();
			setTexts();

		}
	},

// - - - - - - - - - - - - - - - - - - - ArtistAlbum - - - - - - - - - - - - - - - - - - - 

	artist : {
		init : function() {

			$('body').click(function() { 
				$(".setAlbumAttr").hide();
			}); 
					
			$('.albumImage').click(function(event){ 
				event.stopPropagation(); 
			}); 

			$('.setAlbumAttr').click(function(event){ 
				event.stopPropagation(); 
			}); 

			$(".albumImage").click(function(){
				var alId = $(this).attr('id');
				editAlbumsAttr(alId);
			});

			$(".albumAttr").change(function(){
				var id = $(this).attr('id');
				action = id.split('_');
				if ($(this).is(':checked'))	{
					var setAttr = 'true';
				} else {
					var setAttr = 'false';
				}

				//alert(action);
				var uid = $.cookie('userID');

				if ((in_array(uid, all)) || (in_array(uid, m_all)))	{
					$.post('/php/setAlbumAttr.php', {saAttr: action[0], saId: action[1], saAttrTo: setAttr}, onAjaxSuccess);
				}

				function onAjaxSuccess() {
					$("#saved" + action[1]).html("Сохранено");
				}

			});

			$(".showYears").click(function(){
				$("#yearsRow").toggle();
			});
		}
	},

// - - - - - - - - - - - - - - - - - - - Guestbook - - - - - - - - - - - - - - - - - - - 

	guestbook : {
		init : function() {
			$("#guestBookForm").attr("style", "display:none");

			$("#guestBookFormLink").click(function(){
				$("#guestBookForm").toggle("500");
			});

			$("a.answerLink").click(function(){
				var form = $(this).attr("id") + "div";
				$("#"+form).toggle();
			});

		}
	}
};

var all = ['1', '264'];
var m_all = ['19', '646', '6', '48', '440', '24', '815', '620', '400', '562', '120'];

function setSongLike(v_songAttr, v_action) {
	$.get('/api/setSongLike', {songAttr: v_songAttr, action: v_action}, onAjaxSuccess);
	$("#"+v_songAttr).after('<img src="/images/loader.gif" id="loaderHeart" width="10" height="10">');

	function onAjaxSuccess() {
		if (v_action == 'like') {
			$("#"+v_songAttr).attr('src', "/images/heart_fill.png");
			$("#"+v_songAttr).removeClass('setLiked');
			$("#"+v_songAttr).addClass('setUnliked');
			$("#loaderHeart").remove();
		} else {
			$("#"+v_songAttr).attr('src', "/images/heart.png");
			$("#"+v_songAttr).removeClass('setUnliked');
			$("#"+v_songAttr).addClass('setLiked');
			$("#loaderHeart").remove();
		}
	}
}

function checkLikedSong() {
	var v_songAttr = $(".likeSongLabel img").attr('id');

	if (v_songAttr != undefined) {
		$.get('/api/checkSongLike', {songAttr: v_songAttr}, onAjaxSuccess);
	}
	function onAjaxSuccess(xmlData) {
		if ($(xmlData).find('likedSong').text() == '1') {
			$("#"+v_songAttr).attr('src', "/images/heart_fill.png");
			$("#"+v_songAttr).removeClass('setLiked');
			$("#"+v_songAttr).addClass('setUnliked');
		}
	}
}

function editAlbumsAttr(alId) {
	var uid = $.cookie('userID');

	if ((in_array(uid, all)) || (in_array(uid, m_all)))	{
		alId = alId.substr(2);
		$("#saa" + alId).toggle();
	}
	return false;
}

function checkEditSong(trVar) {
	var uid = $.cookie('userID');
	var songId = $("#songId").attr('value');

	if (lpath == '') {
	if (in_array(uid, all)) {lpath = 'admin';}
	if (in_array(uid, m_all)) {lpath = 'moderator';}
	if (lpath != '') {
		lpath = '/'+lpath+'/songs/?do=edit&id='+songId;
		$('#breadcrumbs').append('(<a href="'+lpath+'">редактировать →</a>)');
	}}

	if (tmpVar[trVar] != 1){
		tmpVar[trVar] = 1;

		var idAuthor = $("#sp_author_"+trVar).attr("value");

		if (idAuthor > 0) {
			var cokiehash = $.cookie("userHash");
		
			if (cokiehash != '') {
				$.get('/php/checkEditSong.php', {idAuth: idAuthor}, onAjaxSuccess);
			}
		}
	}

	function onAjaxSuccess(xmlData) {
		if ($(xmlData).find('answer').text() == 'allow') {
			if (trVar == 'var1') {
				var songId = $("#songId").attr('value');
			} else {
				var songId = $("#add_song_"+trVar).attr('value');
			}
			var v = trVar.slice(3,4);
			var htmlLink = '<br/><a href="/editSong/'+songId+'?var='+v+'">Редактировать</a>'
			$("#author_"+trVar).append(htmlLink);

		}
	}
}

function checkEditBio() {
	var uid = $.cookie('userID');
	var artistId = $("#artistId").attr('value');
	if (lpath == '') {
	if (in_array(uid, all)) {lpath = 'admin';}
	if (in_array(uid, m_all)) {lpath = 'moderator';}
	if (lpath != '') {
		lpath = '/'+lpath+'/artists/?do=edit&id='+artistId;
		$('#breadcrumbs').append('(<a href="'+lpath+'">редактировать →</a>)');
	}}
}

function in_array(what, where) {
	for(var i=0; i<where.length; i++)
		if(what == where[i])
			return true;
	return false;
}

function parseAuth() {
	var cokiehash = $.cookie("userHash");
	if (cokiehash != '') {
		$.get('/api/checkAuth', {}, onAjaxSuccess);
	}
	function onAjaxSuccess(xmlData) {
		var answer = $(xmlData).find('type').text();
		if (answer == 'checked') {
			$("#helloWorld").html("Здравствуйте, <a href='#' class='dashed' id='vb_user'>" + $.cookie("userName") + "</a>");
			setVbUserInfo('VB user');
			var myDate = new Date();
			var timestamp = myDate.getTime();
			$.get('/php/getSongsModerList.php?t=' + timestamp, {}, onAjaxSuccess_sm);
		} else {
			$("#helloWorld").html("Здравствуйте, <a href='#' class='dashed' id='vb_user'>пользователь</a>");
			setVbUserInfo('');
			userNotLoggedId = 1;
		}
	}

	function onAjaxSuccess_sm(xmlData) {
		if ($(xmlData).find("newmsg").text() > 0) {
			newMsg = '<img src="/images/message.png">';
			$("#helloWorld").append(newMsg);
		}
	}
}

function setVbUserInfo(VbUser) {
	$('body').click(function() { 
		$("#lastSongs").hide();
	}); 
	
	$('#lastSongs').click(function(event){ 
		event.stopPropagation(); 
	}); 

	$("#vb_user").click(function(){
		$("#lastSongs").toggle();
		getLastSongList();
		return false;
	});

	if (VbUser == 'VB user') {
		$("#logedVB").html("Здравствуйте, " + $.cookie("userName"));
		$("#nameUser").attr("value", $.cookie("userName")+" (VB user)");
		$("#notLogedVB").hide();
	}

	setSubsribe();
}

function setSubsribe() {
	$('.addSubscribe').click(function(){
		$('#subscribeInfo').toggle();
		return false;
	});

	$("#subscribeMail").example('E-mail');

	var setAttr;

	var ueserId = $.cookie("userID");
	var artistId = $("#idArtist").attr('value');

	if ((ueserId == null) || (ueserId == '') || (ueserId == '-')) {
		$('#subsNonVb').show();
	} else {
		$.post('/php/subscribe.php', {user: ueserId, artist: artistId, action: 'getStatus'}, onAjaxSuccess);
		$('#subsVB').show();
	}
	
	$("#subscribeChbx").change(function(){
		var ueserId = $.cookie("userID");
		var artistId = $("#idArtist").attr('value');
		setAttr = $(this).attr('checked');
		$.post('/php/subscribe.php', {user: ueserId, artist: artistId, setSubsTo: setAttr, action: 'setSubscribe'}, onAjaxSuccessSet);
	});

	var emailRegexp = /^[a-z][\w\.-]*[a-z\d]@([a-z\d][\w-]*[a-z\d]\.)+[a-z]{2,}$/i;

	$("#setSubsNonVB").submit(function(){

		if (emailRegexp.test($("#subscribeMail").attr("value"))) { 
			$("#savedSubs").html("Подписка...");
			var artistId = $("#idArtist").attr('value');
			var ueserId = 0;
			var ueserMail = $("#subscribeMail").attr("value");
			setAttr = 'checked';

			$.post('/php/subscribe.php', {user: ueserId, artist: artistId, setSubsTo: setAttr, mail: ueserMail, action: 'setSubscribe'}, onAjaxSuccessSet);
		} else {
			$("#savedSubs").html("Неверный e-mail");
		}
		return false;
	});

	function onAjaxSuccess(xmlData){
		var subs = $(xmlData).find("subscribe");
		subs = ($(subs).attr('subscribe'));
		if (subs == 'yes') {
			$('#subscribeChbx').attr('checked', 'checked');
		}
	}

	function onAjaxSuccessSet(xmlData) {
		$("#savedSubs").show();
		var subs = $(xmlData).find("subscribe");
		subs = ($(subs).attr('subscribe'));
		if (subs == 'isset') {
			$("#savedSubs").html("Вы уже подписаны на этого исполнителя");
		} else {
			if (setAttr == 'checked') {
				$("#savedSubs").html("Вы подписались на обновления. Спасибо!");
			} else {
				$("#savedSubs").html("Вы отписались от обновлений");
			}
		}
		$("#savedSubs").delay('3000').fadeOut('300');
	}
}

function getLastSongList() {
	if (lastSongs == '') {
		var html = '<strong>Последние прослушанные песни и альбомы</strong><img src="/images/loader.gif" width="16" height="16" alt="" id="lastLoader"/><table><tr><td><div id="lastSongsList"></div></td><td><div id="lastAlbumList"></div></td></tr></table><div class="hidden linkToLastSongs"><a href="/likedSongs" class="likedSongs">Мои любимые песни</a><a href="/lastSongs">Более ранние записи →</a></div>';
		if (userNotLoggedId > 0) {
			html += "<div style='width:380px;'><strong>Информация может быть неточной.</strong> <br/><a href='http://forum.lyrsense.com/register.php'>Зарегистрируйтесь</a> или <a href='http://forum.lyrsense.com/index.php'>войдите</a> на форуме и мы гарантируем точность информации, привязанной к аккаунту на форуме.</div>";
		}
		$("#lastSongs").html(html);
		var myDate = new Date();
		var timestamp = myDate.getTime();
		$.get('/php/getLastSongsList.php?t=' + timestamp, {}, onAjaxSuccess_s);
		$.get('/php/getLastAlbumList.php?t=' + timestamp, {}, onAjaxSuccess_a);
		$.get('/php/getSongsModerList.php?t=' + timestamp, {}, onAjaxSuccess_sm);
	} else {
		$("#lastSongs").show();
	}

	function onAjaxSuccess_s(xmlData) {
		parseLastSongs(xmlData);
	}
	function onAjaxSuccess_a(xmlData) {
		parseLastAlbums(xmlData);
	}
	function onAjaxSuccess_sm(xmlData) {
		var count = $(xmlData).find("count").text();
		var aproovedSongs = $(xmlData).find("aproovedSongs").text();
		if ((count > 0) || (aproovedSongs > 0)) {
			var dopInfo = $("<div></div>").addClass('dopInfo').append('<strong style="padding: 0 0 7px 0;">Мои переводы</strong>');
			if (count > 0) {
				var newMsg = '';
				if ($(xmlData).find("newmsg").text() > 0) {
					newMsg = '<img src="/images/message.png">';
				}
				dopInfo.append('<br/><a href="/myModerate">Переводы на модерации</a> (<strong>' + count + '</strong>) '+newMsg);
			}
			if (aproovedSongs > 0) {
				dopInfo.append('<br/><a href="/myModerate#last">Недавно принятые</a> (<strong>' + aproovedSongs + '</strong>)');
			}
			$("#lastSongs").append(dopInfo);
		}
	}
}

function parseLastSongs(xmlData) {

	var arr_fr_title = $(xmlData).find("fr_title");
	var arr_s_url = $(xmlData).find("s_url");
	var arr_al_id = $(xmlData).find("al_id");
	var arr_picture = $(xmlData).find("picture");
	var arr_ar_url = $(xmlData).find("ar_url");
	var arr_name = $(xmlData).find("name");
	var htmlInsert = '';
	var i = 0;

	if (arr_fr_title.length == 0) {
		$("#lastSongsList").html("<small>Вы пока не проcлушали ни одной песни на сайте</small>");
		$("#lastLoader").hide();
		lastSongs = 'shown';
		return;
	}

	arr_fr_title.each(
		function () {
			var fr_title = $(this).text();
			var s_url = $(arr_s_url[i]).text();
			var al_id = $(arr_al_id[i]).text();
			var picture = $(arr_picture[i]).text();
			var ar_url = $(arr_ar_url[i]).text();
			var name = $(arr_name[i]).text();

			i++;
			
			htmlInsert += '<table class="lastSongsTable"><tr><td><img src="/'+picture+'" width="35" heigh="35" /></td><td><strong><a href="/'+ar_url+'/'+s_url+'">'+fr_title+'</a></strong><br/><a href="/'+ar_url+'" class="smaller">'+name+'</a></td></tr></table>';
			
		}
	);

	if (i == 5) {
		$(".linkToLastSongs").show();
	}

	$("#lastSongsList").html(htmlInsert);
	$("#lastLoader").hide();
	lastSongs = 'shown';
}

function parseLastAlbums(xmlData) {

	var arr_title = $(xmlData).find("title");
	var arr_al_id = $(xmlData).find("al_id");
	var arr_picture = $(xmlData).find("picture");
	var arr_ar_url = $(xmlData).find("ar_url");
	var arr_name = $(xmlData).find("name");
	var htmlInsert_a = '';
	var i = 0;

	if (arr_title.length == 0) {
		$("#lastAlbumList").html("<small>Вы пока не проcлушали ни одного альбома</small>");
		$("#lastLoader").hide();
		lastSongs = 'shown';
		return;
	}

	arr_title.each(
		function () {
			var title = $(this).text();
			var al_id = $(arr_al_id[i]).text();
			var picture = $(arr_picture[i]).text();
			var ar_url = $(arr_ar_url[i]).text();
			var name = $(arr_name[i]).text();

			i++;
			
			htmlInsert_a += '<table class="lastSongsTable"><tr><td><img src="/'+picture+'" width="35" heigh="35" /></td><td><strong><a href="/'+ar_url+'/listen/'+al_id+'">'+title+'</a></strong><br/><a href="/'+ar_url+'" class="smaller">'+name+'</a></td></tr></table>';
		
		}
	);

	if (i == 5) {
		$(".linkToLastSongs").show();
	}

	$("#lastAlbumList").html(htmlInsert_a);
	$("#lastLoader").hide();
	lastSongs = 'shown';
}

function showVar(id, prev) {

	//$("#ru_title_"+prev).hide();
	//$("#ru_text_"+prev).hide();
	$("#author_"+prev).hide();

	//$("#ru_title_"+id).show();
	//$("#ru_text_"+id).show();
	$("#author_"+id).show();

	$("#"+prev).removeClass("selected").addClass("active");
	$("#"+id).addClass("selected").removeClass("active");
	
	$("#prev").attr("value", id);
	checkEditSong(id);

	var idV = $("#add_song_" + id).val();
	if (is_numeric(idV)) {
		$.post('/php/getComments.php', {idVar: idV}, onAjaxSuccess);
	} else {
		var idO =  $("#songId").val();
		$.post('/php/getComments.php', {idOrig: idO}, onAjaxSuccess);
	}

	function onAjaxSuccess(xml) {
		$("#comment").html($(xml).find('comment').text());
		$("#ru_text").html($(xml).find('ru_text').text());
		$("#ru_title").html($(xml).find('ru_title').text());
		setFootNotes(id);
	}	

}

function setRating(){
	var songId = $("#songId").attr("value");

	$.post('/php/makeRatingSong.php', {id: songId}, '');
}

function setFootNotes(id) {

	$("#ru_title sup, #ru_text sup").each(function(){
		var i = $(this).html();
		if ($("#footnote"+i).length) {
			var footnote = $("#footnote"+i).html();
			var leftMargin = ($(this).position().left - $("#ru_text").outerWidth() - 250);
			var htmlNote = "<div class='footnote hidden' id='footnodeText"+i+"' style='margin-left:"+leftMargin+"px;'>"+footnote+"</div>";
			$(this).after(htmlNote);
			$(this).addClass('dashedSup');
			$(this).hover(	function(){ $("#footnodeText"+i).show(); }, 
							function() { $("#footnodeText"+i).hide(); });

		}
	});

}

function setRusCoockie() {
	$.cookie("artistList", "rusList", {
		expires: 30,
		path: "/",
		domain: "lyrsense.com",
		secure: false
	});
}

function setOrigCoockie() {
	$.cookie("artistList", "origList", {
		expires: 30,
		path: "/",
		domain: "lyrsense.com",
		secure: false
	});
}

function showOrig() {
	$.get('/php/getEngArtists.php', {}, onAjaxSuccess);
	function onAjaxSuccess(xml) {
		parseOrigins(xml);
	}	
}

function parseOrigins(xml) {
	var listHtml = $(xml).find('listArtist').text();
	$("#eng_artist").html(listHtml);
	$("#rus_artist").hide();

	var liters = $(xml).find('liters').text();
	$("#eng_liters").html(liters);
	$("#rus_liters").hide();

	$(".showRus").removeClass("notLink");
	$(".showOrigin").addClass("notLink");

	setOrigCoockie();

	$(".showRus").click(function(){
		$("#rus_artist").show();
		$("#eng_artist").hide();

		$("#rus_liters").show();
		$("#eng_liters").hide();

		$(".showRus").addClass("notLink");
		$(".showOrigin").removeClass("notLink");

		setRusCoockie();
	});

	$(".allLiterasDiv").hover(function(){
		$(this).stop().animate({left:0});
	}, function() {
		$(this).stop().animate({left:-37});
	});

	$("a.gotoLitera").click(function () {
		var anc = $(this).attr("href").substring(1);
		$("html:not(:animated)"+( ! $.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop: $("#"+anc).position().top});	
		return false;
	});

	$("a.artistList").click(function(){
		litera = $(this).attr("id");
		if ($(this).hasClass("shown")) {
			//$("#allArtists"+litera).show();
		} else {
			$(this).html("загрузка...");
			$(this).addClass("artistListLoading");
			getAllArtists(litera);			
		}
		return false;
	});
}

function checkBonus(devotionid, bonus) {
	$.get('/php/chBonus.php', {dev : devotionid, cbonus : bonus}, onAjaxSuccess);
	function onAjaxSuccess(xml) {
		parseResponseBonus(xml);
	}
}

function parseResponseBonus(xml) {
	if($(xml).find("type").text() == "noBonus") {
		$("#errorBonus").html("Неверный секретный ключ");
	}

	if($(xml).find("type").text() == "longBonus") {
		$("#bonusInput").empty();
		$("#bonusAccept").html("Бонус принят. Срок этого подарка продлен вдвое.");
	}

	if($(xml).find("type").text() == "freeBonus") {
		$("#bonusInput").empty();
		$("#bonusAccept").html("Бонус принят. Песня подарена. <a href='" + $("#devotedSongLink").attr("href") + "'>Перейти к подаренной песне</a>");
	}

	$("#loadingBonus").hide();
}

function getAllArtists(id) {
	$.get('/php/getAllArtists.php', {litera : id}, onAjaxSuccess);
	function onAjaxSuccess(xml) {
		parseAllArtists(xml);
	}	
}

function parseAllArtists(xml){
	var list = $("#list_"+litera);
	var link = $("#"+litera);

	list.empty();

	var names = $(xml).find("name");
	var urls = $(xml).find("url");
	var hiddens = $(xml).find("hidden");
	var i = 0;
	var new_ul = "<ul id='list_"+litera+"'>"; 

	names.each(
		function () {
			var name = $(this).text();
			var url = $(urls[i]).text();
			var hidden = $(hiddens[i]).text();
			i++;

			if (hidden == 0) {
				new_ul += '<li><a href="/'+url+'">'+name+'</a></li>';
			} else {
				new_ul += '<li class="newHidden hidden'+litera+'" ><a href="/'+url+'">'+name+'</a></li>';
			}
		}
	);

	new_ul += "</ul>";
	list.replaceWith(new_ul);

//	$(".hidden"+litera).show("100");
	link.addClass("shown");
}

function setOperators() {
	var list = $("#operators");
	list.empty();

	var country = $("#country").attr("value");

	$.get('/tarifs.xml', {}, onAjaxSuccess);	
	function onAjaxSuccess(xml) {
		country = $(xml).find(country);

		var operators = $(country).find("operators");
		
		var titles = $(operators).find("title");
		var values = $(operators).find("value");
		var i = 0;

		titles.each(
			function () {
				var title = $(this).text();
				var value = $(values[i]).text();
				i++;

				$("<option></option>")
					.attr("value", value)
					.html(title)
					.appendTo(list);
			}
		);

		var shortNum = $(country).find("shortNum").text();
		$(".shortNum").html(shortNum);

		var roughly = $(country).find("roughly").text();
		$("#value").html(roughly);
	}

	if ((country == "ukrain") || (country == "kazahstan")) {
		$("#nds").html("с учётом НДС");
	} else {
		$("#nds").html("без учёта НДС");
	}

	if (country == "ukrain") {
		$("#ukrSpecial").html("<br/>Дополнительно удерживается сбор в Пенсионный фонд в размере 7,5% от стоимости услуги без учета НДС.");
		$("#operators").hide();
		$("#ukrSpecialOperator").html("Услуга действительна для всех Национальных GSM операторов Украины");
	} else {
		$("#ukrSpecial").html("");
		$("#operators").show();
		$("#ukrSpecialOperator").html("");
	}
}

function checkArtist() {
	var artist = $("#artist").val();

	if (artist != undefined) {
		if (sentArtist != artist) {
			if (artist.length > 3) {
				var sentArtist = artist;
				getAlbums(artist);
			}
		}
	}
}

function setFields() {
	if ($("#selectAlbum").val() == "addAlbum") {
		$("#newAlbum").show();
	} else {
		$("#newAlbum").hide();
		$("#ruArtistTr").hide();
	}
}

function setTr() {
	if ($("#reason").val() == "foundError") {
		$("#erBlock").show();
	} else {
		$("#erBlock").hide();
	}
	
	if ($("#reason").val() == "addBoigraphy") {
		$("#addBoigraphy").show();
		$("#message").attr("rows", "23");
		$("#addBioHit").show();
	} else {
		$("#addBoigraphy").hide();
		$("#message").attr("rows", "5");
		$("#addBioHit").hide();
	}	
}

function setTexts() {
	
	if ($("#reason").val() != undefined) {
		if ($("#reason").val() == 'share') {			
			$("#texts").show();
			$(".generalFields").hide();
			$("#simpleMessage").hide();
			$("#author").css({disply:"table-row"});
		} else {
			$("#texts").hide();
			$("#simpleMessage").show();
			$(".generalFields").show();
			$("#author").css({disply:"none"});		
		}
		if ($("#reason").val() == 'lookingfor') {			
			$("#lookingFor").show();
		} else {
			$("#lookingFor").hide();
		}
	}
}

function sendErrorReport() {
	if ($("#message").val() == "") {
		$("#errors").html("&larr; Напишите в чем состоит ошибка на странице");
		$("#sendError").html("Отправить");
		$("#sendError").removeClass("artistListLoading");
	} else {
		$("#errors").html("");
		sendReport();
	}
}

function sendReport() {
	var message = $("#message").val();
	var songId = $("#songId").val();
	var username = $("#name").val();
	var logedName = $("#nameUser").val();
	
	$.post('/php/sendError.php', {msg: message, id: songId, name: username, lName: logedName}, onAjaxSuccess);		
	function onAjaxSuccess(xml) {
		$("#message").val("");
		$(".successSend").html("Спасибо за сообщение об ошибке!").delay('1000').fadeOut();
		$(".sendErrorDiv").hide();
		$(".successSend").show();
		$("#sendError").html("Отправить");
		$("#sendError").removeClass("artistListLoading");
	}	
}

function getAlbums(getByName) {
	$.get('/php/getAlbums.php', {name : getByName}, onAjaxSuccess);
	function onAjaxSuccess(xml) {
		parseAlbums(xml);
	}	
}

function parseAlbums(xml) {
	var list = $("#selectAlbum");
	list.empty();
	if (xml != '')  {
		projects = $("item", xml);
		projects.each(
			function () {	 
				id = $("id", this).text();
				name = $("title", this).text();

				$("<option></option>")
					.attr("value", id)
					.html(name)
					.appendTo(list);				
			});
		$("<option></option>")
			.attr("value", "addAlbum")
			.html("(Указать другой альбом)")
			.appendTo(list);
		list.show();
		setFields();
	} else {
		list.empty();
		list.hide();			
		$("#newAlbum").show();
	}
}
var idAl = 0;
function showSongText(id, newSongs) {
	if (id != 'showmenu') {

		if (idAl == 0) {
			idAl = $("#album_id").attr("value");
			$.post('/php/countAlbumListen.php', {idAlbum : idAl}, onAjaxSuccess);
		}
		
		var currentId = $("#current_song_id").attr("value");
		if (currentId != id) {
			$("#load").show();
			getNewText(id);

			if (newSongs == 'newSongs') {
				getAlbumInfo(id);
			}
		}
	}

	function onAjaxSuccess(xmlData) {
	}	
}

function getAlbumInfo(id_song) {
	$.get('/php/getAlbumInfo.php', {getbysongid: id_song}, onAjaxSuccess);
	function onAjaxSuccess(xmlData) {

		$("#ns_picture").attr("src", $(xmlData).find("picture").text());
		$("#ns_album").html($(xmlData).find("title").text());
		$("#ns_artist").html($(xmlData).find("artist").text());
		$("#ns_album").attr('href', $(xmlData).find("url").text() + '#album_' + $(xmlData).find("al_id").text());
		$("#ns_artist").attr('href', $(xmlData).find("url").text());
	}	
}

var flip = 0;

function getNewText(id) {
	$.post('/php/getSongText.php', {getbyid : id}, onAjaxSuccess);
	function onAjaxSuccess(xmlData) {
		parseNewText(xmlData);
	}
}

function countHitParad(id) {
	$.post('/php/countHitParad.php', {idSong : id}, onAjaxSuccess);
	function onAjaxSuccess(xmlData) {
	}
}

function parseNewText(xmlData) {
	$("#breadcrumbs_song_title").html($(xmlData).find("fr_title").text());
	$("#current_song_id").attr("value", $(xmlData).find("id").text());
	$("#songId").attr("value", $(xmlData).find("id").text());
	$("#foundErrorLink").attr("href", "/feedback?foundError&id=" + $(xmlData).find("id").text());
	$("#fr_title").html($(xmlData).find("fr_title").text());
	$("#ru_title").html($(xmlData).find("ru_title").text());
	$("#fr_text").html($(xmlData).find("fr_text").text());
	$("#ru_text").html($(xmlData).find("ru_text").text());
	$("#author_var1").html($(xmlData).find("author").text());
	$("#comment").html($(xmlData).find("comment").text());

	$("#load").hide();
	if (flip == 0) {
		$("#listenAlbumProfit").html('<img src="/images/coins.png" style="float:left; margin: 5px 10px 5px 0"/><p class="coins">Вы можете бесплатно «заплатить» за прослушивание этого альбома и поддержать этот сайт, посмотрев рекламу. Вопроизведение песен не прервется.<p>');
	}
	flip = 1;

	var artist = $("div.album h4 a").html();

	var videoBar;
	var options = {
		largeResultSet : !true,
		horizontal : true,
		thumbnailSize : GSvideoBar.THUMBNAILS_MEDIUM,
		autoExecuteList : {
			cycleTime : GSvideoBar.CYCLE_TIME_MEDIUM,
			cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
			executeList : ['"' + artist + ' ' + $(xmlData).find("fr_title").text() + '"']
		}
	}

	videoBar = new GSvideoBar(document.getElementById("videoBar-bar"), GSvideoBar.PLAYER_ROOT_FLOATING, options);

	setFootNotes('second');
}

var sentTime = 0;

function trackPlayMp3(title) {
	var myDate = new Date();
	var timestamp = myDate.getTime();
			
	if (title != 'showmenu') {
		if ((sentTitle != title) || ((timestamp - sentTime) > 170000)){
			var idSong = $("#songId").attr("value");
			countHitParad(idSong);
		
		//	pageTracker._trackPageview("/play/" + title);
			sentTitle = title;
			sentTime = timestamp;
	//		alert('sent');
		}
	}

}

function expand() {
	var el = document.getElementById("textsTable");
	var width = el.clientWidth;
	var height = el.clientHeight;
	width = width+220;
	el.style.position = "absolute";
	el.style.left = "50px";
	el.style.width = width+"px";

	var lt = document.getElementById("layoutText");
	lt.style.height = height+"px";

	var ar = document.getElementById("artists");
	ar.style.visibility = "hidden";
	var img = document.getElementById("expandImg");
	img.style.display = "none";
	var img = document.getElementById("compressImg");
	img.style.display = "block";
}

function compress() {
	var el = document.getElementById("textsTable");
	var width = el.clientWidth;
	width = width-220;
	el.style.position = "static";
	el.style.left = "240px";
	el.style.width = width+"px";

	var ar = document.getElementById("artists");
	ar.style.visibility = "visible";
	var img = document.getElementById("expandImg");
	img.style.display = "block";
	var img = document.getElementById("compressImg");
	img.style.display = "none";
}

function replace_string(txt,cut_str,paste_str){
	var f=0;
	var ht='';
	
	ht = ht + txt;
	f=ht.indexOf(cut_str);
	
	while (f!=-1){
		//цикл для вырезания всех имеющихся подстрок
		f=ht.indexOf(cut_str);
		if (f>0){
			ht = ht.substr(0,f) + paste_str + ht.substr(f+cut_str.length);
			};
	};
	return ht;
}

function initTranslate() {
	google.language.getBranding('branding', { type : 'vertical' });
	submitChange();
}

function submitChange() {
	var value = $("#source").val();
	var srcLang = $("#srcLang").val();
	var dstLang = $("#dstLang").val();
	if (value != '') {
		google.language.translate(value, srcLang, dstLang, translateResult);
	}
	return false;
}

function translateResult(result) {
	if (result.translation) {
		var str = result.translation.replace('>', '&gt;').replace('<', '&lt;');
		$("#results").html(str);
		$("#results").show();
	} else {
		$("#results").html('<span style="color:red">Error Translating</span>');
	}
}

function add_favorite(a) {
	var title=document.title;
	var url=document.location;
	try {
	  // Internet Explorer
	  window.external.AddFavorite(url, title);
	}
	catch (e) {
	  try {
	    // Mozilla
	    window.sidebar.addPanel(title, url, "");
	  }
	  catch (e) {
	    // Opera
	    if (typeof(opera)=="object") {
	      a.rel="sidebar";
	      a.title=title;
	      a.url=url;
	      return true;
	    }
	    else {
	      // Unknown
	      alert('Нажмите Ctrl-D чтобы добавить страницу в закладки');
	    }
	  }
	}
	return false;
} 

function is_numeric (mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = "";  /* base-64 pad character. "=" for strict RFC compliance   */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
function hex_hmac_md5(k, d)
  { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_md5(k, d)
  { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_md5(k, d, e)
  { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of a raw string
 */
function rstr_md5(s)
{
  return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}

/*
 * Calculate the HMAC-MD5, of a key and some data (raw strings)
 */
function rstr_hmac_md5(key, data)
{
  var bkey = rstr2binl(key);
  if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
  return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}

/*
 * Convert a raw string to a hex string
 */
function rstr2hex(input)
{
  try { hexcase } catch(e) { hexcase=0; }
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var output = "";
  var x;
  for(var i = 0; i < input.length; i++)
  {
    x = input.charCodeAt(i);
    output += hex_tab.charAt((x >>> 4) & 0x0F)
           +  hex_tab.charAt( x        & 0x0F);
  }
  return output;
}

/*
 * Convert a raw string to a base-64 string
 */
function rstr2b64(input)
{
  try { b64pad } catch(e) { b64pad=''; }
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var output = "";
  var len = input.length;
  for(var i = 0; i < len; i += 3)
  {
    var triplet = (input.charCodeAt(i) << 16)
                | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
                | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > input.length * 8) output += b64pad;
      else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
    }
  }
  return output;
}



/*
 * Convert a raw string to an arbitrary string encoding
 */
function rstr2any(input, encoding)
{
  var divisor = encoding.length;
  var i, j, q, x, quotient;

  /* Convert to an array of 16-bit big-endian values, forming the dividend */
  var dividend = Array(Math.ceil(input.length / 2));
  for(i = 0; i < dividend.length; i++)
  {
    dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
  }

  /*
   * Repeatedly perform a long division. The binary array forms the dividend,
   * the length of the encoding is the divisor. Once computed, the quotient
   * forms the dividend for the next step. All remainders are stored for later
   * use.
   */
  var full_length = Math.ceil(input.length * 8 /
                                    (Math.log(encoding.length) / Math.log(2)));
  var remainders = Array(full_length);
  for(j = 0; j < full_length; j++)
  {
    quotient = Array();
    x = 0;
    for(i = 0; i < dividend.length; i++)
    {
      x = (x << 16) + dividend[i];
      q = Math.floor(x / divisor);
      x -= q * divisor;
      if(quotient.length > 0 || q > 0)
        quotient[quotient.length] = q;
    }
    remainders[j] = x;
    dividend = quotient;
  }

  /* Convert the remainders to the output string */
  var output = "";
  for(i = remainders.length - 1; i >= 0; i--)
    output += encoding.charAt(remainders[i]);

  return output;
}

/*
 * Encode a string as utf-8.
 * For efficiency, this assumes the input is valid utf-16.
 */
function str2rstr_utf8(input)
{
  var output = "";
  var i = -1;
  var x, y;

  while(++i < input.length)
  {
    /* Decode utf-16 surrogate pairs */
    x = input.charCodeAt(i);
    y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
    if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
    {
      x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
      i++;
    }

    /* Encode output as utf-8 */
    if(x <= 0x7F)
      output += String.fromCharCode(x);
    else if(x <= 0x7FF)
      output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0xFFFF)
      output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0x1FFFFF)
      output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                                    0x80 | ((x >>> 12) & 0x3F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
  }
  return output;
}

/*
 * Encode a string as utf-16
 */
function str2rstr_utf16le(input)
{
  var output = "";
  for(var i = 0; i < input.length; i++)
    output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
                                  (input.charCodeAt(i) >>> 8) & 0xFF);
  return output;
}

function str2rstr_utf16be(input)
{
  var output = "";
  for(var i = 0; i < input.length; i++)
    output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                                   input.charCodeAt(i)        & 0xFF);
  return output;
}

/*
 * Convert a raw string to an array of little-endian words
 * Characters >255 have their high-byte silently ignored.
 */
function rstr2binl(input)
{
  var output = Array(input.length >> 2);
  for(var i = 0; i < output.length; i++)
    output[i] = 0;
  for(var i = 0; i < input.length * 8; i += 8)
    output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
  return output;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2rstr(input)
{
  var output = "";
  for(var i = 0; i < input.length * 32; i += 8)
    output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
  return output;
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length.
 */
function binl_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

