// required scripts:
// jquery-1.5.min.js
// ckeditor.js
// ckeditor/adapters/jquery.js


// -------------------------------
// adjust variables HERE:

var ff_language = "de";
var ff_ckelements_data = {
	editKeyword: "edit",
	language: ff_language,
	currentHTML: "",
	currentDivID: "",
	currentEditorIndex: 0,
	sessionID: "",
	loginScriptURL: "/scripts/login.php5",
	logOutScriptURL: "/scripts/logout.php5",
	saveScriptURL: "/scripts/ajaxsave.php5",
	sidScriptURL: "/scripts/getSessionID.php5",
	requiredscripts:["/styles/cupertino/jquery-ui-1.8.10.custom.css",
					 "/styles/ckelements.css",
					 "/js/jquery-1.5.min.js",
					 "/js/jquery-ui-1.8.10.custom.min.js",
					 "/js/ckeditor/ckeditor.js",
					 "/js/ckeditor/adapters/jquery.js",
					 "/js/ckelements/lang/" + ff_language + ".js"
					]
};
							
// ------------------------------- // adjust variables


// see the end of this script for how the scripts are included
// once all (external javascript and CSS files) is loaded
// the allScriptsLoaded() function is called

function _(s){
	if (typeof(ff_ckelements_data.i18n) != 'undefined' && ff_ckelements_data.i18n[s]) return ff_ckelements_data.i18n[s];
	return s;
}


function allScriptsLoaded(){

	$(document).ready(function(){
		
		var ff_dlog_div;
		
		// -------------------------------
		// create div for login dialog:

		var myFields = document.createElement('fieldset');
		$(myFields).append('<label for="username">' + _("username") + ':</label>')
			.append('<input type="text" name="username" id="ff_username" class="text ui-widget-content ui-corner-all" />')
			.append('<label for="password">' + _("password") + ':</label>')
			.append('<input type="password" name="password" id="ff_password" value="" class="text ui-widget-content ui-corner-all" />')
			.appendTo($("body"));
			
		$(myFields).wrap('<form />');
		$(myFields).parent().wrap('<div id="ff_ckelements_LoginDialogDiv" title="Login" class="ff_ckelements_Dialog"/>');
		$(myFields).parent().prepend('<p class="ff_validateTips" id="ff_loginResultDisplay">' + _("Enter username to save changes") + '</p>');
			
		$('#ff_ckelements_LoginDialogDiv').dialog(
		{
			modal: true,
			resizable: false,
			draggable: false,
			dialogClass: 'ff_ckelements_Dialog',
			position: ['center','center'],
			width: 350,
			height: 300,
			hide: 'fade',
			show: 'fade',
			closeOnEscape: true,
			autoOpen: false,
			buttons:[
				{
					text: _("Login"),
					click: function(){
						login({username:$("input#ff_username").val(), password:$("input#ff_password").val()});
					}
				}
			]
		});
		// -------------------------------
		
		
		// -------------------------------
		// create div for unsaved changes dialog:
		
		ff_dlog_div = $("<div></div>")
		.attr({
			id: "ff_ckelements_UnsavedChangesDialogDiv",
			title: _("Alert")
			}
		)
		.text(_("There are unsaved changes"))
		.prependTo($("body"));
		
		
		$('#ff_ckelements_UnsavedChangesDialogDiv').dialog(
		{
			modal: true,
			resizable: false,
			draggable: false,
			dialogClass: 'ff_ckelements_Dialog',
			position: ['center','center'],
			width: 300,
			//height: 300,
			hide: 'fade',
			show: 'fade',
			closeOnEscape: true,
			autoOpen: false,
			buttons:[
				{
					text: _("Save"),
					click: function(){
						$(this).dialog("close");
						if (! ff_ckelements_data.sessionID){
							alert(_("You are not logged in.") + " " + _("You must be logged in to save."));
							var ed = $('#ff_ckeditor').ckeditorGet();
							if(ed) ed.resetDirty();
						}
						else{
							saveCurrent();
							var ed = $('#ff_ckeditor').ckeditorGet();
							if(ed) ed.resetDirty();
						}
					}
				},
				{
					text: _("Don't Save"),
					click: function(){
						$(this).dialog("close");
						var ed = $('#ff_ckeditor').ckeditorGet();
						if(ed) ed.resetDirty();
						$('#ff_dlog_div').dialog("close");
					}
				}
			]
		});
		
		// -------------------------------
		
		
		// -------------------------------
		// create div for login button:
		
		jQuery.get(ff_ckelements_data.sidScriptURL, null, function(data, textStatus, jqXHR){
			var buttonText = _("Login");
			if (textStatus == "success"){
				if (data.length) {
					ff_ckelements_data.sessionID = data;
					buttonText = _("Logout");
				}
			}
			$("<div></div>")
				.attr("id", "ff_ckelements_LoginButtonDiv")
				.addClass("ff_ckelements_StartEditLogin")
				.text(buttonText)
				.prependTo($("body"))
				.click(function(e) {
					if ($(this).text() == _("Login")){
						$('#ff_ckelements_LoginDialogDiv').dialog("open");
					}
					else{
						logout();
						$(this).text(_("Login"));
					}
				});
			}
		);
		// -------------------------------
		
	
		// -------------------------------
		// create div for editor dialog:
		ff_dlog_div = $("<div></div>")
				.attr({
					id: "ff_dlog_div",
					title: _("Edit webpage")
					}
				)
				.prependTo($("body"));
		// -------------------------------
		
		
		// -------------------------------
		// create textarea for ckeditor inside div for dialog:
		$("<textarea></textarea>")
			.attr({
				id: "ff_ckeditor",
				name: "ff_ckeditor"
				}
			)
			.appendTo(ff_dlog_div);
		// -------------------------------
		
			
		// -------------------------------
		// find all divs with class "ff_ckelements_Area" and prepend
		// div with "Edit" link and unique (numbered) ID
		var i = 1;
		$(".ff_ckelements_Area").each(function(){
			var currentName = "ff_ckelements_Area" + i;
			var jqObject = $(this);
			var closureFunc = function(jqObj, divName, divIndex){
				$("<div></div>")
					.attr("id", divName)
					.addClass("ff_ckelements_StartEdit")
					.text(_("Bearbeiten"))
					.prependTo(jqObj)
					.click(function(e) {
						showEditor(divName, divIndex);
					}
				);
			}
			closureFunc(jqObject, currentName, i);
			i++;
		});
		// -------------------------------
		
		
		// -------------------------------
		// initialize ckeditor:
		$('#ff_ckeditor').ckeditor(function(){
 				// alert("fertig");
 			}, {
  			language: ff_ckelements_data.language
  			}
		);
		// -------------------------------
		
		
		// -------------------------------
		// initialize jquery ui dialog:
		$('#ff_dlog_div').dialog(
		{
			modal: false,
			resizable: true,
			draggable: true,
			dialogClass: 'ff_ckelements_Dialog',
			position: ['center','center'],
			width: 400,
			height: 500,
			hide: 'fade',
			show: 'fade',
			closeOnEscape: true,
			autoOpen: false,
			beforeClose: function(){
				if (checkEditorDirtyFlag()){
					// alert(_("There are unsaved changes"));
					$('#ff_ckelements_UnsavedChangesDialogDiv').dialog("open");
					return false;
				}
			},
			buttons:[
				{
					text: _("Close"),
					click: function(){
						$(this).dialog("close");
					}
				},
				{
					text: _("Save"),
					click: function(){
						if (! ff_ckelements_data.sessionID){
							alert(_("You are not logged in.") + " " + _("You must be logged in to save."));
						}
						else{
							saveCurrent();
							var ed = $('#ff_ckeditor').ckeditorGet();
							if(ed) ed.resetDirty();
						}
					}
				},
				{
					text: _("Preview"),
					click: function(){
						var editorID = ff_ckelements_data.currentDivID;
						var theParent = $("#" + editorID).parent();
						$(theParent).html($('#ff_ckeditor').val());
							$(theParent).prepend(
								$("<div></div>")
									.attr("id", editorID)
									.addClass("ff_ckelements_StartEdit")
									.text(_("edit"))
									.click(function(e) {
										showEditor(editorID, ff_ckelements_data.currentEditorIndex);
										}
								)
						);
					}
				}
			]
		});
		// -------------------------------
		

	});
};

function checkEditorDirtyFlag(){
	var ed = $('#ff_ckeditor').ckeditorGet();
	if(ed){
		if (ed.checkDirty()){
			return true;
		}
	}
	return false;
}

function showEditor(editorID, editorIndex) {

	if (checkEditorDirtyFlag()){
		// alert(_("There are unsaved changes"));
		$('#ff_ckelements_UnsavedChangesDialogDiv').dialog("open");
		return;
	}
	
	var ed = $('#ff_ckeditor').ckeditorGet();

	var theParent = $("#" + editorID).parent().clone();
	
	theParent.children().first().remove();
	ff_ckelements_data.currentHTML = $(theParent).get(0).innerHTML;
	
	if($('#ff_dlog_div').dialog("isOpen")){
		$('#ff_ckeditor').val(ff_ckelements_data.currentHTML);
		if(ed) ed.resetDirty();
	}
	else{
		if(ed){
			ed.setData(ff_ckelements_data.currentHTML, function(){
				$('#ff_dlog_div').dialog('open');
			});
			ed.resetDirty();
		}
	}
	ff_ckelements_data.currentDivID = editorID;
	ff_ckelements_data.currentEditorIndex = editorIndex;
}

//----------- session handling and login --------------//

function login(data){
	if(! data){
		var data = {username:$("input#ff_username").val(), password:$("input#ff_password").val()}
	}
	
	jQuery.post(ff_ckelements_data.loginScriptURL, data, function(data, textStatus, jqXHR){
			if (textStatus == "success"){
				if (_(data) == _("Error: Invalid username or password.")) {
					$("p#ff_loginResultDisplay").text(_("Login failed. Please verify your user credentials."));
					return;
				}
				else{
					ff_ckelements_data.sessionID = data;
					$("p#ff_loginResultDisplay").text(_("Login successful."));
					$("#ff_ckelements_LoginDialogDiv").dialog("close");
					$("#ff_ckelements_LoginButtonDiv").text(_("Logout"));
				}
			}
		}
	);	
}

function logout(){
	jQuery.get(ff_ckelements_data.logOutScriptURL);
	ff_ckelements_data.sessionID = null;
}

function saveCurrent(){
	
	var saveData = {
		sid: ff_ckelements_data.sessionID,
		targetFileName: document.localFileName,
		http_referer: document.location.href,
		newHTML: $('#ff_ckeditor').val(),
		divClass: ".ff_ckelements_Area",
		divIndex: ff_ckelements_data.currentEditorIndex - 1
	};
	
	jQuery.post(ff_ckelements_data.saveScriptURL, saveData, function(data, textStatus, jqXHR){
			if (textStatus == "success"){
				if (data != "OK") {
					alert(_("Save failed") + ":" + data);
					$("#ff_ckelements_LoginButtonDiv").html(data);
				}
				else{
					var d = new Date();
					d = d.valueOf();
					var loc = document.location.href;
					var i = loc.indexOf("?");
					if (i > 0) loc = loc.substring(0, i)
					document.location = loc + "?" + ff_ckelements_data.editKeyword + d;
				}
			}
		}
	);
}

//----------- dynamically load required scripts --------------//

var scriptsLoader = function(){
	if (ff_ckelements_data.requiredscripts.length > 0){
		loadScript(ff_ckelements_data.requiredscripts.shift(), scriptsLoader);
	}
	else{
		allScriptsLoaded();
	}
}

function loadScript(url, callback){

	var head = document.getElementsByTagName('head')[0];
	var isCSS = false;
	
	var fileExt = url.substring(url.lastIndexOf("."));
	if (fileExt.toLowerCase() == ".css"){
		var script= document.createElement('link');
		script.type= 'text/css';
		script.rel= 'stylesheet';
		script.href= url;
		script.media = 'screen';
//		script.title = url.substring(url.lastIndexOf("/")); // den title mag er nicht
		isCSS = true;
	}
	else{
		var script= document.createElement('script');
		script.type= 'text/javascript';
		script.src= url;
	}
	
	if (callback){
		script.onreadystatechange = callback;
		script.onload = callback;
	}
	
	if (typeof script!="undefined"){
		if (window.console && console.log) console.log("loaded:" + url);
		head.appendChild(script);
	}
	else{
		if (window.console && console.log) console.log("couldn't load:" + url);
		callback();
	}
	
	if (isCSS){
		// the link object doesn't receive onload or onreadystatechange events :-(
		callback();
	}
}

// the whole party only starts, if a special keyword is appended to the URL
if (document.location.search.length > 1){
	if (document.location.search.substr(1, ff_ckelements_data.editKeyword.length) == ff_ckelements_data.editKeyword){
		loadScript(ff_ckelements_data.requiredscripts.shift(), scriptsLoader);
	}
}
