var inprocess;

function kill_remove_rows(row)
{
	$('#tr'+row+' td').css('text-decoration', 'line-through');
	$('#tr'+row).fadeOut('slow', function(){
		$(this).remove();
		rowscount = count_videos_rows();
		if (rowscount == 0)
		{
			$('#no_video_message').show();
		}
		return true;
	});
}

function start_reordering_channel()
{
	$('a.reorder_link').click(function() {
		get_channel_videos();
		return false;
	});
}


var deleted = 0;
function delete_video(sig, row)
{
	if (confirm(JST_MEMBER_DELETE_VIDEO) == true)
	{
		var qs = new Querystring();
		$.ajax({
			type: "GET",
			url: "/api_server/",
			data: 'action=delete_video&sig='+sig+'&orderby='+qs.get('orderby')+'&next='+qs.get('next')+'&way='+qs.get('way')+'&max_per_page='+max_per_page,
			dataType: "json",
			success: function(msg) {

				if (msg['return_code'] == 1)
				{
					$('#tr'+row+' td').css('text-decoration', 'line-through');
					$('#tr'+row).fadeOut('slow', function(){
						$(this).remove();

						/* If new line coming */
						if (msg['additional_params']['new_line'] == true)
						{
							var newline = $('#tr_default').clone();
							$(newline).attr('id', 'tr'+row);
							$(newline).appendTo('#videoslist');

							$('#tr'+row+' .span_modify_details a').attr('href', '/videos/?action=edit_video_details&sig='+msg['additional_params']['results'][0]['sig']);
							$('#tr'+row+' .span_modify_kad a').attr('href', '/videos/?action=edit_kad_details&sig='+msg['additional_params']['results'][0]['sig']);

							if (msg['additional_params']['results'][0]['kad_id'] > 0)
							{
								$('#tr'+row+' .span_modify_kad a img').attr('src', '/img/default/notext/member-modify-kad-ok.gif');
							}

							$('#tr'+row+' .span_date').text(msg['additional_params']['results'][0]['creation_date']);
							$('#tr'+row+' .span_time').text(msg['additional_params']['results'][0]['creation_time']);
							$('#tr'+row+' .span_thumb a').attr('href', msg['additional_params']['results'][0]['video_link']);
							$('#tr'+row+' .span_thumb img').attr('src', msg['additional_params']['results'][0]['thumb_url']);
							$('#tr'+row+' .span_title a').text(msg['additional_params']['results'][0]['title']);
							$('#tr'+row+' .span_title a').attr('href', msg['additional_params']['results'][0]['video_link']);
							$('#tr'+row+' .span_status').text(msg['additional_params']['results'][0]['status']);
							$('#tr'+row+' .span_view').text(msg['additional_params']['results'][0]['counter']);
							$('#tr'+row+' .span_delete').click(
								function()
								{
									delete_video(msg['additional_params']['results'][0]['sig'], row);
								});

							$('#tr'+row).show();

							$('.pagination').html(msg['additional_params']['pagination'][0]+' - '+msg['additional_params']['pagination'][1]+' - '+msg['additional_params']['pagination'][2]);

							nb_next = Math.ceil(msg['additional_params']['total_results']/max_per_page);
						}
						else
						{
							nb_next = 1;
						}


						rowscount = count_videos_rows();
						if (rowscount == 0)
						{
							$('.pagination').hide();
							if ($('.pagination a').length == 0)
							{
								$('#no_video_message').show();
							}
							else
							{
								$.blockUI('<h2 style="font-size: 16px; z-index: 3000 !important;"><img src="/img/default/notext/uploading.gif" />&nbsp;&nbsp;'+JST_MEMBER_WAIT+'</h2>');
								window.location.href = '/videos/?orderby='+qs.get('orderby')+'&next='+(qs.get('next')-1)+'&way='+qs.get('way');
							}
						}
						return true;
					});
				}
				else
				{
					alert(JST_AJAX_ERROR);
				}
			}
		});
	}
	else return false;
}

function delete_favorite(sig, row)
{
	$.ajax({
		type: "GET",
		url: "/api_server/",
		data: "action=delete_favorite&sig="+sig,
		success: function(msg) {
			if(msg == 1)
			{
				$('#tr'+row+' td').css('text-decoration', 'line-through');
				$('#tr'+row).fadeOut('slow', function(){
					$(this).remove();
					rowscount = count_videos_rows();
					if (rowscount == 0)
					{
						$('#no_video_message').show();
					}
					return true;
				});
			}
			else
			{
				alert(JST_AJAX_ERROR);
			}
		}
	});
}

function delete_from_channel(sig, csig, row)
{
	$.ajax({
		type: "GET",
		url: "/api_server/",
		data: "action=delete_from_channel&sig="+sig+"&csig="+csig,
		success: function(msg) {
			if(msg == 1)
			{
				$('#tr'+row+' td').css('text-decoration', 'line-through');
				$('#tr'+row).fadeOut('slow', function(){
					$(this).remove();
					rowscount = count_videos_rows();
					if (rowscount == 0)
					{
						$('#no_video_message').show();
						$('.play_channel_enabled').remove();
						$('.play_channel_disabled').css('display', 'inline');

					}
					if (rowscount <= 1)
					{
						$('.reorder_channel_enabled').remove();
						$('.reorder_channel_disabled').css('display', 'inline');
					}
				});
			}
			else
			{
				alert(JST_AJAX_ERROR);
			}
		}
	});
}

function stripSlashes(s)
{
	s = s.replace(/\\'/g,'\'');
	s = s.replace(/\\"/g,'"');
	s = s.replace(/\\\\/g,'\\');
	s = s.replace(/\\0/g,'\0');
	return s;
}

function rename_channel()
{
	var csig = channel_sig;
	var old_cname = stripSlashes(channel_name);

	var new_cname = window.prompt(JST_MEMBER_ENTER_CHANNEL_NEW_NAME+old_cname, old_cname);
	if (new_cname == null) return;
	var valid_new_cname = js_is_valid_channel_name(new_cname);

	if (valid_new_cname == true)
	{
		$.ajax({
			type: "GET",
			url: "/api_server/",
			data: "action=rename_channel&csig="+csig+"&channel_name=" + escape(new_cname),
			success: function(msg) {
				if(msg == 1)
				{
					$('#i'+csig+' a').text(new_cname);
					channel_name = new_cname;
				}
				else if(msg == -2005)
				{
					window.alert(JST_MEMBER_ERROR_CHANNEL_ALREADY_EXISTS);
					rename_channel();
				}
				else
				{
					//document.location.href = '/videos/?action=rename_channel&csig='+csig+'&channel_name='+new_cname;
					alert(JST_AJAX_ERROR+' ['+msg+']');
				}
			}
		});
	}
	else
	{
		alert(JST_MEMBER_CHANNEL_NAME_INVALID);
	}
}


function count_videos_rows()
{
	return ($('#videoslist tr').length -1);
}

function delete_channel()
{
	var csig = channel_sig;
	var cname = channel_name;
	var answer = confirm(JST_MEMBER_DELETE_CHANNEL+' "'+cname+'"?');

	if (answer == true)
	{
		//delete_channel
		//call a new php page
		document.location.href = "/videos/?action=delete_channel&csig="+csig;
	}
}

function js_is_valid_channel_name(cname)
{
	//if (length(cname) > 3 and length(cname) < 255)) return true;
	//else return false;
	var reg = new RegExp("^[a-zâàáâãäåòóôõöøèéêëçìíîïùúûüÿñ\'\"]{1}[a-z0-9âàáâãäåòóôõöøèéêëçìíîïùúûüÿñß#\'\" _-]{2,30}$", "gi");

	if(cname.match(reg)) return true;
	else return false;
}

function addNewItem(source_link, menu_id, completeCallback)
{
	$(source_link).hide();
	$('#m'+menu_id+' ul').append('<li id="new_item_li"><input id="new_item_field" type="text" id="js_new_channel" value="'+JST_MEMBER_CHANNEL_NAME+'" maxlength="30" flexy:ignore />&nbsp;<img id="new_item_apply" src="/img/default/notext/apply.gif" />&nbsp;<img id="new_item_cancel" src="/img/default/notext/cancel.gif" /></li>');

	$('#new_item_field').focus();
	$('#new_item_field').select();

	$('#new_item_field').keydown( function(evt) {
		keyWasHit(evt, source_link, menu_id)
	});

	$('#new_item_apply').click( function() {
		completeItem(source_link, menu_id);
	});

	$('#new_item_cancel').click( function() {
		cancelItem(source_link, menu_id);
	});

	return false;
}



function cancelItem(source_link, menu_id)
{
	$('#new_item_li').remove();
	$(source_link).show();
	$('#new_item_field').unbind();
	$('#new_item_apply').unbind();
	$('#new_item_cancel').unbind();
}

function keyWasHit(pEvent, source_link, menu_id)
{
	if(pEvent.keyCode == 13)
	{
		completeItem(source_link, menu_id)
	}
	else if (pEvent.keyCode == 27) cancelItem(source_link, menu_id);
}

function completeItem(source_link, menu_id)
{
	var fieldvalue = stripSlashes($('#new_item_field').val());
	$('#new_item_field').blur();

	if (js_is_valid_channel_name(fieldvalue))
	{
		$.ajax({
			type: "GET",
			url: "/api_server/",
			data: "action=create_channel&channel_name="+escape(fieldvalue),
			success: function(msg) {
				if(msg == -7002)
				{
					window.alert(JST_MEMBER_ERROR_CHANNEL_ALREADY_EXISTS);
				}
				else if(msg == -7000)
				{
					window.alert(JST_MEMBER_ERROR_CHANNEL_CHECK_NAME);
				}
				else if(msg < 0 || (msg >= 7003 && msg <= 7005))
				{
					window.alert(JST_MEMBER_ERROR_CHANNEL_NOT_CREATED+" ["+msg+"]");
				}
				else
				{
					document.location.href = '/videos/?action=display_channel&csig='+msg;
				}
			}
		});
	}
	else
	{
		window.alert(JST_MEMBER_CHANNEL_NAME_INVALID);
	}
}



function click_update_password(state)
{
	if (state == true) {
		document.getElementById('tr_passwd1').style.visibility = 'visible';
		document.getElementById('tr_passwd2').style.visibility = 'visible';
	}
	else {
		document.getElementById('tr_passwd1').style.visibility = 'hidden';
		document.getElementById('tr_passwd2').style.visibility = 'hidden';
	}
}

/* Experimental */
var current_channel_id;
var current_channel_name;

function startContext(object)
{
	current_channel_id = object.id;
	current_channel_name = object.text;

	document.getElementById('playlist_context_menu').style.top = object.offsetTop+17+'px';
	document.getElementById('playlist_context_menu').style.left = object.offsetLeft+'px';
	document.getElementById('playlist_context_menu').style.display = 'block';
}

function hideContext()
{
	document.getElementById('playlist_context_menu').style.display = 'none';
}

function send_message()
{
	receiver_username = $('#receiver_username').val();
	sender_id = $('#sender_id').val();
	message_subject = encodeURIComponent($('#message_subject').val());
	message_body = encodeURIComponent($('#message_body').val());
	message_attached_id = $('#message_attached_id').val();
	$.ajax({
		type: "POST",
		url: "/api_server/",
		data: "action=write_message&sender_id="+sender_id+"&receiver_username="+receiver_username+"&message_subject="+message_subject+"&message_body="+message_body+"&message_attached_id="+message_attached_id,
		success: function(msg) {
			if (msg == 1)
			{
				window.location = '?action=read_message&new=1';
				//window.location.reload();
				return true;
			}
			else if (msg == -1)
			{
				$('#error_message').html(JST_USER_UNKNOWN);
				$('#error_message').fadeIn("slow");
			}
			else
			{
				$('#error_message').html(JST_MESSAGE_NOT_SENDED);
				$('#error_message').fadeIn("slow");
			}
		}
	});
	return false;
}

function save_channel_order()
{
	$('div#thumbnails_list').hide();
	var serial = $.SortSerialize('thumbnails_img');

	$.ajax({
		type: "POST",
		url: "/api_server/",
		data: "action=reorder_channel&channel_sig="+channel_sig+'&'+serial.hash,
		success: function(msg) {
			if (msg == 1)
			{
			    var url = window.location.toString();
				var anchor = url.indexOf('#');
				if (anchor != -1)
				{
					url = url.substr(0, anchor);
				}
				window.location = url;
			}
			else
			{
				$('div#thumbnails_list').show();
				window.alert(JST_CANNOT_REORDER);
			}
		}
	});
	return false;
}


function cancel_channel_reorder()
{
	$('div.header_pub').css('visibility', 'visible');
	$('div#partner_header').css('visibility', 'visible');
	$('div#thumbnails_list').hide();
	$('div#transparent_layer').hide();
	return false;
}

function get_channel_videos()
{

	/* Displaying waiting message during AJAX queries */
	/*$().ajaxStop($.unblockUI);
	$().ajaxStart(function() {
		$.blockUI('<h2 style="font-size: 16px; z-index: 3000 !important;"><img src="/img/default/notext/uploading.gif" />&nbsp;&nbsp;'+JST_MEMBER_WAIT+'</h2>');
	});*/

	$('a#cancel_reordering').click(cancel_channel_reorder);

	/* When window is resized */
	$(window).resize(function() {
		$('div#transparent_layer').css({height:$(document).height(), width: $(document).width(), opacity:'0.8', filter: 'alpha(opacity = 80)'});
	});

	/* Displaying the form */
	$('div.header_pub').css('visibility', 'hidden');
	$('div#partner_header').css('visibility', 'hidden');
	$('div#hdrbanner').css('visibility', 'hidden');

	window.scrollTo(0,0);

    $('div#transparent_layer').show();
	$('div#transparent_layer').css({height:$(document).height(), width: $(document).width(), opacity:'0.8', filter: 'alpha(opacity = 80)'});
	$('a#save_link').css('color', '#CCC');
	$('a#save_link').unbind();

	$('.sortableitem').remove();

	$.ajax({
		type: "POST",
		url: "/api_server/",
		data: "action=get_all_channel_videos&channel_sig="+channel_sig,
		dataType: "json",
		success: function(videos_list) {

				for(i = 0; videos_list[i]; i++)
				{
					thumb = new Image();
					thumb.src = videos_list[i]['thumb_url'];
					video_position = i + 1;
					var element = $('<img>').attr('id', videos_list[i]['sig'] + '.' + videos_list[i]['added_on']).attr('height', '114').attr('width', '154').attr('src', thumb.src).attr('className', 'sortableitem').attr('title', "#"+video_position+": "+videos_list[i]['title']).attr('alt', "#"+video_position+": "+videos_list[i]['title']);
					$(element).appendTo("#thumbnails_img");
				}

				$('div#thumbnails_list').show();

				$('div#thumbnails_img').Sortable(
				{
						accept : 		'sortableitem',
						helperclass : 	'sorthelper',
						activeclass : 	'sortableactive',
						hoverclass : 	'sortablehover',
						opacity: 		0.8,
						/*revert:			true,*/
						floats:			true,
						tolerance:		'pointer',
						onChange : function()
						{
							var j = 1;
							$('img.sortableitem').each(function()
							{
								var old_title = $(this).attr('title');
								var reg = new RegExp("^#[0-9]{1,}", "g");
								var new_title = old_title.replace(reg, "#"+j);
								$(this).attr('title', new_title);
								$(this).attr('alt', new_title);
								j ++;
							});

							/* When action is saved */
							$('a#save_link').click(save_channel_order);
							$('a#save_link').css('color', '#76B102');

						},
						onStart : function()
						{
							$.iAutoscroller.start(this, document.getElementsByTagName('body'));
						},
						onStop : function()
						{
							$.iAutoscroller.stop();
						}
				});
		}
	});

	return false;

}

function remove_transparent_layer()
{
	$.blockUI.impl.remove(document);
}

function delete_account_confirm()
{
		var a;

		for (var i=0; i<document.reason.reason_account_deleted.length; i++)
		{
			if (document.reason.reason_account_deleted[i].checked == true)
			{
				a = document.reason.reason_account_deleted[i].value;
			}
	    }
		if(!a)
		{
			$("#check_radio").fadeIn(300); return false;
		}
		else
		    return true;
 	}


$(document).ready(function(){
	if ($(window).height() > $(document).height())
		docheight = $(window).height()
	else
		docheight = $(document).height()
		
 	if ($(window).width() > $(document).width())
		docwidth = $(window).width()
	else
		docwidth = $(document).width()

 	$(".desactivate_vb").click(function()
	{
		window.scrollTo(0,0);
		$('#opt_transparent_layer').show();
		$('#opt_transparent_layer').css({height: docheight, width: docwidth, opacity:'0.8', filter: 'alpha(opacity = 80) progid:DXImageTransform.Microsoft.Alpha(opacity=80)'});
	    $("#desactivate_vb").fadeIn(800);

		return false;
	});
	
	$(window).resize(function()
	{
		$('#opt_transparent_layer').css({height: docheight, width: docwidth, opacity:'0.8', filter: 'alpha(opacity = 80) progid:DXImageTransform.Microsoft.Alpha(opacity=80)'});
	});
	
	$(".desactivate_vb_cancel").click(function()
	{
    	$("#desactivate_vb").fadeOut(300);
		$('#opt_transparent_layer').hide(function(){
		});
	});

	$(".delete_account").click(function()
	{
		window.scrollTo(0,0);
		$('#opt_transparent_layer').show();
		$('#opt_transparent_layer').css({height: docheight, width: docwidth, opacity:'0.8', filter: 'alpha(opacity = 80) progid:DXImageTransform.Microsoft.Alpha(opacity=80)'});
    	$("#delete_account").fadeIn(800);

		return false;
	});

	$(".delete_account_cancel").click(function()
	{
	    $("#delete_account").fadeOut(300);
	    $("#check_radio").hide();
		$('#opt_transparent_layer').hide(function()
		{
		});
	});

	$(".activate_vb").click(function()
	{
		window.scrollTo(0,0);
		$('#opt_transparent_layer').show();
		$('#opt_transparent_layer').css({height: docheight, width: docwidth, opacity:'0.8', filter: 'alpha(opacity = 80) progid:DXImageTransform.Microsoft.Alpha(opacity=50)'});
    	$("#activate_vb").fadeIn(800);

		return false;
	});
	
	$(".activate_vb_cancel").click(function()
	{
    	$("#activate_vb").fadeOut(300);
		$('#opt_transparent_layer').hide(function()
		{
		});
	});

	// Enable tooltip for top proposal links
	top_proposal_links();
});