var active_identifier;

$(document).ready(function() {
	
	simple_edit_init();
	
});


/*
 * simple edit
 * 
 * init
 * 
 */
function simple_edit_init()
{
	
	/* setup ajax */
	jQuery.ajaxSetup({
		type: 'post',
		beforeSend: function() { $('.simple-edit-status').show(); },
		complete: function() { $('.simple-edit-status').hide(); },
		error: function(o, msg) {
			simple_edit_showError('Auf dem Server ist etwas schief gelaufen: ' + msg);
		},
	});
	
	/* */
	$('#simple-edit-login-form').dialog({
		autoOpen: false,
		title: 'Administration',
		'class': 'simple-edit-login',
		buttons: {
			'Abbrechen' : function() {
				$('#simple-edit-login-form').dialog('close');
			},
			'Login' : function() {
				
				$.ajax({
					url: 'simple-edit/login.ajax.php',
					data: {'username': $('#simple-edit-login-username').val(), 'password' : $('#simple-edit-login-password').val()},
					success: function(response) {
						
						if(is_numeric(response) && parseInt(response) == 1)
						{
							// show success
							simple_edit_showSuccess('Willkommen zur&uuml;ck!!');
							// close dialog
							$('#simple-edit-login-form').dialog('close');
							
							simple_edit_editMode();
							
							// set page to edit mode
							$.ajax({
								url: 'simple-edit/adminBar.ajax.php',
								success: function(response) {
									$('body').prepend(response);
									simple_edit_adminBar_events()
								}
							});
						}
						else
						{
							simple_edit_showError('Falsche Zugangsdaten!');
						}
					}
				});
				
			},
		}
	});
	
	
	/* */
	$('#simple-edit-dialog').dialog({
		title: 'Bereich editieren',
		autoOpen: false,
		width: 800,
		'class': 'simple-edit-dialog',
		position: ['center',25],
		open: function() {
			$('#simple-edit-dialog textarea').ckeditor();
		},
		close: function() {
			$('#simple-edit-dialog textarea').val("");
			$('#simple-edit-dialog textarea').ckeditorGet().destroy();
		},
		buttons: {
			'Abbrechen' : function() { $('#simple-edit-dialog').dialog('close') },
			'Speichern' : function() { simple_edit_setContent(active_identifier, $('#simple-edit-dialog textarea').val()) },
		}
	});
	
	/* */
	$('.simple-edit-login').click(function() {
		$('#simple-edit-login-form').dialog('open');
		return false;
	});
	
	/* */
	simple_edit_editMode_events();
	/* */
	simple_edit_adminBar_events();
}


/*
 * simple edit
 * 
 * set page to edit mode
 * 
 */
function simple_edit_editMode()
{	
	$('body').addClass('simple-edit-admin');
	simple_edit_editMode_events();
}

/*
 * simple edit
 * 
 * set edit page events
 * 
 */
function simple_edit_editMode_events()
{	
	/* */
	$('.simple-edit-admin .simple-edit').click(function() {
		
		active_identifier = str_replace ('simple-edit-', '', this.id);

		if(active_identifier.length > 0)
		{
			// open dialog
			$('#simple-edit-dialog').dialog('open');
			
			// get latest revision and set as editor content
			simple_edit_getContent(active_identifier)
		}
		
	});
}


/*
 * simple edit
 * 
 * set admin bar events
 * 
 */
function simple_edit_adminBar_events()
{
	/* */
	$('#simple-edit-toggle-admin').click(function() {

		if($('body').hasClass('simple-edit-admin'))
		{
			simple_edit_viewMode();
		}
		else
		{
			simple_edit_editMode();
		}
		
		return false;
	});
	
	$('#simple-edit-admin-bar ul').hover(
		function() { $('#simple-edit-admin-bar ul').stop().animate({'opacity':'0.9'}, 400); }, 
		function() { $('#simple-edit-admin-bar ul').stop().animate({'opacity':'0.4'}, 800); }
	)
}

/*
 * simple edit
 * 
 * set page to view mode
 * 
 */
function simple_edit_viewMode()
{
	$('body').removeClass('simple-edit-admin');
	$('.simple-edit').unbind('click');
}


/*
 * simple edit
 * 
 * returns content of page element matches the given key
 * 
 */
function simple_edit_getContent(identifier)
{
	$.ajax({
		url: 'simple-edit/get.ajax.php',
		data: {'identifier': identifier},
		success: function(response) {
			if(is_numeric(response) && parseInt(response) == 0)
			{
				simple_edit_showError('Du hast keine ausreichenden Berechtigungen!');
				$('#simple-edit-dialog').dialog('close');
			}
			else
			{
				$('#simple-edit-dialog textarea').val(response);
			}
		}
	});
}

/*
 * simple edit
 * 
 * sets content of page element matches the given key
 * 
 */
function simple_edit_setContent(identifier, content)
{
	$.ajax({
		url: 'simple-edit/set.ajax.php',
		data: { 'identifier': identifier, 'content': content },
		success: function(response) {
			if(is_numeric(response) && parseInt(response) == 1)
			{
				simple_edit_showSuccess('Der Inhalt wurde erfolgreich gespeichert.');
				
				$('#simple-edit-' + active_identifier).html(
					$('#simple-edit-dialog textarea').val()
				);
				
				$('#simple-edit-dialog').dialog('close');
			}
			else
			{
				simple_edit_showError('Beim Speichern ist ein Fehler augetreten.');
			}
		}
	});
}


/*
 * simple edit
 * 
 * shows growl error notification with given msg
 * 
 */
function simple_edit_showError(msg)
{
	humanMsg.displayMsg('Oops! ' + msg);
}

/*
 * simple edit
 * 
 * shows growl success notification with given msg
 * 
 */
function simple_edit_showSuccess(msg)
{
	humanMsg.displayMsg('Das hat geklappt! ' + msg);
}


function is_numeric (mixed_var) {
    // Returns true if value is a number or a numeric string  
    // 
    // version: 911.718
    // discuss at: http://phpjs.org/functions/is_numeric    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // +   bugfixed by: Tim de Koning
    // +   bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false
    // *     example 4: is_numeric([]);    // *     returns 4: false
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}


function count (mixed_var, mode) {
    // Count the number of elements in a variable (usually an array)  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/count    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Waldo Malqui Silva
    // +      bugfixed by: Soren Hansen
    // *     example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
    // *     returns 1: 6    // *     example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
    // *     returns 2: 6
    var key, cnt = 0;
 
    if (mixed_var === null){        return 0;
    } else if (mixed_var.constructor !== Array && mixed_var.constructor !== Object){
        return 1;
    }
     if (mode === 'COUNT_RECURSIVE') {
        mode = 1;
    }
    if (mode != 1) {
        mode = 0;    }
 
    for (key in mixed_var){
        cnt++;
        if ( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){            cnt += this.count(mixed_var[key], 1);
        }
    }
 
    return cnt;
}

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}        }
    }
    return sa ? s : s[0];
}
