var mailDialogCreated = false;
var statuteDialogCreated = false;


$(document).ready(function(){
	
	$.ajaxSetup({
	  dataType: 'json'
	});
	$('#tab_option').hover(function(){
		$('#user_menu_tab').slideDown('fast');
	},function(){
		//$('#user_menu_tab').slideUp('fast');
		$('#user_menu_tab').hide();
	});
});	


function photoStatusCheck(status){
	var message = '';
	
	switch (status){
		case 2:
			message = 'Tylko zalogowani użytkownicy mogą oglądać to zdjęcie.';
			break;
		case 3:
			message = 'Wybrany użytkownik zablokował dla ciebie to zdjęcie.';
			break;
		case 4:
			message = 'Musisz być przyjacielem tego użytkownika aby oglądać to zdjęcie.';
			break;
		case 5:
			message = 'Musisz należeć do tej samej grupy aby oglądać to zdjęcie.';
			break;
		case 6:
			message = 'Tylko przyjaciele i członkowie grup mogą oglądać to zdjęcie.';
			break;
			
	}
	return message;
	
}

function movieStatusCheck(status){
	var message = '';
	switch (status){
		case 2:
			message = 'Tylko zalogowani użytkownicy mogą oglądać ten film.';
			break;
		case 3:
			message = 'Wybrany użytkownik zablokował dla ciebie ten film.';
			break;
		case 4:
			message = 'Musisz być przyjacielem tego użytkownika aby oglądać ten film.';
			break;
		case 5:
			message = 'Musisz należeć do tej samej grupy aby oglądać ten film.';
			break;
		case 6:
			message = 'Tylko przyjaciele i członkowie grup mogą oglądać ten film.';
			break;
			
	}
	return message;
}


function read_cookie(nazwa)
  {
   
   nazwa+="="; //uzupełnia nazwę
   var startCookie=document.cookie.indexOf(nazwa); //sprawdza czy istnieje cookie o podanej nazwie
   if (startCookie==-1) {return ""} //jeżeli nie istnieje
   startCookie+=nazwa.length; //początek treści cookie
   var  koniecCookie;
   if (document.cookie.indexOf(";",startCookie)==-1) //jeżeli jest więcej cookie
    {
     koniecCookie=document.cookie.length; //jeżeli nie ma podstawia jako koniec cookie, koniec całego tekstu
    }
   else
    {
     koniecCookie=document.cookie.indexOf(";",startCookie); // podstawia pod koniec miejsce występowania ";" (czyli początek następnego cookie)
    }
  var textCookie=document.cookie.substring(startCookie,koniecCookie); //kopiuje treść cookie
   textCookie=unescape(textCookie); //rozkodowuje treść
  
   //alert(textCookie); //zwraca wartość
   return textCookie;
  //pod zmienna textCookie mamy wartosc naszego cookisa
 }


function sendAjaxForm(form_id){
var data_tab = new Array();
	
	$('#'+form_id+' * input').each(function(){
		
		if ($(this).attr('type') != 'submit' && $(this).attr('type') != 'button' && $(this).val() != null){
			data_tab[$(this).attr('name')] = $(this).val();
		}
	});


	
	var data = '';
	for (var key in data_tab){
		if (typeof(key) == 'string'){
			data+= key+'='+data_tab[key]+'&';
		}
	}	
	//alert(data)
	$.ajax({
		type: "POST",			
		url: 'ajax.php',
		data: data,		   
		dataType: 'json',
		success: function(response){						 
			alert('success');
		},
		error: function(er){
			alert('error');
		}
	});		
}
	
function show_subcategories(submenuid)
{
	$("#"+submenuid).toggle("slow");	   
}

function closeDiv(id){
	$('#'+id).css('display','none');
}

function truncate(string,count){
	if (string.length > count) {
		var zm = string;
		zm = string.substring(0, count);
		zm = zm + '...';
		return zm;
	}
	else {
		return string;
	}
}
	
function loadSubcategories(val){
	//alert($(val).val());
	var id_cat = $(val).val();
	 $.ajax({
	   type: 'GET',
	   url: 'index.php?mod=front&view=newElements&act=getChildCategoriesById',
	   data: 'parent_id='+id_cat,
	   dataType: 'json',
	   success: function(response){
	   	 opcje = '';
		 
		 for (key in response){
		 	opcje += '<option value="'+response[key]['id_category']+'">'+response[key]['name']+'</option>';
		 }		
	     $('#sub_category').html(opcje);
	   }
	 });
	
	
}

function systemMessage(message,type){
	
	
	
		if (type == 'error') {
			var error = computeErrMsg(message);
			//alert(message);
			var dialog = $('<div id="message" title="<span style=\'color:#343434;\'>Wystąpił błąd</span>">').append(error);
		}
		else 
			if (type == 'success') {
				var msg = computeMsg(message);
				var dialog = $('<div id="message" title="<span style=\'color:#343434;\'>Informacja</span>" >').append(msg);
			}
		dialog.dialog({
			autoOpen: true,
			minWidth: 540,
			width: 440,
			minHeight: 90,
			position: 'top',
			closeOnEscape: 'true',
			beforeclose: function(event, ui){
			
			}
			
		});
		dialog.dialog('option', 'hide', 'blind');
		
		setTimeout('hideDialog()', 5000);
		
	
			
			//$('body').append(message);
}

function computeMailForm(message_receiver){
		var msg_box = new Object();
		msg_box = $('<div id="mailFormBox">\
					<form id="mailForm" method="">\
					<div id="hidden_users_list">\
					<input type="hidden" value="'+message_receiver+'" name="takers_login[]"/>\
					</div>\
					<input type="hidden" name="receiver_id" value=""/>\
						<table style="float:left" cellspacing="10" cellpadding="0">\
							<tr>\
								<th><label>Do:</label></th>\
								<td><input id="receiverAuto" type="text" name="" /></td>\
							</tr>\
							<tr>\
								<th><label>Temat:</label></th>\
								<td><input id="subject" type="text" name="message_subject" /></td>\
							</tr>\
							<tr>\
								<th><label>Treść:</label></th>\
								<td><textarea id="content" rows="4" cols="40" name="message_content"></textarea></td>\
							</tr>\
						</table>\
						<div style="height:160px;width:160px;;padding-left:4px;overflow-y:auto"><table class="listUsersTableSend" style="float:right">\
						<tr><td>Wyślij do:<br/>\
						<div  class="clear"></div>\
						<div id="users_list">\
						<span>'+message_receiver+'</span>\
						</div>\
						</td>\
						</tr>\
						</table></div>\
					</form>\
					</div>');	
	return msg_box;	
}
function computeStatuteForm(){
		var msg_box = new Object();
		msg_box = $('<div id="statuteFormBox">\
					<form id="statuteForm" method="">\
					<input type="hidden" name="receiver_id" value=""/>\
						<table cellspacing="10" cellpadding="0">\
							<tr>\
								<th><label>Treść:</label></th>\
								<td><textarea id="contentDerogation" rows="4" cols="40" name=""></textarea></td>\
							</tr>\
						</table>\
					</form>\
					</div>');	
	return msg_box;	
}

function selectItem(){
	
	$('#users_list').append('<span>'+$("#receiverAuto").val()+'</span>');
	$('#hidden_users_list').append('<input type="hidden" name="takers_login[]" value="'+$("#receiverAuto").val()+'"/>');
}
function sendMessageForm(message_receiver){
			
	if (!mailDialogCreated){
			var mailForm = computeMailForm(message_receiver);
			var dialog = $('<div id="mailMessage" title="<span style=\'color:#343434;\'>Wiadomość do użytkownika: '+$('#user-profile-user-name span').text()+'</span>" >').append(mailForm);		
						
			dialog.dialog({
				autoOpen: true,
				width:595,
				minHeight:270,				
				position: 'center',
				closeOnEscape: 'true',
				beforeclose: function(event, ui) { 
					
				},
				buttons: {
				'Wyślij': function() {			
					sendMessage('mailForm');					
				},
				'Anuluj': function() {
					$(this).dialog('close');
					}
				}			
			});	
			
			$("#receiverAuto").autocomplete(
				"autocomplete.php",
				{
					delay:10,
					minChars:3,
					matchSubset:1,
					matchContains:1,
					cacheLength:10,
					maxItemsToShow:10,
					onItemSelect:selectItem,
		//			onFindValue:findValue,
		//			formatItem:formatItem,
					lineSeparator:'|',
					cellSeparator:'&',
					autoFill:false
				}
			);				
			mailDialogCreated = true;
			dialog.dialog('option', 'show', 'blind');
			dialog.dialog('option', 'hide', 'blind');
										
	}
	else{
		$('#mailMessage').dialog('open');		
		
	}

}

function statuteMessageForm(derogation_type,derogation_subject_id){
	var type = 	derogation_type;			
	if (!statuteDialogCreated){
			var statuteForm = computeStatuteForm();
			var dialog = $('<div id="statuteMessage" title="<span style=\'color:#343434;\'>Naruszenie regulaminu przez użytkownika: '+$('#user-profile-user-name span').text()+'</span>" >').append(statuteForm);		
					
			dialog.dialog({
				autoOpen: true,
				width:440,
				minHeight:170,				
				position: 'center',
				closeOnEscape: 'true',
				beforeclose: function(event, ui) { 
					
				},
				buttons: {
				'Wyślij': function() {	
					switch(type){
						// zgłoszenie naruszenia dla profilu
						case '1': 
							sendDerogationProfile('mailForm',this);
						break;
						// zgłoszenie naruszenia dla filmu
						case '2':
							sendDerogationMovie('mailForm',this);
						break;
						case '3':
							sendDerogationPhoto('mailForm',this);
						break;
						case '4':
							sendDerogationText('mailForm',this);
						break;
						default:
							$(this).dialog('close');
						break;
						
					}
										
				},
				'Anuluj': function() {
					$(this).dialog('close');
					}
				}			
			});		
			statuteDialogCreated = true;
			dialog.dialog('option', 'show', 'blind');
			dialog.dialog('option', 'hide', 'blind');
										
	}
	else{
		$('#statuteMessage').dialog('open');		
		
	}

}

function findValue(li) {
	if( li == null ) return alert("No match!");
	
	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];
	
	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;
	
	//alert("The value you selected was: " + sValue);
}



function sendDerogationProfile(mailForm,dialog_box){
	
	$.ajax({
		type: "POST",			
		url: 'sendDerogationProfile.html',
		data: {
			receiver: $('#contentDerogation').val(),
			user_login: $('#user_login').val()
		},		   
		dataType: 'json',
		beforeSend: function(){
						
		},
		success: function(response){	
							 
			$(dialog_box).dialog('close');
			systemMessage('Zgłoszenie zostało przyjęte','success');
			return true;
		},
		error: function(er){

			$('#mailFormBox').prepend('<p>Wystąpił problem podczas wysyłania wiadomości, spróbuj ponownie.</p>');
		}
	});	
}

function sendDerogationMovie(mailForm,dialog_box){
	
	$.ajax({
		type: "POST",			
		url: 'sendDerogationMovie.html',
		data: {
			receiver: $('#contentDerogation').val(),
			movie_id: $('#movie_id').val()
		},		   
		dataType: 'json',
		beforeSend: function(){
						
		},
		success: function(response){	
							 
			$(dialog_box).dialog('close');
			systemMessage('Zgłoszenie zostało przyjęte','success');
			return true;
		},
		error: function(er){

			$('#mailFormBox').prepend('<p>Wystąpił problem podczas wysyłania zgłoszenia, spróbuj ponownie.</p>');
		}
	});	
}

function sendDerogationPhoto(mailForm,dialog_box){
	
	$.ajax({
		type: "POST",			
		url: 'sendDerogationPhoto.html',
		data: {
			receiver: $('#contentDerogation').val(),
			photo_id: $('#photo_id').val()
		},		   
		dataType: 'json',
		beforeSend: function(){
						
		},
		success: function(response){	
							 
			$(dialog_box).dialog('close');
			systemMessage('Zgłoszenie zostało przyjęte','success');
			return true;
		},
		error: function(er){

			$('#mailFormBox').prepend('<p>Wystąpił problem podczas wysyłania zgłoszenia, spróbuj ponownie.</p>');
		}
	});	
}

function sendDerogationText(mailForm,dialog_box){
	
	$.ajax({
		type: "POST",			
		url: 'sendDerogationText.html',
		data: {
			receiver: $('#contentDerogation').val(),
			text_id: $('#text_id').val()
		},		   
		dataType: 'json',
		beforeSend: function(){
						
		},
		success: function(response){	
							 
			$(dialog_box).dialog('close');
			systemMessage('Zgłoszenie zostało przyjęte','success');
			return true;
		},
		error: function(er){

			$('#mailFormBox').prepend('<p>Wystąpił problem podczas wysyłania zgłoszenia, spróbuj ponownie.</p>');
		}
	});	
}


function sendMessage(mailForm){
//	alert($('#'+mailForm+' input#receiver').val()+' .... '+$('#'+mailForm+' input#subject').val()+' ..... '+$('#'+mailForm+' textarea#content').val());
	tab_form = $('#mailForm').serialize();
	$.ajax({
		type: "POST",			
		url: 'sendMultipleMessage.html',
		data: tab_form,		   
		dataType: 'json',
		beforeSend: function(){
						
		},
		success: function(response){	
							 
			if(response == 'OK')
			{
				systemMessage('Wiadomość została wysłana','success');
				$('#mailMessage').dialog('destroy');
				return false;				
			}
			else
			{
				systemMessage('Wystąpił problem podczas wysyłania wiadomości, spróbuj ponownie.','error');
				$('#mailMessage').dialog('destroy');
				return false;					
			}

		},
		error: function(er){
			systemMessage('Wystąpił problem podczas wysyłania wiadomości, spróbuj ponownie.','error');
			$('#mailMessage').dialog('destroy');
			return false;	
		}
	});	
}



function hideDialog(){
	if ($('#message').dialog('isOpen')){
		$('#message').dialog('close');
	}
	
}


function validateInt(iString) {
return (("" + parseInt(iString)) == iString);
}