/*****************
 *     USER
 ****************/

function initUser(){
	
	//initMenu();
	
	$('#account').click(function(){
		selectPage('account', account);
		return false;
	});
	
	initConfig();
	
	userName = $('#userName').val();
	userId = $('#userId').val();
	
	initHeader();
}

/*****************
 *   LISTILES
 ****************/

function loadListFiles(){
	var type = $('#filesType').val();
	var flux = $("#flux").val();
	var userId = $("#userAccountId").val();
	
	$.ajax({
		type: 'POST',
		url: 'listUserFilesAjax' + extension,
		data: {'type': type, 'flux': flux, 'userId': userId},
		success: function(msg){
			$('#dataTableWapper').html(msg);
			var title = $(msg).find('#titleFlux').val();
			if (title != undefined)
				$('#title').text(title);
			dTable = $('#files').dataTable({
				"aoColumns": [
	    			{ "sType": 'html' },
	    			{ "sType": 'num-html' },
	    			{ "sType": 'date' },
	    			{ "sType": 'html' }
	    		], "oLanguage": getDatatableLanguage(),
	    		"iDisplayLength": config.tableDisplayResults,
	    		"bSortClasses": false
		  	});
		},
		beforeSend: function(msg){
			if (dTable != undefined && dTable.length)
				dTable.fnDestroy();
			$('#dataTableWapper').empty();
			loadingTimeout = setTimeout("$('#insideLoading').show();", 300);
				
		},
		complete: function(msg){
			clearTimeout(loadingTimeout);
			$('#insideLoading').hide();
			$('#footer').show();
		}
	});
}

/**************
 *  ACCOUNT
 *************/

function account(params){
	
	var flux = null;
	if (params){
		var split = params.split("&");
		for (var i = 0; i < split.length; i++){
			var indexFlux = split[i].indexOf("flux");
			if (indexFlux != -1)
				flux = split[i].substring(5);
		}
	}
	if (flux != null){
		$('#flux').val("uploads");
	}
	
	$('#flux').change(function() {
		loadListFiles();
	});
	
	$('#filesType').change(function() {
		loadListFiles();
	}); 
	
	dTable = $('#files').dataTable({
		"aoColumns": [
  			{ "sType": 'html' },
  			{ "sType": 'time' },
  			{ "sType": 'date' },
  			{ "sType": 'html' }
  		], "oLanguage": getDatatableLanguage(),
  		"iDisplayLength": config.tableDisplayResults,
  		"bSortClasses": false
	});
	
	$('#editAccount').button().click(function (){
		var href = $(this).attr('href');
		
		editAccount(href, function(json){
			$('#account_age').text(json.map['age']);
            $('#account_city').text(json.map['city']);
            $('#account_country').text(json.map['country']);
            $('#account_email').text(json.map['email']);
            $('#account_website').text(json.map['website']);
		});
		return false;
	});	
	
	removeAjaxEvents = function(){
		if (dTable != undefined && dTable.length)
			dTable.fnDestroy();
		$('.file').unbind();
	};
};

/*****************
 *  LIST USERS
 ****************/

function listUsers(){
	
	$('.deleteUser').click(function(){
		// Single Delete
		var id = searchIdFromHref($(this).attr('href'));
		$.ajax({
			   type: "POST",
			   url: 'deleteUserJson' + extension,
			   data: "id=" + id,
			   success: function(json){
				  if (json.code == 0){
					  $('#' + id).html(json.message).css('color', 'red');
					  $('.' + id).each(function(){
						  $(this).html('');
					  });
				  }
				  else {
					  $('#' + id).html(json.message).css('color', 'orange').css('text-decoration', 'blink');
				  }
			   },
			   error : function(msg){
				 alert(msg);
			   }
			 });
		return false;
	}).confirm({
		  msg: getText('Delete') + ' ? ',
		  timeout: 5000,
		  buttons: {
		    ok: getText('Yes'),
		    cancel: getText('No'),
		    separator: ' '
		  }
	});
	
	$('.editUser').click(function (){
		var aPos = dTable.fnGetPosition(($(this).parent())[0]);
		var href = $(this).attr('href');
		
		editAccount(href, function(json){
			dTable.fnUpdate(json.map['name'], aPos[0], 0);
			var id = searchIdFromHref(href);
            $('#' + id).html(json.map['name'] + ' ' + getText("Updated")).css('color', 'red');
		});
		
		return false;
	});	
	
	if ($("#head").children().length == 11){
		dataTableParam = {
			"aoColumns": [
  			{ "sType": 'html' }, // Name
  			{ "sType": 'time' }, // TimeOnline
  			{ "sType": 'date' }, // Register
  			{ "sType": 'numeric' }, // NbDl
  			{ "sType": 'num-html' }, // SizeDl
  			{ "sType": 'numeric' }, // NbUp
			{ "sType": 'num-html' }, // SizeUp
			{ "sType": 'numeric' }, // NbUpLeft
			{ "sType": 'numeric' }, // NbUpLeftAccepted
			{ "sType": 'numeric' }, // NbSizeLeft
  			{ "sType": 'html', "sClass": "center", "bSortable": false} // Edit
  			], "bSortClasses": false,
  			"oLanguage": getDatatableLanguage(),
  			"iDisplayLength": config.tableDisplayResults
  		};
		
//		$('.user').toolTip({
//			ElementClassId: 'user'
//		});
		
	} else {
		dataTableParam = {
  			"aoColumns": [
  			{ "sType": 'html' }, // Name
			{ "sType": 'time' }, // TimeOnline
			{ "sType": 'date' }, // Register
			{ "sType": 'numeric' }, // NbDl
			{ "sType": 'num-html' }, // SizeDl
			{ "sType": 'numeric' }, // NbUp
			{ "sType": 'num-html' }, // SizeUp
  			], "bSortClasses": false,
  			"oLanguage": getDatatableLanguage(),
  			"iDisplayLength": config.tableDisplayResults
  		};
	}
	dTable = $('#users').dataTable(dataTableParam);
	
	removeAjaxEvents = function(){
		if (dTable != undefined && dTable.length)
			dTable.fnDestroy();
		$('#type, #categories, #readyUpload,.user,#selectAll,.deleteMultiUser,.multiDownload,.deleteUser,.editUser').unbind();
	};
};

/************************
 *  LIST CONNECTED USERS
 ***********************/

function connectedUsers(){
	dataTableParam = {
		"aoColumns": [
		{ "sType": 'html' },
		{ "sType": 'num-html' },
		{ "sType": 'numeric' },
		{ "sType": 'numeric' },
		], "bSortClasses": false,
		"oLanguage": getDatatableLanguage(),
		"iDisplayLength": config.tableDisplayResults
	};
	
	dTable = $('#users').dataTable(dataTableParam);
	
	removeAjaxEvents = function(){
		if (dTable != undefined && dTable.length)
			dTable.fnDestroy();
		$('.user').unbind();
	};
}

/*****************
 *    CONFIG
 ****************/

function initConfig(){
	$.ajax({
	   type: "POST",
	   url: "getConfigJson" + extension,
	   success: function(json){
			config = json;
	   }
	});
	buildConfig();
}

function buildConfig(){
	$('#configContainer').buildContainers();
	editConfig();
	$(".makeMeAbutton").button();
	$('#cancelConfig').click( function (){
		unEditConfig();
		$('#configContainer').mb_iconize();
		return false;
	});
	$('#submitConfig').click(function (){
		uploadConfig(function(){
			unEditConfig();
			window.location.reload(true);
		});
	});
	return false;
}

function editConfig(){
	
	$('#toolTipEffect').change(function (){
		config.toolTipEffect = $(this).val();
	});
	
	$('#saveStats').change(function (){
		config.saveStats = $(this).val();
		config.saveStats = $('#saveStats').attr('checked')?true:false;
	});
	
	$('#showLoadTimes').change(function (){
		config.showLoadTimes = $('#showLoadTimes').attr('checked')?true:false;
	});
	
	$('#ajaxMode').change(function (){
		config.ajaxMode = $('#ajaxMode').attr('checked')?true:false;
	});
	
	$('#tableDisplayResults').change(function (){
		config.tableDisplayResults = $(this).val();
	});
}

function unEditConfig(){
	$('#toolTipEffect, #saveStats, #showLoadTimes, #ajaxMode, #tableDisplayResults').unbind();
}

function uploadConfig(callback){
	var configData = "config=" + $.toJSON(config);
	if ($("#userName").val() != ""){
		$.ajax({
			type: "POST",
			dataType: 'json',
			url: serverUrl + "saveConfigAjax" + extension,
			data: configData,
			complete: function(){
				if (callback != undefined)
					callback.call();
			}
		});
	}
}

/*********
 *   MP
 ********/

$('#mp').click(function(){
	selectPage('mp', mp());
});

function mp(){
	removeAjaxEvents = function(){
	};
}

$.tools.dateinput.localize("fr",  {
   months:        'janvier,f&eacute;vrier,mars,avril,mai,juin,juillet,ao&ucirc;t,' +
                   	'septembre,octobre,novembre,d&eacute;cembre',
   shortMonths:   'jan,f&eacute;v,mar,avr,mai,jun,jul,ao&ucirc;,sep,oct,nov,d&eacute;c',
   days:          'dimanche,lundi,mardi,mercredi,jeudi,vendredi,samedi',
   shortDays:     'dim,lun,mar,mer,jeu,ven,sam'
});

/*********************/

function editAccount(href, callback){
	var id = searchIdFromHref(href);
	var containerId = createMbContainer('#editUserMain', "editUser", id);
	
	$(containerId).mb_open(href, function(){
		$(".makeMeAbutton").button();
		$(".birthday").dateinput({
			format: 'dddd dd, mmmm yyyy',
			selectors: true,
			offset: [0, 0],
			speed: 'fast',
			firstDay: 1,
			yearRange: [-100, 1],
			lang: $('#language').val()
		});
		$('#submitUser' + id).click( function (){
			$('#updateUserAjax' + id).ajaxSubmit({
				success: function(json) {
					if (json.code != 0){
						$.jGrowl('',{
							theme: 	'error',
							header: json.message,
							life:	5000,
							sticky: false
						});
					} else {
						$.jGrowl('',{
							theme: 	'success',
							header: json.message,
							life:	5000,
							sticky: false
						});
			            $(containerId).mb_close();
			            if (callback != undefined){
			            	callback(json);
			            }
			            if (id == $('#userId').val() && json.list != undefined && json.list[0] != undefined)
			            	$('#adult').val(json.list[0]);
					}
			    },
			    error: function(res) {
		            $(containerId).mb_close();
		            $.jGrowl('',{
						theme: 	'error',
						header: getText('Error'),
						life:	5000,
						sticky: false
					});
			    }
			});
			return false;
		});
		$('#cancelUser' + id).click( function (){
			$(containerId).mb_close();
			return false;
		});
	});
	$(containerId).css('top', (getScrollPosition()[1] + 100) + 'px');
}
