Ajax.Responders.register({onCreate:show_loader,onComplete:hide_loader}); // Show loader when activity

function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function toggle_cockpit()
{
	modify_links = document.getElementsByClassName("modify_links");
	
	if (modify_links)
	{
		for(i=0;i<modify_links.length;i++)
			modify_links[i].toggle();
	}
		
	if ($('add_content_link')) $('add_content_link').toggle();
	if ($('cockpit_links')) $('cockpit_links').toggle();
}

function prepere_cockpit_toggle()
{
	if (!$('cockpit_toggle_link')) return false;
	
	$('cockpit_toggle_link').onclick = function()
	{
		toggle_cockpit();
	}
	
	body = document.getElementsByTagName("body");
	
	body[0].ondblclick = function()
	{
		if (!$('cockpit_links').visible())
			toggle_cockpit();
	}
	
}

function post_xstandard_code()
{
	if (!$('cockpit_editor') || !$('xhtml_value') || !check_category_input()) return false;
	
	$('cockpit_editor').EscapeUnicode = true;
	$('xhtml_value').value = $('cockpit_editor').value;

	//alert($('xhtml_value').value);
}

function prepere_form()
{
	if (!$('cockpit_form') || !post_xstandard_code) return false;
	
	//alert("prepere!")
	
	$('cockpit_form').onsubmit = function() {
		//alert(post_xstandard_code());
		return post_xstandard_code();
	}
	
	$('cancel_xstandard').onclick = function() {
		window.location.href = $('current_page').value;
	}
}

/*** CATEGORY STUFF ***/

function prepere_category_inputs()
{
	if (!$('category_id_box')) return false; // Only continue if category_id_box is present
	
	$('category_modify_buttons').hide();	// Hide category_modify_buttons from start, cause category_id is null
	
	$('category_name_box').hide();			// Hide textfield for new category
	$('ajax_buttons').hide();				// Hide buttons for renaming
	
	
	// Apply function to toggle-link (select/textfield)
	$('category_toggle_link').onclick = function() {
		toggle_category_inputs('');
	}
	
	// Apply function to select
	$('category_id').onchange = function()
	{
		$('option_index').value 		= $('category_id').selectedIndex;	// and hidden field with the selected index (needed for renamning option if db-renaming succeeds)
		
		toggle_category_modify_buttons();
	}
	
	// Apply function to delete link
	$('category_delete_link').onclick = function()
	{
		$('category_modify_id').value = $('category_id').value;			// and hidden field with the id
		modify_category('delete');
	}
	
	// Apply function to modify link
	$('category_modify_link').onclick = function() {
		$('category_modify_id').value = $('category_id').value;			// and hidden field with the id
		load_category_for_modifying();
	}
	
	// Apply function to rename cancel button
	$('cancel_modify').onclick = function()
	{
		$('category_modify_id').value 	= "";
		reset_from_modifying_mode();
	}
	
	// Apply function to modify submit button
	$('submit_modify').onclick = function()
	{
		if ($('category_modify_id').value != "")
			modify_category('rename');
		else
			modify_category('create');
	}
	
}

// Check if category is selected before submitting
function check_category_input()
{
	if(!$('category_id')) return true;
	
	if(
		($('category_id_box').visible() && !$('category_id').value) || 
		($('category_name_box').visible() && !$('category_name').value)
		)
	{
		alert("Välj en kategori eller skapa en ny!");
		return false;
	}
	else
		return true;
}

// Toggle betweem dropdown and inputs
function toggle_category_inputs(mode)
{
	$('cockpit_form').onsubmit = function() { return post_xstandard_code(); }
	
	$('category_id_box').toggle();
	$('category_name_box').toggle();
	
	if ($('category_id_box').visible())
	{
		$('category_id').focus();
		$('category_toggle_link').firstChild.nodeValue = "Skapa ny kategori";
		
		toggle_category_modify_buttons();
		$('form_buttons').show();			// Hide xstandard form buttons
	}
	else
	{
		$('category_name').focus();
		$('category_toggle_link').firstChild.nodeValue = "Välj bland befintliga kategorier";
		$('category_modify_buttons').hide();
		$('ajax_buttons').show();
		$('form_buttons').hide();			// Hide xstandard form buttons
		set_category_textfield_label("Ny kategori");			// Change textfield label
		
		if (mode != 'rename')
			$('category_modify_id').value 	= "";
		
		// Disable form.. we dont want a submit by mistake if the user hits enter
		$('cockpit_form').onsubmit = function() { return false; }
	}
}

function reset_from_modifying_mode()
{
	$('form_buttons').show();
	$('category_toggle_link').show();
	$('ajax_buttons').hide();
	toggle_category_inputs('');
	$('category_name').value = "";
	set_category_textfield_label("Ny kategori");
}

function set_category_textfield_label(value)
{
	textfield_label = $('category_name_box').getElementsByTagName("label");
	textfield_label[0].firstChild.nodeValue = value;
}

// Loads name of selected category in textfield for renaming
function load_category_for_modifying()
{
	category_name = $('category_id').options[$('category_id').selectedIndex].text;

	$('category_name').value = category_name;			// Load textfield with category name
	
	$('category_toggle_link').hide();					// Hide toggle link
	
	toggle_category_inputs('rename');							// Toggle inputs
	
	set_category_textfield_label("Döp om kategori");	// Change textfield label
	
	return false;
}

function toggle_category_modify_buttons()
{
	if($('category_id').value)
		$('category_modify_buttons').show();
	else
		$('category_modify_buttons').hide();
}

/*** AJAX STUFF ***/

// Action for updating caption
function modify_category(type) {
	
	url = window.location;
	
	category_id = $F("category_modify_id");
	
	if (type == "rename")
	{
		new_category_name = $F("category_name");
		post_body 	= 'ajax_action=rename&category_id=' + category_id + '&new_category_name=' + new_category_name;
		
		var ajax = new Ajax.Request(url, {method:'post', postBody:post_body, onSuccess:handlerFuncRename, onFailure:errFunc });
	}
	else if (type == "create")
	{
		new_category_name = $F("category_name");
		post_body 	= 'ajax_action=create&new_category_name=' + new_category_name;
		
		var ajax = new Ajax.Request(url, {method:'post', postBody:post_body, onSuccess:handlerFuncCreate, onFailure:errFunc });
	}
	else if (type == "delete")
	{
		if (top.confirm("Är du säker på att du vill radera den valda kategorin?"))
		{
			post_body 	= 'ajax_action=delete&category_id=' + category_id;

			var ajax = new Ajax.Request(url, {method:'post', postBody:post_body, onSuccess:handlerFuncDelete, onFailure:errFunc });
		}
		else
			return false;
	}
}

var handlerFuncCreate = function(t) {
	alert("Kategorin har lagts till!");
	
	if (t.responseText == "error") // Empty for firefox, null for safari
		alert("Kategorin kunde inte döpas om.");
	else
	{	
		var response_text_array = t.responseText.split("|"); // split on "|". first index is id, second is category name
		
		new_option 	= document.createElement("option");	// Create new option element
		new_option.value = response_text_array[0];
		
		option_text = document.createTextNode(response_text_array[1]);		// Create a child node to the option...

		new_option.appendChild(option_text);							// ... and append it
		
		$('category_id').appendChild(new_option);
		
		reset_from_modifying_mode();
		
		category_options = $('category_id').getElementsByTagName("option");
		
		new_selected_index = category_options.length -1;
		
		$('category_id').selectedIndex = new_selected_index;

	}
}

var handlerFuncRename = function(t) {
	//alert(t.responseText);
	
	if (t.responseText == "error") // Empty for firefox, null for safari
		alert("Kategorin kunde inte döpas om.");
	else
	{
		$('category_id').selectedIndex = $F('option_index');

		$('category_id').options[$('option_index').value].text = $F("category_name");

		reset_from_modifying_mode();
	}
}

var handlerFuncDelete = function(t) {
	if (t.responseText == "error") // Empty for firefox, null for safari
		alert("Kategorin kunde inte raderas, den används förmodligen av en eller flera artiklar.");
	else
	{	
		Element.remove($('category_id').options[$('option_index').value]);
		
		$('category_id').selectedIndex = 0;
	}
}

// Alert error if any
var errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

function show_loader() {
	if($('busy') && Ajax.activeRequestCount>0)
		Effect.Appear('busy');
}

function hide_loader() {
	if($('busy') && Ajax.activeRequestCount==0)
		Effect.Fade('busy');
}

addLoadEvent(prepere_form);
addLoadEvent(prepere_category_inputs);
addLoadEvent(prepere_cockpit_toggle);