
var user = {};

$(document).ready(function(){	
	$.ajax({
		url: "app/model/CreateEditUser.php",
		success: function(result) {
			var data = ui.ParseJSON(result);
			if(data.Status == undefined || data.Status != "Success"){
				ui.Callout(data);
				return;
			}
			user.Load(data);
		}
	});
});

user.GetModal = function(post_data , callback){
	$.ajax({
		url: "app/model/CreateEditUser.php",
		type : 'POST',
		data : post_data,
		success: function(result) {
			callback(result);
		}
	});
}

user.Load = function(data){

	if( parseInt( ui.data.user.isAdmin ) == 0 ){
		user.NotAdmin();
	} else if(ui.GetCookie("last_cp_action") == '_EDIT_USER') {
		user.DisplayUser(ui.data.user);
	}
	$("#userForm").show();

	if (ui.data.ss == false && ui.data.hl == true) {
		// we have classic license, don't show anything here
	} else if (ui.data.ss.type=="server") {
		// server pro license, don;t show here
	} else {
		$(".license_info").show();
	}	

	// update the license info if the user has any
	if (ui.data.ss.type == "user") {
		ui.ProLicenseInfo();
	}

	$(".profiles-box .search").autocomplete({ source: data.availableTags, minLength : 0 }).bind('click', function(){ $(this).autocomplete("search"); } );
	$(".profiles-box .search").on("autocompleteclose", function(){
		$(".profiles-box .search").val('');
	});

	$(".profiles-box .search").on("autocompleteselect", function(e, obj){
		var v = obj.item.value;
		if(v == ""){
			return;
		}

		data.availableTags.splice(data.availableTags.indexOf(v),1);
	   	// Re-assign the source
	   	$(this).autocomplete("option","source", data.availableTags );
	   	
	   	user.AddProfile(v);
	});

	$(".profiles-list").on("click", ".users-profile i", function(){
		var item = $(this).parent("li");
		var p = item.find("span").html();

		data.availableTags.push(p);
	   	// Re-assign the source
	   	$(".profiles-box .search").autocomplete("option","source", data.availableTags );

		item.remove();
	});

	$(".form-group").on("mouseover", function(e) {	
		var txt = $(this).attr("data-help");
		var title = $(this).find("label:first").html();
		user.UpdateHelp(title,txt);
	});

	$(".profiles-box ul").on("click", function(){
		$(".profiles-box .search").focus();
	});

	$(".checkbox").on("mouseover", function(e) {
		var txt = $(this).attr("data-help");
		var title = $(this).find("label:first").clone(true);
		title.find("input").remove();
		title = title.html();

		user.UpdateHelp(title,txt);

	});

	$('input[name="isAdmin"]').on("click", function(){
		if($(this).is(":checked")){
			user.isAdmin('enable');
		} else {
			user.isAdmin('disable');
		}
	});
	$('input[name="canViewAllProfiles"]').on("click", function(){
		if($(this).is(":checked")){
			user.DisableProfiles();		
		} else {
			user.EnableProfiles();
		}
	});


   	$('input[name="expires"]').inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
   	$('input[name="created"]').inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});

	$(".save-user").on("click", function(e){
			e.preventDefault();
			
			$("html, body").animate({ scrollTop: 0 }, "fast");

			var data = FormObjectToArray( $("#userForm") );
			if(user.checkForm(data)){
				user.SaveUser(data);
			}
	});

	//get a width for the helptxt div and set it. then change it to a fixed position
	w = $(".helptxt").width();
	$(".helptxt").css("position","fixed");
	$(".helptxt").width(w);
}

user.checkForm = function(data){
	$(".form-group").removeClass("has-error");
	var error = 0;

	if( data.username == "" ){
		error ++;
		$('#userForm input[name="username"]').parents(".form-group").first().addClass("has-error");		
	}

	var regex= /[^0-9A-Za-z@.\-.]/;	
	if (regex.test(data.username) == true) {
		error ++;
		$('#userForm input[name="username"]').parents(".form-group").first().addClass("has-error");			
	}

	// only check password with new users 
	if( data.userid == ""){

		if( data.password == "" || !checkPassword(data.password) ){
			error ++;
			$('#userForm input[name="password"]').parents(".form-group").first().addClass("has-error");		
		}		
	} else {
		if( data.password != "" && !checkPassword(data.password) ){
			error ++;
			$('#userForm input[name="password"]').parents(".form-group").first().addClass("has-error");		
		}
	}

	if(data.email == "" || !ValidateEmail(data.email)){
		error ++;
		$('#userForm input[name="email"]').parents(".form-group").first().addClass("has-error");
	}

	if(error > 0){
		return false;
	}
	return true;
}

user.EnableProfiles = function(){
	$('.profiles-list .search').removeAttr("disabled", "disabled").attr("placeholder", ui.data.languages["_TYPE_TO_ADD_PROFILE"]);
}

user.DisableProfiles = function(){	
	$('.profiles-list .users-profile').remove();
	$('.profiles-list .search').attr("disabled", "disabled").attr("placeholder", ui.data.languages["_CAN_VIEW_ALL_PROFILES"]);
}

user.AddProfile = function(name){
	$(".profiles-box .profiles-list").append("<li class='users-profile bg-success'><span class='name'>"+ name +"</span><i class='fa fa-times'></i></li>");
	$(".profiles-box .profiles-list").append( $(".profiles-box .input") );
	$(".profiles-box .input .search").focus();
}

user.SaveUser = function(data){

	data.action = "saveuser";

	data.profiles = [];
	$(".users-profile").each( function(){
		data.profiles.push( $(this).find(".name").html() );
	});

	user.GetModal(data, function(result){
		var r = ui.ParseJSON(result);
		ui.Callout( r );

		if(r.Status != undefined && r.Status == "Success"){
			if(r.userid != undefined){
				$('input[name="userid"]').attr("value", r.userid);
				$("#userSettings .box-title").html( ui.data.languages['_EDIT_USER'] );
			}
		}

	});
}

user.isAdmin = function(state){
	var fields = [
		"accessAddProfile",
		"accessEditProfile",
		"accessUpdateLogs",
		"changeAccountInfo",
		"canViewAllProfiles",
		"trackermode_0",
		"trackermode_1",
		"trackermode_2",
		"trackermode_3"
	];
	if(state == 'enable'){
		$('input[name="isAdmin"]').attr("checked", true );

		$.each(fields, function(k,v){
			$('input[name="'+ v +'"]').prop('checked', true).attr("disabled", "disabled" );
		});
		user.DisableProfiles();

	} else if(state == 'disable'){
		$.each(fields, function(k,v){
			$('input[name="'+ v +'"]').removeAttr("disabled").removeAttr("checked");
		});
		user.EnableProfiles();
	}
}

user.DisplayUser = function(data){
	$("#userSettings .box-title").html( ui.data.languages['_EDIT_USER'] );
	
	$('input[name="userid"]').val(data.userid);
	$('input[name="username"]').val(data.username);
	$('input[name="name"]').val(data.name);
	$('input[name="email"]').val(data.email);

	$('input[name="created"]').parents(".form-group").first().show();


	if(parseInt(data.active) === 1){
		$('select[name="active"] option[value="1"]').attr("selected", "selected" );
	}

	if(parseInt(data.subscriptionid) != null){
		$('select[name="userSubscription"] option[value="'+ data.subscriptionid +'"]').attr("selected", "selected" );
	}


	if(data.profiles != null && data.profiles != "" ){
		var profiles = data.profiles.split(",");
		$.each(profiles, function(k,v){
			user.AddProfile(v);
		});
	}

	if(parseInt(data.created) > 0){
		var d = new Date( parseInt(data.created * 1000) );
		var n = (d.getMonth() + 1) +"/"+ d.getDate() + "/" + d.getFullYear();
		$('input[name="created"]').attr("value", n );
	}

	if(parseInt(data.expires) > 0){
		var d = new Date( parseInt(data.expires * 1000) );
		var n = d.getMonth() +"/"+ d.getDay() + "/" + d.getFullYear();
		$('input[name="expires"]').attr("value", n );		
	}

	var metadata = {};
	
	if(data.metadata != undefined){
		metadata = data.metadata;
	}

	if(parseInt(data.isAdmin) === 1){
		user.isAdmin('enable');
	} else {
		if(parseInt(data.accessAddProfile) === 1){
			$('input[name="accessAddProfile"]').attr("checked", "checked" );
		}
		if(parseInt(data.accessEditProfile) === 1){
			$('input[name="accessEditProfile"]').attr("checked", "checked" );
		}
		if(parseInt(metadata.accessBasicEditProfile) === 1){
			$('input[name="accessBasicEditProfile"]').attr("checked", "checked" );
		}
		if(parseInt(data.accessUpdateLogs) === 1){
			$('input[name="accessUpdateLogs"]').attr("checked", "checked" );
		}
		if(metadata.changeAccountInfo != undefined && parseInt(metadata.changeAccountInfo) === 1){
			$('input[name="changeAccountInfo"]').attr("checked", "checked" );
		}

		if(metadata.trackermode_0 != undefined && parseInt(metadata.trackermode_0) === 1){
			$('input[name="trackermode_0"]').attr("checked", "checked" );
		}
		if(metadata.trackermode_1 != undefined && parseInt(metadata.trackermode_1) === 1){
			$('input[name="trackermode_1"]').attr("checked", "checked" );
		}
		if(metadata.trackermode_2 != undefined && parseInt(metadata.trackermode_2) === 1){
			$('input[name="trackermode_2"]').attr("checked", "checked" );
		}
		if(metadata.trackermode_3 != undefined && parseInt(metadata.trackermode_3) === 1){
			$('input[name="trackermode_3"]').attr("checked", "checked" );
		}

	}

	if(metadata.profileLimit != undefined){
		$('input[name="profileLimit"]').attr("value", metadata.profileLimit );
	}
}


user.UpdateHelp = function(title,txt) {

	if (txt==undefined) {
		txt =  ui.data.languages['_MOVE_YOUR_MOUSE_FOR_HELP'];
		title = ui.data.languages['_HELP'];
	}
	if (title == $(".helptxt .box-title span").html()) {
		return;
	}	

	$(".helptxt .box-body").fadeOut(100, function(){
		$(".helptxt .box-title span").html(title);
		$(".helptxt .box-body").html(txt);
		$(".helptxt .box-body").fadeIn();
	});
}


user.NotAdmin = function(){
	$("#userSettings .box-title").html( ui.data.languages['_EDIT_USER'] );
	var remove = [
		,"[name='active']"
		,"[name='created']"
		,"[name='expires']"
		,"[name='profileLimit']"
		,".profiles-list"
		,".permissions-box"
		,".permissions-box"
	];

	$.each(remove , function(k,v){
		$(v).parents(".form-group").first().remove();
	});


	$("[name='username']").attr( "disabled","disabled" );
	$("[name='userid']").val( ui.data.user.userid );
	$("[name='username']").val( ui.data.user.username );
	$("[name='email']").val( ui.data.user.email );
	$("[name='name']").val( ui.data.user.name );
	$("[name='userSubscription']").val( ui.data.user.subscriptionid );
}

