var popupStatus = 0;

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupAddVideo").fadeOut("slow");
		popupStatus = 0;
	}
}

$(document).ready(function(){
	$("#add_video").click(function(){
		
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupHeight = $("#popupAddVideo").height();
		var popupWidth = $("#popupAddVideo").width();

		//centering
		$("#popupAddVideo").css({
			"position": "fixed",
			"top": windowHeight/2-popupHeight/2,
			"left": windowWidth/2-popupWidth/2
		});
		//only need force for IE6
		
		$("#backgroundPopup").css({
			"height": windowHeight
		});
		
		//loads popup only if it is disabled
		if(popupStatus==0){
			$("#backgroundPopup").css({
				"opacity": "0.7"
			});
			$("#backgroundPopup").fadeIn("slow");
			$("#popupAddVideo").fadeIn("slow");
			popupStatus = 1;
		}
	});
	

	$("#saveVideo").click(function(){
		var video_url = $("#video_url").val();
		var video_code;
		var video_type = $('input[name=video_type]:checked').val();
		var song_id = $("#song_id").val();
		if (video_code = video_url.match(/youtube\.com\/watch\?v=([^&]+)/)) {
			video_code = video_code[1];
		} else {
			alert('Not valid YouTube address!');
			return;
		}
		var ajaxOpts = {  
		  type: "POST",  
		  url: "/index.php?page=Song&action=saveVideo",  
		  data: "&code=" + video_code + "&provider=youtube&type=" + video_type  + "&song_id=" + song_id,  
		  success: function(data) {  
			alert('Your video have been successfully submitted for moderation!');
			disablePopup();
		  }
		};  
		                    
		$.ajax(ajaxOpts);  
	});
	
	$("#popupAddVideoClose").click(function(){
		disablePopup();
	});

	$("#backgroundPopup").click(function(){
		disablePopup();
	});

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

});