var swfu = null;       // Variable para la instancia del SWFUploader
var swfu_queue = [];   // Cola de uploads del SWFUploader
var empty_inputs = []; // Lista de inputs ya vaciados
var num_submits = 0;

function closeModalbox(no_reload)
{
	if(no_reload == null) {
		to_reload = true;
	} else {
		to_reload = false;
	}

	var formErrors;

	if ($('closeModalbox')) {
		// Switch the page if we are in a wizard
		if ($('wizard_redirect') && $('wizard_redirect').value.length > 0) {
			// Switch the displayed page
			Modalbox.show($('wizard_redirect').value, {title: '', width: 500, height: 600});
		}
		else {
			// Hide the modal box and refresh the current page
			Modalbox.hide();
			
			if(to_reload) {
				location.reload(false);
			}
		}
	}
	else {
		// Resize to new content and try to focus on error messages
		Modalbox.resizeToContent();

		if (swfu != null) {
			swfu.loadFlash();
		}
		
		Modalbox.focusableElements = Modalbox._findFocusableElements();

		formErrors = $$('.form-error');
		if (formErrors.length > 0) {
			formErrors[0].focus();
		}
	}
	
	num_submits = 0;
	
	return true;
}

function closeWizard()
{
	if ($('wizard_redirect')) {
		$('wizard_redirect').value = '';
	}
}

function removeCloneTemplates()
{
	if (num_submits == 0) {
		$$('.template').each(function(element) {
			element.remove();
		});
		
		num_submits++;
		
		return true;
	}
	else {
		return false;
	}
}

function hideSubmitButtons()
{
	var submit_area = $('submit-area');
	var loading_area = $('loading-area');
	
	if (submit_area != undefined && loading_area != undefined) {
		$(submit_area).hide();
		$(loading_area).show();
	}
}

function getNewItem(templateId, itemNumber)
{
	var newItem = $(templateId).cloneNode(true);
	
	// Le cambiamos el ID y le quitamos la clase 'template' al item nuevo
	$(newItem).removeClassName('template');
	$(newItem).writeAttribute('id', templateId + itemNumber);

	// Actualizamos los campos ID, Name y For recursivamente en el item nuevo
	form_replace_children(newItem, itemNumber, true);
	
	return newItem;
}

function form_add(templateId)
{
	var currentItem = $(templateId + '0');
	var lastItem = undefined;
	var newItem = undefined;
	var numItems = 0;
	var addButton = undefined;
	
	// Contamos el número de items disponibles y buscamos el último de ellos
	while (currentItem != undefined) {
		numItems++;
		lastItem = currentItem;
		currentItem = $(templateId + numItems);
	}
	
	newItem = getNewItem(templateId, numItems);
	
	// Insertamos el nodo en el documento HTML
	$(lastItem).insert({'after': newItem});
	
	// Eliminamos el botón de agregar del elemento desde el que se ha llamado a la función
	do {
		numItems--;
		addButton = $(templateId + numItems).select('#' + templateId + 'n');
	} while (addButton.length == 0 && numItems > 0);
	
	if (addButton.length > 0) {
		$(addButton)[0].remove();
	}
	
	// Actualizamos la lista de elementos 'focusables'
	if (Modalbox.initialized) {
		Modalbox.focusableElements = Modalbox._findFocusableElements();
	}
}

function form_replace_children(element, num_id)
{
	var search_tags = ['id', 'name', 'for', 'href', 'onclick'];
	var content;
	var index;
	
	// Actualizamos los campos ID, Name y For
	$(element).childElements().each(function(child)
	{
		form_replace_children(child, num_id, false);
		
		for (var n = 0; n < search_tags.length; n++)
		{
			content = $(child).readAttribute(search_tags[n]);
			
			if (content != null) {
			
				index = content.search(/%n%/i);
				
				if (index >= 0) {
					content = content.substr(0, index) + num_id + content.substr(index + 3);
					$(child).writeAttribute(search_tags[n], content);
				}
			}
		}
	});
}

function form_delete(element)
{
	var itemIndex = element.match(/\d+$/);
	var lastItemIndex = -1;
	var itemId = element.substr(0, element.length - itemIndex.toString().length);
	var nextItem = undefined;
	var addButton = $(element).select('#' + itemId + 'n');
	
	// Si el item contiene el botón de agregar, lo movemos al anterior disponible
	if (addButton.length > 0) {
		itemIndex = parseInt(itemIndex);

		do {
			itemIndex--;
			nextItem = $(itemId + itemIndex);

			if (nextItem != undefined && !nextItem.hasClassName('deleted')) {
				nextItem.select('.btn-clone')[0].insert({'before': addButton[0]});
				//nextItem.insert({'top': addButton[0]});
				break;
			}
		} while (nextItem != undefined);
		
		// Si no hay más items disponibles creamos uno nuevo
		if (nextItem == undefined) {
			
			// Contamos el número de items disponibles y buscamos el último de ellos
			do {
				lastItemIndex++;
			} while ($(itemId + lastItemIndex) != undefined)
			
			nextItem = getNewItem(itemId, lastItemIndex);
			//nextItem.select('.btn-clone')[0].insert({'before': addButton[0]});
			//nextItem.insert({'top': addButton[0]});
			
			// Insertamos el nodo en el documento HTML
			$(element).insert({'after': nextItem});
		}
	}

	// Cambiamos el estado del item y le añadimos el estilo 'deleted'
	$(element + 'FormStatus').value = 'deleted';
	$(element).addClassName('deleted');
	
	// Actualizamos la lista de elementos 'focusables'
	if (Modalbox.initialized) {
		Modalbox.focusableElements = Modalbox._findFocusableElements();
	}
}

function empty_input(input_element)
{
	if (empty_inputs[input_element] == null) {
		$(input_element).value = '';
		empty_inputs[input_element] = true;
	}
}


// TinyMCE event handlers

// Drag & drop blocker
var tinymce_block_dragdrop = function(ed) {
	if (tinymce.isIE) {
		tinymce.dom.Event.add(ed.getBody(), "dragenter", function(e) {
			return tinymce.dom.Event.cancel(e);
		});
	} else {
		tinymce.dom.Event.add(ed.getBody().parentNode, "dragover", function(e) {
			return tinymce.dom.Event.cancel(e);                
		});
	}
}

// Erase default contents
var tinymce_empty_textarea = function(ed) {
	tinymce.dom.Event.add(ed.getDoc(), "click", function(e) {
		if (empty_inputs[tinyMCE.activeEditor.id] == null) {
			tinyMCE.activeEditor.setContent("");
			empty_inputs[tinyMCE.activeEditor.id] = true;
		}
	});
}


// SWFUpload event handlers

var swfu_init = function()
{
    swfu = new SWFUpload(swfupload_settings);
}

// The uploadStart event handler.  This function variable is assigned to upload_start_handler in the settings object
var swfu_upload_start = function(file)
{
	var element = $$('.swfupload')[0];
	
	// Contamos cuantos elementos hay y obtenemos una copia del template
	var num_clonables = $(element).adjacent('div.clonable').length;
	var node = $(element).previous('.template').cloneNode(true);
	$(node).writeAttribute('id', $(node).readAttribute('id') + num_clonables);
	
	// Actualizamos los campos Id, Name y For
	form_replace_children(node, num_clonables);
	
	// Cambiamos algunos atributos
	$(node).childElements().each(function(child)
	{
		if ($(child).readAttribute('type') == 'text') {
			$(child).writeAttribute('value', file.name);
			$(child).writeAttribute('disabled', true);
		}
	});
	
	// Cambiamos la clase del contenedor
	$(node).removeClassName('template');
	$(node).addClassName('clonable');
	
	// Insertamos el nodo en el documento HTML
	$(element).insert({'before': node});
	
	// Guardamos el nodo en la cola
	swfu_queue[file.index] = node;
	
	return true;
}

// The uploadSuccess event handler.  This function variable is assigned to upload_success_handler in the settings object
var swfu_upload_success = function (file, server_data, receivedResponse)
{
	var node = swfu_queue[file.index];

	if (receivedResponse && server_data.length > 0 && !isNaN(server_data)) {
		// Eliminamos la imagen de carga y mostramos el botón de eliminar
		$(node).select('.upload-img')[0].remove();
		$(node).select('.btn-delete')[0].setStyle({display: 'inline'});
		
		// Actualizamos el contenido de los campos
		$(node).select('input').each(function(child)
		{
			id = $(child).readAttribute('id');

			if (id != null && id.substr(id.length - 2) == 'Id' && !isNaN(id[id.length - 3])) {
				$(child).value = server_data;
				return;
			}

			if (id != null && id.substr(id.length - 4) == 'Name') {
				$(child).writeAttribute('disabled', false);
				return;
			}
		});
	}
	else {
		alert('The upload failed! Please, try again.');
		$(node).remove();
	}
}

var swfu_dialog_complete = function fileDialogComplete(numFilesSelected, numFilesQueued)
{
	try {
		if (numFilesSelected > 0) {
			this.startUpload();
		}
	}
	catch (ex) {
		this.debug(ex);
	}
}





function switchTab(element)
{
	// Retrieve the name of the tab group
	var elementName = $(element).readAttribute('href').match(/#(.*)\./);

	if (elementName != null && elementName.length > 1) {
		var contentList = $$("div[id^='" + elementName[1] + "']");
		var selectedContentId = $(element).readAttribute('href').replace(/#/g, '');
		var tabId;
		
		var section = $(element).readAttribute('href').replace('#dotopen-seven.', '');
		
		var allHTMLTags = new Array();
		var allHTMLTags=document.getElementsByTagName('a');
		for (i=0; i<allHTMLTags.length; i++) {
			if (allHTMLTags[i].className=='reload-arrow') {
				allHTMLTags[i].setAttribute('href','/dotopen/users/reload_dotopen_seven/'+section);
			}
		}	
	

		// Only proceed if the selected tab is not visible
		if ($(selectedContentId).style.display == 'none' && contentList != null) {
			for (n = 0; n < contentList.length; n++)
			{
				// Search for the currently visible tab
				if ($(contentList[n]).style.display != 'none') {
					// Toggle the currently visible tab
					tabId = $(contentList[n]).readAttribute('id');
					$(tabId + '.tab').removeClassName('active');
					$(contentList[n]).toggle();

					// Toggle the selected tab
					tabId = selectedContentId + '.tab';
					$(tabId).addClassName('active');
					$(selectedContentId).toggle();
					break;
				}
			}
		}
	
		
	}

	return false;
}




