if(window.addEventListener){
	window.addEventListener( "load", init, false );
	window.addEventListener( "unload", end, false );
} else {
	window.attachEvent( "onload", init );
	window.attachEvent( "onunload", end );
}

function end()
{
	clearTimeout(thumbMovieTimeout);
}
function init()
{
	initContentActions();
	initComments();
	initAvatars();
	initHome();
	initThumbMovies();
	initAddPlaylist();
	initImageList();
}

function initThumbMovies()
{
	var arr = document.getElementsByTagName("a");
	for (i = 0; i < arr.length; i++) {
		if (arr[i].className.toLowerCase() == "thumb-movie")
		{
			arr[i].onmouseover = function()
			{
				startThumbMovie(this);
			}
			arr[i].onmouseout = function()
			{
				clearTimeout(thumbMovieTimeout);
				thumbMovieImg.style.top="0px";
			}
		}
	}
}

var thumbMovieImg, thumbMovieTimeout, thumbMovieFrames;
function startThumbMovie(obj)
{
	var childs = obj.childNodes;
	for (i = 0; i < childs.length; i++) {
		if ((childs[i].tagName != undefined) && (childs[i].tagName.toLowerCase() == "img"))
		{
			thumbMovieImg = childs[i];
			thumbMovieImg.style.top="0px";
			playThumbMovie();
			thumbMovieFrames = ((thumbMovieImg.height)/75)-1;

			break;
		}
	}
}
function playThumbMovie()
{
	var frame = -1*(parseInt(thumbMovieImg.style.top)/74);
	frame++;
	if (frame > thumbMovieFrames) frame = 1;
	thumbMovieImg.style.top = "-"+(frame*74)+"px";
	thumbMovieTimeout = setTimeout("playThumbMovie()",300);
}

function initContentActions()
{
	if ((document.getElementById("get_code") != undefined)&&(document.getElementById("get_code") != null)) 
	{
		document.getElementById("get_code").onclick=function()
		{
			toggleActionsPanel("code_field");			
			return false;
		}
		var getCodeCloser = document.createElement("a");
		getCodeCloser.onclick=function() 
		{
			contentActionsClose();
			return false;
		};
		getCodeCloser.href="#";
		getCodeCloser.innerHTML="Затвори";
		getCodeCloser.className="closeButton";
		document.getElementById("code_field").insertBefore(getCodeCloser, document.getElementById("code_field").firstChild);
		document.getElementById("code_field").style.display="none";
		
		setInnerCode( {} );
		
	}

	if ((document.getElementById("social_field") != undefined)&&(document.getElementById("social_field") != null)) {
		document.getElementById("social").onclick=function(){
			toggleActionsPanel("social_field");
			return false;
		}
		var getSocialCloser = document.createElement("a");
		getSocialCloser.onclick=function() {
			contentActionsClose();
			return false;
		};
		getSocialCloser.href="#";
		getSocialCloser.innerHTML="Затвори";
		getSocialCloser.className="closeButton";
		document.getElementById("social_field").insertBefore(getSocialCloser, document.getElementById("social_field").firstChild);
		document.getElementById("social_field").style.display="none";
	}

	if (document.getElementById("add-fav") != undefined) {
	
		document.getElementById("add-fav").onclick=function(){
			addToFavorites( "add-fav" );
			return false;
		}
	
	}

	if (document.getElementById("playlist-add") != undefined) {
		document.getElementById("playlist-add").onclick=function(){
			togglePlaylistPanel("playlist-add-field");
			initAddPlaylist( "save" );
			return false;
		}
		var emailPlaylistAddCloser = document.createElement("a");
		emailPlaylistAddCloser.onclick=function() {
			playlistActionsClose();
			return false;
		};
		emailPlaylistAddCloser.href="#";
		emailPlaylistAddCloser.innerHTML="Затвори";
		emailPlaylistAddCloser.className="closeButton";
		document.getElementById("playlist-add-field").insertBefore(emailPlaylistAddCloser, document.getElementById("playlist-add-field").firstChild);


		document.getElementById("playlist-add-field").style.display="none";
		document.getElementById("add-fav-field").style.display="none";
		document.getElementById("decription_actions").style.height="0px";

	}

}
function toggleActionsPanel(divId)
{
	if( document.getElementById("playlist-add-field") ){
		document.getElementById("playlist-add-field").style.display="none";
	}	
	if( document.getElementById("add-fav-field") ){
		document.getElementById("add-fav-field").style.display="none";
	}
	var divDisplay = document.getElementById(divId).style.display.toLowerCase();
	if (divDisplay == "none")
	{
		document.getElementById("code_field").style.display="none";
		//document.getElementById("send_field").style.display="none";
		if ((document.getElementById("social_field") != undefined)&&(document.getElementById("social_field") != null))
			document.getElementById("social_field").style.display="none";

	        if ((document.getElementById("add-fav-field") != undefined)&&(document.getElementById("add-fav-field") != null))
			document.getElementById("add-fav-field").style.display="none";			
			
		if ((document.getElementById(divId) != undefined)&&(document.getElementById(divId) != null))
			document.getElementById(divId).style.display="block";
		contentActionsOpen();
	} else {
		document.getElementById(divId).style.display = "none";
		contentActionsClose();
	}
}

function togglePlaylistPanel(divId)
{
	var divDisplay = document.getElementById(divId).style.display.toLowerCase();
	if (divDisplay == "none")
	{
		playlistActionsOpen();
	} else {
		playlistActionsClose();
	}
}

var contentActionsMaxHeight = 100;
var contentActionsMinHeight = 0;
var contentActionsIncrease = true;
var animateTimeout;
function contentActionsOpen()
{
	//document.getElementById("playlist-add-field").style.display="none";
	document.getElementById("decription_actions").style.height = "100px";
	return
	clearTimeout(animateTimeout);
	contentActionsIncrease = true;
	contentActionsAnimate();
}
function contentActionsClose()
{
	document.getElementById("decription_actions").style.height = "0px";
	return
	clearTimeout(animateTimeout);
	contentActionsIncrease = false;
	contentActionsAnimate();
}
function contentActionsAnimate() //increase - true or false
{
	var heightNow = parseInt(document.getElementById("decription_actions").style.height);
	var step;
	if (contentActionsIncrease) step = Math.floor((contentActionsMaxHeight - heightNow)/2);
		else step = Math.floor((contentActionsMinHeight - heightNow)/2);

	if (step != 0)
	{
		document.getElementById("decription_actions").style.height = (heightNow + step) + "px";
		animateTimeout = setTimeout("contentActionsAnimate();", 50);
	} else if (!contentActionsIncrease) {
		document.getElementById("code_field").style.display="none";
		//document.getElementById("send_field").style.display="none";
		document.getElementById("social_field").style.display="none";
	}

}

var playlistActionsIncrease;
function playlistActionsOpen()
{
		document.getElementById("playlist-add-field").style.display="block";

//	clearTimeout(animateTimeout);
//	playlistActionsIncrease = true;
//	playlistActionsAnimate();
}
function playlistActionsClose()
{
		document.getElementById("playlist-add-field").style.display="none";
//	clearTimeout(animateTimeout);
//	playlistActionsIncrease = false;
//	playlistActionsAnimate();
}
function playlistActionsAnimate() //increase - true or false
{
	var heightNow = parseInt(document.getElementById("playlist-add-field").style.height);
	var step;
	if (playlistActionsIncrease) step = Math.floor((contentActionsMaxHeight - heightNow)/2);
		else step = Math.floor((contentActionsMinHeight - heightNow)/2);

	if (step != 0)
	{
		document.getElementById("playlist-add-field").style.height = (heightNow + step) + "px";
		animateTimeout = setTimeout("playlistActionsAnimate();", 50);
	} else if (!playlistActionsIncrease) {
		document.getElementById("playlist-add-field").style.display="none";
	}
}


var commentsFormOpener;
var commentsFormIncreace = true;
var commentsFormMaxHeight = 240;
var commentsFormMinHeight = 0;
function initComments()
{
	if (document.getElementById("add_comment_form") == undefined) return;

	if (!document.getElementById("add_comment_form") ) return;

	commentsFormOpener = document.createElement("a");
	commentsFormOpener.onclick=function() {
		toggleCommentForm();
		return false;
	};
	commentsFormOpener.href="#";
	commentsFormOpener.innerHTML="Добави твой коментар";
	document.getElementById("comments_title").appendChild(commentsFormOpener);

	var commentsFormCloser = document.createElement("a");
	commentsFormCloser.onclick=function() {
		addCommentFormClose();
		return false;
	};
	commentsFormCloser.href="#";
	commentsFormCloser.innerHTML="Затвори";
	commentsFormCloser.className="closeButton";
	document.getElementById("add_comment_form").insertBefore(commentsFormCloser, document.getElementById("add_comment_form").firstChild);

	document.getElementById("add_comment_form").style.height="0px";
}
function toggleCommentForm()
{
	if (commentsFormIncreace)
	{
		addCommentFormOpen();
	} else {
		addCommentFormClose();
		commentsFormIncreace = false;
	}
}
function addCommentFormOpen()
{
        if( !commentsFormOpener )
	{
		return;
	}
	//commentsFormOpener.innerHTML="Скрий добавянето на коментар";
	clearTimeout(animateTimeout);
	commentsFormIncreace = true;
	addCommentFormAnimate();
}
function addCommentFormClose()
{

        if( !commentsFormOpener )
	{
		return;
	}
	commentsFormOpener.innerHTML="Добави твой коментар";
	clearTimeout(animateTimeout);
	commentsFormIncreace = false;
	addCommentFormAnimate();
}
function addCommentFormAnimate()
{
	if( !document.getElementById("add_comment_form") )
	{
	    return false;
	}

	var heightNow = parseInt(document.getElementById("add_comment_form").style.height);
	var step;
	if (commentsFormIncreace) step = Math.floor((commentsFormMaxHeight - heightNow)/2);
		else step = Math.floor((commentsFormMinHeight - heightNow)/2);

	if (step != 0)
	{
		document.getElementById("add_comment_form").style.height = (heightNow + step) + "px";
		animateTimeout = setTimeout("addCommentFormAnimate();", 50);
	}
	else if (heightNow == 0) commentsFormIncreace = true;
	else if (heightNow == 199) commentsFormIncreace = false;
}

var newFileName;
function initAvatars()
{
	if (document.getElementById("avatar_accordion") == undefined) return;

	$("#avatar_accordion").accordion({ header: "h4", active: false, alwaysOpen: false });

	$("#avatar_accordion li a img").click(function() {
		$("img.selected_avatar").removeClass("selected_avatar");
		document.getElementById("selectedAvatar").src = $(this).attr('src');
		document.getElementById("srcAvatar").src = $(this).attr('src');
		document.getElementById("resultAvatar").src = $(this).attr('src');
		document.getElementById("user_avatar").value = $(this).attr('src');
		$(this).addClass("selected_avatar");
	});

	$('#uploadAvatarDialog').dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		buttons: {
			"Изрежи": function() {
				var x1 = $('#x1').val();
				var y1 = $('#y1').val();
				var x2 = $('#x2').val();
				var y2 = $('#y2').val();
				var w = $('#w').val();
				var h = $('#h').val();
				if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
					alert("Трябва първо да селектирате част от голямата снимка, като кликнете върху нея и влачите с мишката.");
					return false;
				}
				var thumbFileName = String((new Date()).getTime()).replace(/\D/gi,'') + ".jpg";
				$.ajax({
					type: "POST",
					cache: false,
					url: "Avatars/upload/resize.php",
					data: "x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2+"&w="+w+"&h="+h+"&fname="+newFileName+"&thname="+thumbFileName,
					success: function(msg){
						$('#uploadAvatarDialog').dialog("close");
						document.getElementById("selectedAvatar").src = "Avatars/upload/files/"+thumbFileName;
						document.getElementById("user_avatar").value = "Avatars/upload/files/"+thumbFileName;
					}
				});


			},
			"Отказ": function() {
				$(this).dialog("close");
			}
		}
	});

	new Ajax_upload('#avatarUploadLink', {
		action: 'Avatars/upload/upload.php',
		name: 'userfile',
		onSubmit : function(file , ext){
			//if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
			//if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
			if (ext && /^(jpg|jpeg)$/.test(ext)){

				newFileName = String((new Date()).getTime()).replace(/\D/gi,'') + "." + ext;
				this.set_data({
					'newFilename': newFileName
				});
			} else {
				$('#avatarUploadP .uploadText').text('Разрешени са само .jpg(.jpeg) файлове.');
				return false;
			}

		},
		onComplete : function(file){
			document.getElementById("cropAvatar").src = "Avatars/upload/files/"+newFileName;
			document.getElementById("resultAvatar").src = "Avatars/upload/files/"+newFileName;
			$('#uploadAvatarDialog').dialog('open');
			$('#cropAvatar').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview, parent: ".ui-dialog" });
			$('.ui-dialog').css({top: '100px'});
		}
	});

}

function preview(img, selection) {
	var scaleX = 50 / selection.width;
	var scaleY = 50 / selection.height;

	$('#resultAvatar').css({
		width: Math.round(scaleX * 500) + 'px',
		height: Math.round(scaleY * 450) + 'px',
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
	});
	$('#x1').val(selection.x1);
	$('#y1').val(selection.y1);
	$('#x2').val(selection.x2);
	$('#y2').val(selection.y2);
	$('#w').val(selection.width);
	$('#h').val(selection.height);
}

function initHome()
{
	if (document.getElementById("home-top") == undefined) return;

	$('#select-menu-list').jScrollPane({scrollbarWidth: 15, arrowSize: 16});


	var nomeContent = readCookie("home-content");

	if (nomeContent == 1) {
		$("#h2-content .open").css({display:"none"});
		$("#content").css({display:"block"});
	} else {
		$("#h2-content .close").css({display:"none"});
	}
	$("#h2-content").css({visibility:"visible"});

}
function openContent()
{
	$("#h2-content .close").css({display:"block"});
	$("#h2-content .open").css({display:"none"});
	$("#content").css({display:"block"});
	createCookie("home-content",1,365);
}
function closeContent()
{
	$("#h2-content .open").css({display:"block"});
	$("#h2-content .close").css({display:"none"});
	$("#content").css({display:"none"});
	createCookie("home-content",0,365);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; 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);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
