/*
	UTILIDADES
*/

function stripTags(txt){
	return txt.replace(/<br[ ]*\/?>|<\/p>/gi, "\n").replace(/<\/?[^>]+>/gi, '');
}

/*
	FUNCIONES PARA EL MANEJO COMUN DE LAS RESPUESTAS
*/

function errorHandler(responseText){
	if(responseText != '')
		alert(stripTags(responseText));
	else
		alert("No se pudo ejecutar la accion correctamente, contáctese con el webmaster del sitio para informarle lo sucedido.\nMuchas gracias.");
}

/*
	FUNCIONES PARA EL MANEJO DE ACCIONES POR ENVIO DE FORMULARIO
*/

var currentFormActionHandler = false;
var sendingForm = false;
//Esta función s e ejecuta cuando se termino de enviar el formulario a un iframe y no hubo errores
function formReqSuccess(responseText){
	if(sendingForm){
		sendingForm = false;
		if(currentFormActionHandler){
			currentFormActionHandler(responseText);
			currentFormActionHandler = false;
		}
	}
}
//Esta función se ejecuta cuando se termino de enviar el formulario a un iframe y hubo errores
function formReqError(responseText){
	if(sendingForm){
		sendingForm = false;
		currentFormActionHandler = false;
		errorHandler(responseText);
	}
}

function formActionTimeout(){
	if(sendingForm){
		sendingForm = false;
		currentFormActionHandler = false;
		errorHandler('');
	}
}

function formAction(form, respHandler){
	sendingForm = true;
	currentFormActionHandler = respHandler;
	form = $(form);
	if(typeof(form.attr('target')) == 'undefined')
		form.attr('target', 'marco_sendForm');
	if($('#marco_sendForm').size() == 0)
		$('body').append('<iframe id="marco_sendForm" name="marco_sendForm" width="0" height="0" frameborder="0"></iframe>');
	form.submit();
	setTimeout('formActionTimeout()', (60*50*1000));
	return false;
}


/*
	FUNCIONES PARA EL MANEJO DE ACCIONES A TRAVES DE AJAX
*/

function action(url, params, respHandler, reqType, dataType){
	if(reqType == null)
		reqType = 'get';
	if(dataType != null)
		dataType = dataType.toLowerCase();
	if(dataType == null || (dataType != 'text' && dataType != 'json'))
		dataType = 'text';

	$.ajax({
		'async':true,
		'cache':false,
		'type':reqType,
		'url':url,
		'data':params,
		'dataType':dataType,
		'complete':function (XMLHttpRequest, textStatus) {
			switch(XMLHttpRequest.status){
			case 200: //Accion correcta
				switch(dataType){
				case 'json':
					var json = {};
					eval('json = '+XMLHttpRequest.responseText+';');
					respHandler(json);
				break;
				default:
					respHandler(XMLHttpRequest.responseText);
				break;
				}
			break;
			default: //Error en la accion
				errorHandler(XMLHttpRequest.responseText);
			break;
			}
		}
	});
	return false;
}

function jsonAction(url, params, jsonHandler){
	params['output'] = 'json';
	action(url, params, jsonHandler, 'get', 'json');
	return false;
}

function boolMsjAction(url, params, msjCorrecto, msjErroneo){
	var respHandler = function (resp){
		if(parseInt(resp))
			alert(msjCorrecto);
		else
			alert(msjErroneo);
	};
	action(url, params, respHandler, 'post', 'text');
	return false;
}