

function showSettings()
{

	var checkedString = '';
	if(settings['autosave'] && settings['autosave'] == 'true')
		checkedString = ' checked="checked"';
	
	var element = "<table id='settings_table' width='100%' height='100%'><tr><td class='mask'>";
	element += "<center><div id='settings_box'>";
	element += "<table>";
	element += "<tr><td class='settings-label settings-banner'><img src='./images/settings-128.png' /></td><td class='settings-banner'>Settings</td></tr>";
	element += "<tr><td class='settings-label'>AutoLogin URL<div class='settings-label-info'>(You should keep this URL hidden, to avoid not allowed people to connect)</div></td><td class='settings-value'><input type='text' class='settings-field settings-field-big settings-autologin-url' value='Please Wait...' /><input type='button' class='settings-button' id='settings-al-link' value='Go!' /></td></tr>";
	element += "<tr><td class='settings-label'>Theme<div class='settings-label-info'>(CTRL + T)<div class='settings-label-info'></div></td><td class='settings-value'><input type='text' class='settings-field' id='settings-theme-name' disabled='disabled' value='"+settings['theme']+"' /><input type='button' class='settings-button' id='settings-theme-change' value='Click here to change theme!' /></td></tr>";
	element += "<tr><td class='settings-label'>Auto-Save<div class='settings-label-info'>(Be careful! If you activate this option, the system will save your wall after any change)<div class='settings-label-info'></div></td><td class='settings-value'><input type='checkbox' class='settings-checkbox' id='settings-autosave'"+checkedString+"'/></td></tr>";
	element += "</table><div id='settings_submit'></div><div id='settings_cancel'></div></div></center>";
	element += "</td></tr></table>";
	
	$('body').append(element);
	
	setAlString();
	
	$('#settings_table').keyup(function(e) {
		if(e.keyCode == 13) {
			$(this).remove();
		}
	});
	$('#settings-autosave').bind("click", function(e) {
		if($('#settings-autosave').attr('checked'))
			settings['autosave'] = 'true';
		else
			settings['autosave'] = 'false';
	});
	
	$('#settings_submit').bind("click", function(e){
		
		$('#settings_table').remove();
		save();
	});
	$('#settings_cancel').bind("click", function(e){
		$('#settings_table').remove();
	});
	$('#settings-theme-change').bind("click", function(e){
		changeTheme();
		$('#settings-theme-name').val(settings['theme']);
	});
	
}

function showMessage(text, what)
{
	if(what == 0)
		$("#message").css("background-color", "red");
	else
		$("#message").css("background-color", "green");
	
	$("#message").text(text);
	$("#message").css("position","absolute");
	
	$("#message").slideDown("slow");
	
	window.setTimeout("hideMessage()", 5000);

}

function hideMessage()
{
	$("#message").slideUp("slow", function() { $(this).css("display","hidden"); });
}



function changeTheme(theme)
{
	if(!theme)
	{
		
		for(var i=0; i<themes.length; i++)
		{
			if(themes[i] == settings['theme'])
			{
				actualIndex = i;
			}
		}
		if(actualIndex == themes.length-1 || typeof(actualIndex) == undefined)
			newIndex = 0;
		else
			newIndex = actualIndex+1;
		theme = themes[newIndex];
		
	}
	
	document.getElementById('theme').href = './Themes/'+theme+'/style.css';
	
	if(theme != settings['theme']) {
		//change(true);
	}
	else {
		//change(false);
	}
	settings['theme'] = theme;
}
	
function create(id, x, y, width, height, title, content, fadeIn, saveAfter)
{
	if(arguments.length == 0)
	{
		var id = getRandomId();
		var x = ($(window).width()/2)-100;
		var y = ($(window).height()/2)-100;
		var width = 200;
		var height = 200;
		var title = "New Post-it";
		var content = "";
		var fadeIn = true;
		
		if(settings['autosave'] && settings['autosave'] == 'true') saveAfter = true;
	}
	
	var element = "";
	element += "<div class='postit' id='"+id+"' style='left:"+x+"; top:"+y+";'>";
	element += "<div class='drag' id='"+id+"_drag'></div>";
	element += "<input type='text' class='title' value='"+title+"'>";
	element += "<textarea class='content'>"+br2nl(content)+"</textarea></div>";
	$('body').append(element);
	
	$("#"+id).draggable(
	{
		containment	: $('body'),
		opacity		: 0.5,
		handle		: $('#'+id+'_drag'),
		scroll: false,
		stack: { group: '.postit', min: 1 },
		start: function(event, ui) {
			deactivateFields();
			dragging_element = "#"+id;
		},
		stop: function(event, ui) { 
			if(to_delete_element != "")
			{
				$(this).addClass('removing');
				
				$(this).hide("explode", 1000, function() {
					$(this).remove();
					if(settings['autosave'] && settings['autosave'] == 'true') save();
					else change(true);
				}); 
				/*
				$(this).hide("explode", 1000, function() {
					$(this).remove();
					$(this).removeClass('postit');
					if(settings['autosave']) save();
					else change(true);
				});*/ 
			}
			else
			{
				if(settings['autosave'] && settings['autosave'] == 'true') save();
				else change(true);
			}
			to_delete_element = "";
			dragging_element = "";

			
		}
	});
	
	$("#"+id+"_drag").bind("mousedown", function(e){
		
		select("#"+id+"_drag");
		
	});
	
	$("#"+id+"_drag").bind("dblclick", function(e){
		editing = $(this).parent().attr('id');
		
		$("#"+id).addClass("editing");
		$("#"+id).removeClass("unselectable");
		
		$(this).css("display", "none");
		if(e.originalEvent.layerY && e.originalEvent.layerY>30)
		{
			$("#"+id+" .content").focus();
		}
		else
		{
			$("#"+id+" .title").focus()
		}

	
			if(!settings['autosave'] || settings['autosave'] == 'false') change(true);
	});
	
		
			
	$("#"+id).resizable({
		ghost		: true,
		minHeight	: 50,
		minWidth	: 50,
		stop: function(event, ui)
		{
			
			var width = ui.size.width;
			var height = ui.size.height - 30;
			
			$(this).find(".title").width(width);
			
			$(this).find(".content").width(width);
			$(this).find(".content").height(height);
			

			if(settings['autosave'] && settings['autosave'] == 'true') save();
			else change(true);
		}
	});
	
	$("#"+id).find(".title").width(width);
	
	$("#"+id).find(".content").width(width);
	$("#"+id).find(".content").height(height-30);

	$("#"+id).width(width);
	$("#"+id).height(height);
	if(fadeIn == true || typeof( window[ 'foo' ] ) == "undefined"){
		$("#"+id).fadeTo(1,0, function() { $(this).css("display","inline"); });
		$("#"+id).fadeTo(300, 1, function() {
			if(saveAfter && saveAfter == true && settings['autosave'] && settings['autosave'] == 'true') save();
			if(saveAfter && saveAfter == true && (!settings['autosave'] || settings['autosave'] == 'false')) change(true);
		});
	}
	
}



function save() 
{
	setLoading(1);
	var json_string = '{';
	$(".postit").each(function(){
		
		if(!$(this).hasClass('removing'))
		{
			var id = $(this)[0].id;
			var left = $(this).position().left;
			left = (100*left)/$(window).width();
			
			var top = $(this).position().top;
			top = (100*top)/$(window).height();
			
			var width = $(this).css("width").substr(0, $(this).css("width").length-2);
			var height = $(this).css("height").substr(0, $(this).css("height").length-2);
			var title = $(this).find(".title").val();
			var content = nl2br($(this).find(".content").val());
			json_string += '"'+id+'":"'+left+'#%#'+top+'#%#'+width+'#%#'+height+'#%#'+title+'#%#'+content+'",';
		}
	});

	if(json_string.substr(json_string.length-1) == ",")
		json_string = json_string.substr(0,json_string.length-1);

	// SETTINGS STRING
	var settingsstring = settings['theme']+'#%#'+settings['autosave'];
	
	
	json_string += '}';
	
	 $.ajax({
	   type: "POST",
	   url: "./php/service.php",
	   data: "write=true&data="+json_string+"&settings="+settingsstring,
	   success: function(msg){
	     if(msg != "1")
		     alert(msg);
	     else
		     change(false);
	     setLoading(0);
	   }
	 });
}

function loadSettings()
{
	$.getJSON("./php/service.php?readsettings=true",
	        function(data){
				var dt = data['settings'];
				settings = dt;
				$.getJSON("./php/service.php?getThemes=true",
				        function(data){
							var dt = data['themes'];
							
							for(var theme in dt)
							{
								themes.push(theme);
							}
							if(settings["theme"] && themes.in_array(settings["theme"]))
								changeTheme(settings["theme"]);
							else
								changeTheme(standardTheme);
							
				    	});
	    	});
}

function loadData()
{
	$.getJSON("./php/service.php?readdata=true",
	        function(data){
				if(data != '')
				{
					
					for( var i in data)
					{
						var dt = data[i];
						create(i, dt["x"]+"%", dt["y"]+"%", dt["width"], dt["height"], dt["title"], dt["content"], true);
					}
				}
				
				init();
				setLoading(0);
	    	});
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
