/* postulometro.js */
/*
jQuery(document).ready(function () {  	
					// selector
					$('#postulometro1').flash({  
						swf: '/presentacion/editorialavisos/postulometro/postulometro1.swf',						
						width: '184',
						height: '114',
						src: '/presentacion/editorialavisos/postulometro/postulometro1',
						quality: 'best',
						pluginspage: 'http://www.macromedia.com/go/getflashplayer',
						align: 'middle',
						play: 'true',
						loop: 'false',
						scale: 'showall',
						wmode: 'window',
						devicefont: 'false',
						// ID del postulometro
						id: 'postulometro1',
						bgcolor: '#f2f2f2',
						name: 'postulometro1',
						menu: 'false',
						allowFullScreen: 'false',
						allowScriptAccess: 'sameDomain',
						movie: 'postulometro1',
						salign: '',
		
						// Variables
						flashvars: {  
							minCVs: '0',  
							maxCVs: '300', 
							currentCVs: '0'
						}  
					}); 
				});
*/

function postulometro_getFlashObject( flashId ) {
	//return (navigator.appName.indexOf ("Microsoft") !=-1) ? window[flashId] : document[flashId];
	return (navigator.appName.indexOf ("Microsoft") !=-1) ? document.getElementById(flashId) : document[flashId];
}

function postulometro_setCurrentCVs( valor ) {
	var flash = postulometro_getFlashObject('postulometro1');
	if(typeof flash != "undefined" && flash.setCurrentCVs)
	{
		flash.setCurrentCVs( valor );
	}
	return false;
}

function postulometro_setCVlabels( minCVs, maxCVs, animateChange ) {
	var flash = postulometro_getFlashObject('postulometro1');
	if(typeof flash != "undefined" && flash.setCVlabels)
	{
		flash.setCVlabels( minCVs, maxCVs/*, animateChange*/ );
	}
	return false;
}

function postulometro_setFluctuacion( valor ) {	
	var flash = postulometro_getFlashObject('postulometro1');
	if(typeof flash != "undefined" && flash.setFluctuacion)
	{
		flash.setFluctuacion( valor );
	}
	
	return false;
}

function postulometro_setBacklight( encender, blTimeOff, infoTimeOff ) {
	//encender: 1 (prender) o 0 (apagar)
	//blTimeOff: tiempo para apagar backlight, en segundos (default:3)
	//infoTimeOff: tiempo que apaga el texto, en segundos (default: backlightTime * 1.5 = 4.5 segundos para default blTimeOff )

	var flash = postulometro_getFlashObject('postulometro1');
	if(typeof flash != "undefined" && flash.setBacklight)
	{
		flash.setBacklight( encender, blTimeOff, infoTimeOff );
	}
	
	return false;
}
/* end postulometro.js *//* eda_view.js */

jQuery(document).ready(function () {
	//si ejecuto esto es porque hay javasctipt
	$('HTML').attr('id', '');
});

var isDirty = false;
setDirty = function() {isDirty = true;}
clearDirty = function() {isDirty = false;}

jQuery(document).ready(function () {
    jQuery(':input').bind("change select keydown", setDirty);

	window.onbeforeunload = function (e) {
		if (isDirty == true)
		{
			var msg = "Usted tiene cambios aun no guardados.";

            var e = e || window.event;
            if (e) { e.returnValue = msg; }
            return msg;
        }
	}
});


function isLoggedEmpresa()
{
	var classes = jQuery('#editorial').attr('class').split(' ');
	var cantClasses = classes.length;
	for( var i = 0 ; i < cantClasses ; i++ )
	{
		if( classes[i] == 'edNotLoggedIn' )
		{
			return false;
		}
	}

	return true;
}

function deshabilitarTabsPagos()
{
	jQuery('#tabsMain').tabs('option', 'disabled', [2,3]);
}

function habilitarTabsPagos()
{
	jQuery('#tabsMain').tabs('enable', 2);
	jQuery('#tabsMain').tabs('enable', 3);
}

function dynLayoutEv()
{
	dynLayout( jQuery(window).width() );
}
function dynLayout(w)
{
	//defino el array con las clases
	var sizes = new Array(990, "w800", 995, "w1024"); /*default: 755,1010*/

	//busco la clase que corresponde al tamano pasado por parametro
	var sizeClass = sizes[1];
	for(var i=sizes.length-2;i>=0;i-=2)
	{
		if(w >= sizes[i] )
		{
			sizeClass = sizes[i+1];
			break;
		}
	}

	//remuevo las clases de sizes que ya tenia.
	//Lo hago asi porque no quiero sacar todas las clases que ya tenia (para no sacar otra que no tiene nada que ver)
	for(var i=sizes.length-2;i>=0;i-=2)
	{
		if( sizeClass != sizes[i+1] )
		{
			$('HTML').removeClass( sizes[i+1] );
		}
	}

	//agrego la clase que corresponde
	$('HTML').addClass(sizeClass);
}

jQuery(document).ready(dynLayoutEv);
jQuery(document).ready( function (){ jQuery(window).resize(dynLayoutEv); } );

function cloneElement(element)
{
	var clon = element.clone(true);
	var id = clon.attr('id');
	id = id.replace('Modelo',''); //Eliminamos la parte del id que dice Modelo ya que estamos creando uno visible.
	clon.attr('id', id);
	clon.show();//Lo activamos como visible.
	return clon;
}

function appendElement(parent, newSon)
{
	parent.append(newSon);
}

function deleteElement(element, callBackFunction)
{
	if (typeof callBackFunction == "undefined")
	{
		callBackFunction = function(){element.remove()};
	}

	element.fadeOut('slow', callBackFunction);
}

function deleteDisplayNoneElements(idParent)
{
	var object = $('#'+idParent);
	object.find('*').each(
		function(i){
			if($(this).css('display') == 'none')
				$(this).remove();
		}
	)
}

var validateFields = function()
{
	var errores_vacio = 0;
	var errores_longitud = 0;
	var error_salario = 0;
	var error_formatMail = 0;
	var errores_totales = 0;

	$('.required').each(
		function(i)
		{
			$(this).find('.fieldRequired').find('input:text').each(
				function(i)
				{
					if(jQuery.trim($(this).val()).length <= 0 && !$(this).attr('disabled'))
					{
						addErrorToField($(this).parents('.fieldRequired'), 'input:text', true);
						errores_vacio ++;
					}
				}
			)

			$(this).find('.fieldRequired').find('select').each(
				function(i)
				{
					if($(this).val() <= 0 && !$(this).attr('disabled'))
					{
						addErrorToField($(this).parents('.fieldRequired'), 'select', true);
						errores_vacio ++;
					}
				}
			)
		}
	);

	if (jQuery('#avisos').length)
	/*Comprobación especial para el campo de descripción con el editor tinyMCE*/
	{
		if(tinyMCE.activeEditor.getContent()=='')
		{
			$('#DESCRIPCION_CHECK').parents('.required').addClass('error');
			$('#DESCRIPCION_CHECK').parent().find('.iferror span').hide();
			$('#DESCRIPCION_CHECK').parent().find('.iferror .errorTxtRequired').show();

			errores_vacio ++;
		}
		if(tinyMCE.activeEditor.getContent().length > 4000)
		{
			$('#DESCRIPCION_CHECK').parents('.required').addClass('error');
			$('#DESCRIPCION_CHECK').parent().find('.iferror span').hide();
			$('#DESCRIPCION_CHECK').parent().find('.iferror .errorTxtLong').show();
			errores_longitud ++;
		}
	}

	//Como al registrar la empresa toma la primera parte del email como nombre del usuario, tenemso que asegurarnos que no sea mayor a 40 asi no se desborda al hacer la consulta SQL.
	var partes_email = $('#EMPRESAMAIL').val().split('@');

	if(jQuery.trim($('#EMPRESAMAIL').val()).length > 0 && (!isEmailFormat($('#EMPRESAMAIL').val()) || partes_email[0].length > 40) && !$('#EMPRESAMAIL').attr('disabled'))
	{
		addErrorToField($('#EMPRESAMAIL').parents('.fieldRequired'), 'input:text', true);
		error_formatMail ++;
	}

	if(parseInt($('#MINIMO').val()) > parseInt($('#MAXIMO').val()) && $("input[name='PLANPUBLICACION']:checked").attr('id') != 'plnGts' && !$('#MINIMO').attr('disabled') && !$('#MAXIMO').attr('disabled'))
	{
		addErrorToField($('#ctrSalario'), 'input:text', false);
		error_salario ++;
	}

	errores_totales = errores_vacio + error_salario + error_formatMail + errores_longitud;

	if(errores_vacio + error_formatMail + errores_longitud > 0)
	{
		$('#tabsMain').tabs('select', 0);
	}
	else if (error_salario > 0)
	{
		$('#tabsMain').tabs('select', 2);
	}

	return (!(errores_totales > 0));
}

//attacheo la validacion al evento submit del form
jQuery(document).ready(function () {
	//jQuery('.buttonPublicar').each( function(){jQuery(this).click(validateFields)});
	jQuery('#ALTA_POSTING').submit(
									function()
									{
										var submitearForm = function()
															{
																if( validateFields() ) //en realidad ya estaba validado, pero por las dudas....
																{
																	clearDirty();
																	document.getElementById("ALTA_POSTING").submit(); //submiteo de esta forma para que no sea recursivo
																}
															}

										if( validateFields() )
										{
											if( isLoggedEmpresa() )
											{
												login_showFormIfUserNotLogged( submitearForm );//primero le pido el login
											}
											else
											{
												submitearForm();
											}
										}
										return false;
									}
								);
});

//attacheo la funcion para prevenir que el form haga submit, cuando el usr apreta enter
jQuery(document).ready(function () {
	jQuery("#ALTA_POSTING").bind("keypress", function(e) {
														if (e.keyCode == 13) {
																return false;
														}
													});
});

function addErrorToField(object, type, requiredObject)
{
	var objectError;

	if(requiredObject)
	{
		objectError = $(object).parents('.required');
	}
	else
	{
		objectError = $(object);
	}

	objectError.addClass('error');

	var funcion_remover = function () {objectError.removeClass('error');};
	$(object).find(type).click(funcion_remover);
	$(object).find(type).keydown(funcion_remover);
}

function zeroPad(num, count)
{
	//hay que mejorar esta funcion!
	var numZeropad = num + '';
	while(numZeropad.length < count) {
		numZeropad = "0" + numZeropad;
	}
	return numZeropad;
}

function submitToComprar()
{
	//document.getElementById("ALTA_POSTING").action="e_comprarcreditos.ngmf";
	document.getElementById("ALTA_POSTING").action="/empresas/ecommerce/confirmar_upgrade_page.ngmf";
	//document.getElementById("plansug").value = plan;
	document.getElementById("ALTA_POSTING").submit();
}


function createNewEmpresaAndLoggin(afterSuccessCreationCallbackFunc, afterfailCreationCallbackFunc)
{
	//default para las funciones callback
	if (typeof afterSuccessCreationCallbackFunc == "undefined")
	{
		afterSuccessCreationCallbackFunc = function(){};
	}
	if (typeof afterfailCreationCallbackFunc == "undefined")
	{
		afterfailCreationCallbackFunc = function(){};
	}

	var manageCreateEmpError = function(bShowGenericError, extraMsg) {
									//llamo a la funcion que pasaron como parametro
									afterfailCreationCallbackFunc();

							 		//muestro el error
							 		//jQuery('#errorDescr').html(data);
							 		//jQuery('#errorDescr').parent().show();

							 		//oculto el loading
								 	hideCartelProcesando();
									if(bShowGenericError)
									{
										showErrorGenerico(extraMsg);
									}
								};

	var params = "EMPRESANOMBRE=" + jQuery('#EMPRESANOMBRE').val();
	params +=	 "&EMPRESAMAIL=" + jQuery('#EMPRESAMAIL').val();
	if( jQuery('#logoEmpBig').attr("src").indexOf('logoCropped_') > 0 ) //si cargo una imagen
	{
		params +=	 "&idImage=" + jQuery('#idImage').val();
	}

	jQuery.ajax({
		type: 'GET',
		data: params,
		url:  "e_crear_empresa_and_login.ngmf",
		dataType: "html",
		beforeSend: function(xhr)
					{
						showCartelProcesando();
					},
		error: function (xhr, ajaxOptions, thrownError)
				{
					try {
						idStatusRequest = xhr.status;
					}
					catch(e) {
						idStatusRequest = -1;
					}
					if(idStatusRequest!=200)
					{
						var bHasBeenLostConnection = idStatusRequest==0;

						manageCreateEmpError( !bHasBeenLostConnection, 'Mensaje error: ' + ajaxOptions + '. Id Status request: ' + idStatusRequest );

						if(bHasBeenLostConnection)
						{
							showErrorConexion();
						}
					}
				},
		success: function(data)
				 {
				 	if( jQuery.trim(data).length <= 0 )
				 	{
					 	//llamo a la funcion que pasaron como parametro
				 		afterSuccessCreationCallbackFunc();

				 		//pongo los datos de la empresa disabled
				 		jQuery('#EMPRESANOMBRE').addClass('disabledField');
						jQuery('#EMPRESANOMBRE').attr("disabled", "disabled");
						jQuery('#EMPRESAMAIL').addClass('disabledField');
						jQuery('#EMPRESAMAIL').attr("disabled", "disabled");

						//oculto el loading
					 	hideCartelProcesando();
				 	}
				 	else //hubo un error...
				 	{
				 		manageCreateEmpError(true, data);
				 	}
				 }
		});
}

function habilitarBotonPublicar()
{
	//le hablito los botones de publicar para que pueda volver a intentarlo
	jQuery('.buttonPublicar').each( function(){
												jQuery(this).removeClass('disabledField');
												jQuery(this).removeAttr("disabled");
	} );
}

var ComprarCreditos = function()
{
	if( validateFields() ) //valido
	{
		var doComprarCreditos = function()
								{
									//deshabilito los botones de publicar
									jQuery('.buttonPublicar').each( function(){
																				jQuery(this).addClass('disabledField');
																				jQuery(this).attr("disabled", "disabled");
									} );

									if( validateFields() ) //supuestamente ya habia validado, pero por las dudas...
									{
										//submiteo a comprar y guardo un borrador si esta disponible la opcion
										if( jQuery('#BORRADOR').length > 0 )
										{
											grabarBorradorAjax( function(){ submitToComprar() } );
										}
										else
										{
											if( isLoggedEmpresa() )
											{
												submitToComprar();
											}
											else
											{
												createNewEmpresaAndLoggin( function(){ grabarBorradorAjax( function(){ submitToComprar() } ); }, function(){ habilitarBotonPublicar(); } );
											}
										}
									}
									else
									{
										habilitarBotonPublicar();
									}

									return false;
								};


		if( isLoggedEmpresa() )
		{
			login_showFormIfUserNotLogged( doComprarCreditos );//primero le pido el login
		}
		else
		{
			doComprarCreditos();
		}
	}

	return false;
}


function fixPostStatusMsgPositionForIE()
{
	if(jQuery.browser.msie && jQuery.browser.version < 7)
	{
		var scrollPosition = jQuery(window).height() + jQuery(window).scrollTop();
		var elementHeight = jQuery('#postStatusMsg').height();

		jQuery('#postStatusMsg').css('position', 'absolute');
		jQuery('#postStatusMsg').css('top', (scrollPosition - elementHeight));
	}
}

function showCartelGuardando()
{
	fixPostStatusMsgPositionForIE();

	jQuery('#postStatusMsg').show();
	jQuery('#postStatusGuardandoBorrador').show();
	jQuery('#postStatusPublicando').hide();
	jQuery('#postStatusProcesando').hide();

	//
	//muestro el cartel de guardando
	jQuery('.guardandoBorrador').each( function() { jQuery(this).show() } );
	//oculto el boton de guardar borrador
	jQuery('.buttonLinkBorrador').each( function(){ jQuery(this).hide() } );
	//oculto los status del borrador
	jQuery('.statusLinkBorrador').each( function(){ jQuery(this).hide() } );
}

function getSerializedForm()
{
	//var params = jQuery("#ALTA_POSTING").serialize();
	var params = jQuery("#ALTA_POSTING").serialize().split("&");
	var fieldName, fieldsToEscape = ["TITULOPUESTO", "NOMBREALT", "CODREF", "AGRADECIMIENTO", "MAPACALLE", "CIUDAD[]"];
	//a CIUDAD[] se le van a sacar los corchetes para usar $() - mas adelante esto se va a cambiar
	for (var i = 0; i < params.length; i++)
		if (jQuery.inArray(unescape(fieldName = params[i].split("=")[0]), fieldsToEscape) >= 0)
			params[i] = fieldName+"="+escape($("#"+unescape(fieldName).replace(/[\[\]]/g, "")).val()).
				replace(/\+/g, "%2B").replace(/\%20/g, "+"); //se deja como en el resto de la URL armada por serialize()

	//agrego el tab seleccionado
	params[i] = 'SELECTED_EDA_TAB=' + jQuery('#tabsMain').tabs().data("selected.tabs");

	params = params.join("&");

	return params;
}

function grabarBorradorAjax( successCallbackFunc )
{
	//default para la funcion callback
	if (typeof successCallbackFunc == "undefined")
	{
		successCallbackFunc = function(){};
	}

	//obtengo el valor del tinymce para que lo tome el serialize
	//tinyMCE.activeEditor.getContent()
	var txtAux = jQuery('#avisos').val();
	jQuery('#avisos').val( tinyMCE.activeEditor.getContent() );

	//guardo el borrador
	params = getSerializedForm();

	var manageBorradorError = function( bShowGenericError, extraMsg )
								{
									//oculto los status del borrador
							 		jQuery('.statusLinkBorrador').each(
							 			    function(){
							 			                    jQuery(this).hide();
							 			                }
							 			)
							 		//
							 		jQuery('.postStatus').each(
							 			    function(){
							 			                    jQuery(this).hide();
							 			                }
							 			)

							 		//
							 		jQuery('#postStatusMsg').hide();
									//oculto el cartel de guardando
									jQuery('.guardandoBorrador').each( function() { jQuery(this).hide() } );
									//muestro el boton de guardar borrador
									jQuery('.buttonLinkBorrador').each( function(){ jQuery(this).show() } );
									//
									if(bShowGenericError)
									{
										showErrorGenerico(extraMsg);
									}
								};
	jQuery.ajax({
		type: 'POST',
		data: params,
		url:  "e_guardar_borrador.ngmf",
		dataType: "html",
		beforeSend: function(xhr)
					{
						showCartelGuardando();
					},
		error: function (xhr, ajaxOptions, thrownError)
				{
					try {
						idStatusRequest = xhr.status;
					}
					catch(e){
						idStatusRequest = -1;
					}
					if(idStatusRequest!=200)
					{
						var bHasBeenLostConnection = idStatusRequest==0;

						manageBorradorError( !bHasBeenLostConnection, 'Mensaje error: ' + ajaxOptions + '. Id Status request: ' + idStatusRequest );

						if(bHasBeenLostConnection)
						{
							showErrorConexion('Mensaje error: ' + ajaxOptions + '. Id Status request: ' + idStatusRequest );
						}
					}
				},
		success: function(data)
				 {
				 	if(data.length > 0 && data > -1)
				 	{
				 		jQuery('#IDAVISO').val(data);

				 		//actualizo la hora
				 		var currDate = new Date();
				 		jQuery('.postStatusTime').each( function()
				 										{
				 											jQuery(this).html( zeroPad(currDate.getHours(), 2) + ':' + zeroPad(currDate.getMinutes(), 2) );
				 										}
				 									);
				 		//muestro los status del borrador
				 		jQuery('.statusLinkBorrador').each(
				 			    function(){
				 			                    jQuery(this).show();
				 			                }
				 			)
				 		//
				 		jQuery('.postStatus').each(
				 			    function(){
				 			                    jQuery(this).show();
				 			                }
				 			)

				 		//marco el formulario como que ya esta guardado (not dirty)
				 		clearDirty();

				 		jQuery('#postStatusMsg').hide();

						//oculto el cartel de guardando
						jQuery('.guardandoBorrador').each( function() { jQuery(this).hide() } );
						//muestro el boton de guardar borrador
						jQuery('.buttonLinkBorrador').each( function(){ jQuery(this).show() } );
						//
						//llamo a la funcion que pasaron como parametro
				 		successCallbackFunc();
				 	}
				 	else
				 	{
				 		manageBorradorError(true, data);
				 	}
				 }
		});

	//pongo el valor del textarea como estaba antes
	jQuery('#avisos').val(txtAux);

	return false;
}

//agrego la ejecucion del guardado cada 1 minuto. Lo hago en el domReady para no tratar de guardar antes de que cargue la pagina
/*$(document).ready(function () {
	setInterval("grabarBorradorAjax()", 60000);
});*/




function manageLinkGuardarBorrador()
{
	grabarBorradorAjax();
	return false;
}

//attacheo la funcion de guardar borrador a los botones
jQuery(document).ready(function (){

	jQuery('.buttonLinkBorrador').each(
										function()
										{
											jQuery(this).click(
																	function()
																	{
																		return manageLinkGuardarBorrador();
																	}
																);
										}
									)
	});



function actualizarPostulometro()
{
	var pais = jQuery("#PAIS").val();
	var plan = jQuery("input[name='PLANPUBLICACION']:checked").val();
	/*var oficio = document.getElementById('OFICIO') != null ? document.getElementById('OFICIO').options[document.getElementById('OFICIO').selectedIndex].value : 0;
	var area = document.getElementById('AREA') != null ? document.getElementById('AREA').options[document.getElementById('AREA').selectedIndex].value : 0;
	var categoria = document.getElementById('CATEGORIA') != null ? document.getElementById('CATEGORIA').options[document.getElementById('CATEGORIA').selectedIndex].value : 0;*/
	var oficio = jQuery('#OFICIO').val();
	var area = jQuery('#AREA').val();
	var categoria = jQuery('#CATEGORIA').val();

	//if(pais > 0 && plan > 0 && oficio > 0 && area > 0 && categoria > 0 )
	{
		var params = "IDPAIS=" + pais;
		params += "&IDPLAN=" + plan;
		params += "&IDOFICIO=" + oficio;
		params += "&IDAREA=" + area;
		params += "&IDCATEGORIA=" + categoria;

		jQuery.ajax({
						type: 'GET',
						data: params,
						url:  "e_estimar_postulaciones.ngmf",
						dataType: "html",
						beforeSend: function(xhr)
									{
										postulometro_setFluctuacion(1000);
										postulometro_setBacklight(1);  //enciendo el postulometro
									},
						success: function(data)
								 {
									if(data.length > 0 && data > -1)
									{
										//nota: por ahora vamos a usar solo 2 escalas; 0 -> 300 y 0 -> 800
										if(data > 310)
										{
											postulometro_setCVlabels(0, 800, 0)
										}
										else
										{
											postulometro_setCVlabels(0, 300, 0);

										}

										postulometro_setCurrentCVs(data);
									}

									postulometro_setFluctuacion(10);
									postulometro_setBacklight( 0, 8 ); //seteo el tiempo para que se apague el postulometro
								 }
					});
	}
}

//seteo el postulometro con los datos que tiene la pantalla cuando arranca
/*jQuery(document).ready(function (){
		actualizarPostulometro();
	});
*/


//Agrego la funcion para manejar el cambio de tabs
jQuery(document).ready(function (){
									jQuery('#tabsMain').bind('tabsshow', function(event, ui)
																			{
																				//scroleo para arriba
																				jQuery('html,body').animate({scrollTop: 0}, 0);
																			});
});


//grey cover
function createGreyCover()
{
	var isIE6 = jQuery.browser.msie && jQuery.browser.version < 7;

	//creo el gray cover
	var greycover = document.createElement('div');
	greycover.id = 'greycover';
	greycover.style.position = isIE6 ? 'absolute' : 'fixed';
	greycover.style.top = '0px';
	greycover.style.left = '0px';
	greycover.style.background = '#EEEEEE';
	greycover.style.zIndex = 2;
	greycover.style.width = '100%';
	greycover.style.height = isIE6 ? document.body.clientHeight : '100%' ;
	greycover.style.opacity = 0.5;
	greycover.style.filter = 'alpha(opacity=50)'; // IE6 requires this + greycover to have layout, which it does.

	jQuery('#editorial').append( greycover );
}

function removeGreyCover()
{
	jQuery('#greycover').fadeOut( 'slow', function() { jQuery('#greycover').remove() } );
}


//////////////////////////////////////////////////////////////////////////
//errores popup
//////////////////////////////////////////////////////////////////////////
function showErrorPopup( idErrorPopup, extraMsg )
{
	if (typeof idErrorPopup == "undefined")
	{
		idErrorPopup = 'errorGenerico';
	}

	createGreyCover();
	jQuery('#divErroresPopup').show();
	jQuery('#' + idErrorPopup).show();
	jQuery('#divErroresPopup .reportarErrorPopup').show();
	if (typeof extraMsg != "undefined")
	{
		jQuery('#errorExtraMsg').text(extraMsg);
		//jQuery('#errorExtraMsg').show();
	}
	jQuery('#divErroresPopup .errorReportado').hide();
	jQuery('#divErroresPopup .loadingReportando').hide(); //no deberia estar visible pero si lo esta, la oculto

	//scroleo para arriba
	jQuery('html,body').animate({scrollTop: 0}, 0);
}

function showErrorConexion(extraMsg)
{
	showErrorPopup('errorConexion', extraMsg);
}

function showErrorGenerico(extraMsg)
{
	showErrorPopup('errorGenerico', extraMsg);
}

function hideErrorPopup()
{
	jQuery('#greycover').remove();
	jQuery('#divErroresPopup').hide();
	jQuery('#divErroresPopup').find('p').hide();
	jQuery('#errorExtraMsg').text(''); //.hide();
}

jQuery(document).ready(function (){
	jQuery('#aceptarErrorPopup').click( function() {
													hideErrorPopup();
													return false;
												});

	jQuery('#divErroresPopup .reportarErrorPopup').click( function() {

		var errorMsg = '';
		jQuery('#aceptarErrorPopup').parent().parent().find('p:visible').each(function(){ errorMsg += jQuery(this).html() + '\n' });
		errorMsg += jQuery('#errorExtraMsg').html();

		//reporto
		empUsersAjaxLayers_reportError('Error reportado en Editorial de Avisos', errorMsg, this);

		//muestro que se reporto bien (no me importa como salio en realidad)
		jQuery(this).fadeOut(1200,function() {
			jQuery('#divErroresPopup .errorPopupReportado').fadeIn(1200);
			});
		return false;
	});
});


//////////////////////////////////////////////////////////////////////////
//cartel que dice que se esta publicando el aviso
//////////////////////////////////////////////////////////////////////////
function showCartelPublicando()
{
	fixPostStatusMsgPositionForIE();

	createGreyCover();
	jQuery('#postStatusMsg').show();
	jQuery('#postStatusPublicando').show();
	jQuery('#postStatusGuardandoBorrador').hide();
	jQuery('#postStatusProcesando').hide();
}

function hideCartelPublicando()
{
	jQuery('#greycover').remove();
	jQuery('#postStatusMsg').hide();
}

var publicarIfCompraOk = function(idCupon, cantIntentos)
{
	if (typeof cantIntentos == "undefined")
	{
		cantIntentos = 10;
	}
	else if(cantIntentos <= 0) //ya intentamos todas las veces, corto la ejecucion.
	{
		hideCartelPublicando();
		return false;
	}

	var managePublicarError = function(bShowGenericError, extraMsg) {
									hideCartelPublicando();

									//muestro el error
									data = '<div>'+data+'</div>';
									data += '<div style="padding-top:20px; color:#000000;"><button class="buttonBig" id="buttonErrorCompra" style="color:#000000;">Aceptar</button></div>';
									var box = '<div id="divCajaErrorCompra">'+data+'</div>';
									createGreyCover();
									jQuery('body').append(box);

									jQuery('#buttonErrorCompra').click(
										function()
										{
											removeGreyCover();
											jQuery('#divCajaErrorCompra').remove();
										}
									);
									if(bShowGenericError)
									{
										showErrorGenerico(extraMsg);
									}
								};

	//guardo el borrador
	var params = 'ecommerce_idcupon=' + idCupon;

	jQuery.ajax({
		type: 'GET',
		data: params,
		url:  "/empresas/cupones_pago/tarjeta_credito/check_compra_status.ngmf",
		dataType: "html",
		beforeSend: function(xhr)
					{
						if(jQuery('#greycover').length <= 0) //pongo esto para que no me agregue el cartel por cada intento
						{
							showCartelPublicando();
						}
					},
		error: function (xhr, ajaxOptions, thrownError)
				{
					try {
						idStatusRequest = xhr.status;
					}
					catch(e){
						idStatusRequest = -1;
					}
					if(idStatusRequest!=200)
					{
						var bHasBeenLostConnection = idStatusRequest==0;

						managePublicarError( !bHasBeenLostConnection, 'Mensaje error: ' + ajaxOptions + '. Id Status request: ' + idStatusRequest);

						if(bHasBeenLostConnection)
						{
							showErrorConexion();
						}
					}
				},
		success: function(data)
				 {
					if( jQuery.trim(data).length <= 0 )
				 	{
				 		//submiteo el formulario para publicar
				 		document.getElementById("ALTA_POSTING").submit();
				 	}
				 	else
				 	{
				 		//llamo recursivamente a la misma funcion con un intento menos y un delay
				 		cantIntentos--;
				 		if(cantIntentos > 0) //ya intentamos todas las veces, corto la ejecucion.
				 		{
				 			window.setTimeout( 'publicarIfCompraOk( '+idCupon+', '+cantIntentos+' )', 5000 );
				 		}
				 		else
				 		{
				 			managePublicarError(true, data);
				 		}
				 	}
				 }
		});

	return false;
}

//Habilitamos evento keydown para permitir sólo números en los campos numéricos y caracteres necesarios
jQuery(document).ready(function (){

	jQuery('.campoNumerico').each(
			function()
			{
					jQuery(this).keydown(
						function(fn)
						{
							return checkKeyNumeric(fn.keyCode);
						}
					);
			}
		);
});

function checkKeyNumeric(number)
{
	var ValidKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110,188,190];
	var IsNumber = false;
	for (i=0; i< ValidKeys.length && !IsNumber; i++)
    {
		if (number == ValidKeys[i])
        {
			IsNumber = true;
        }
    }
	return IsNumber;
}

function isEmailFormat(email)
{
	var filter=/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
	return filter.test(email);
}

function showCartelProcesando()
{
	fixPostStatusMsgPositionForIE();

	//createGreyCover();
	jQuery('#postStatusMsg').show();
	jQuery('#postStatusProcesando').show();
	jQuery('#postStatusPublicando').hide();
	jQuery('#postStatusGuardandoBorrador').hide();
}

function hideCartelProcesando()
{
	jQuery('#greycover').remove();
	jQuery('#postStatusMsg').hide();
}

function storePostingInSession(redirectTo, beforeCallBackCallbackFunc, successCallbackFunc, errorBackCallbackFunc)
{
	//si no hizo nada, no intento guardarlo
	if(!isDirty)
	{
		if (typeof redirectTo != "undefined")
		{
			 window.location = redirectTo;
			 return false;
		}
		return true;
	}

	//default para los parametros
	if (typeof successCallbackFunc == "undefined")
	{
		successCallbackFunc = function(data){
			if(data.length > 0 && data > -1)
		 	{
		 		//marco el formulario como que ya esta guardado (not dirty)
		 		clearDirty();
		 	}

			hideCartelProcesando();

			if (typeof redirectTo != "undefined")
			{
				 window.location = redirectTo;
			}
		};
	}
	if (typeof beforeCallBackCallbackFunc == "undefined")
	{
		beforeCallBackCallbackFunc = function(xhr) {
			showCartelProcesando();
		};
	}
	if (typeof errorBackCallbackFunc == "undefined")
	{
		errorBackCallbackFunc = function(xhr, ajaxOptions, thrownError) {
			hideCartelProcesando();

			if (typeof redirectTo != "undefined")
			{
				 window.location = redirectTo;
			}
		};
	}

	//obtengo el valor del tinymce para que lo tome el serialize
	//tinyMCE.activeEditor.getContent()
	var txtAux = jQuery('#avisos').val();
	jQuery('#avisos').val( tinyMCE.activeEditor.getContent() );

	//guardo el borrador
	params = getSerializedForm();

	jQuery.ajax({
		type: 'POST',
		data: params,
		url:  "e_guardar_session_posting.ngmf",
		dataType: "html",
		beforeSend: beforeCallBackCallbackFunc,
		error: errorBackCallbackFunc,
		success: successCallbackFunc
		});

	//pongo el valor del textarea como estaba antes
	jQuery('#avisos').val(txtAux);

	return false;
}


//attacheo evento al link de login
jQuery(document).ready(function () {
	jQuery('#HeaderEmpresas a[href*="e_login.ngmf"]').click( function() {
		return storePostingInSession( jQuery(this).attr('href') );
	});
});
/* end eda_view.js *//* eda_tabplan.js */
//Planes Disponibles
var posting = new Object();

//estos valores se van a modificar del lado de php
posting.availablePlans = [];
posting.freePlan = 90;
posting.isEcommerceImplemented = false;
//

posting.isAvailable = function (plan){
							var foundPlan = false;
							var plans = this.availablePlans;
							var i = 0;
	    					for (i = 0; i <= plans.length; i++) { 
		    					if(plans[i] == plan){
		    						foundPlan = true;
		    						break;
		    					}
	    					}
	    					return foundPlan;
	    				};

	    				
function disablePlanTabs()
{
	var tabCount = jQuery('#tabsInner').tabs( 'length' );
	var tabsIndexArray = [];
	for(var nTabIndex = 0 ; nTabIndex < tabCount ; nTabIndex++ )
	{		
		tabsIndexArray.push(nTabIndex);
	}
	jQuery('#tabsInner').tabs('option', 'disabled', tabsIndexArray);
	
	return false;
}

function makeChangesAboutPlan(planSelected, isModifyingPosting)
{	
	
	//si selecciono el gratis
	if( planSelected == posting.freePlan )
	{
		deshabilitarTabsPagos();
		//jQuery('#PROXIMOPASOplan').hide();
		jQuery('#PROXIMOPASOplan').click(function() {
			jQuery('#tabsMain').tabs('select', 4);
			return false;
		});
	}
	else
	{
		habilitarTabsPagos();
		//jQuery('#PROXIMOPASOplan').show();
		jQuery('#PROXIMOPASOplan').click(function() {
			jQuery('#tabsMain').tabs('select', 2);
			return false;
		});
		
		/*if( !isLoggedEmpresa() )
		{
			jQuery('#itemsLogo').hide();	
		}*/
	}	
		
	//actualizo el postulometro
	actualizarPostulometro();

	//manejar los botones de publicar
	if(!isModifyingPosting)
	{
		if(posting.isEcommerceImplemented)
		{
			if(!posting.isAvailable(planSelected))
			{				
				if( planSelected == posting.freePlan || (planSelected == 420 && jQuery('#PAIS_HIDDEN').val() == 18)) //Si el plan es destacado plus y estamos en mexico no muestro el boton de pagar
				{										
					
					$('.buttonPublicar').each(function () {
																jQuery(this).hide();
															});
					
					$('#oAviso').hide(); // Ocultamos el "o" del guardar del último tab, ya que como no tiene botón de próximo paso ni de comprar quedaría "o guardar" sin nada adelante
					
					
				}
				else //si el plan no es gratis, le muestro el boton para pagar
				{
					
					$('.buttonPublicar').each(function () {
																jQuery(this).val(jQuery('#textComprar').val());
																jQuery(this).click(ComprarCreditos);
																//jQuery('#ALTA_POSTING').unbind('submit', validateFields);
																jQuery(this).show();
															});
					$('#oAviso').show();
				}
			}
			else
			{
				$('.buttonPublicar').each(function () {
															jQuery(this).val($('#textPublicar').val());
															jQuery(this).unbind('click', ComprarCreditos);
															//jQuery('#ALTA_POSTING').submit( validateFields );
															jQuery(this).show();
														});
				$('#oAviso').show();
			}
		}
		else
		{
			if(!posting.isAvailable(planSelected))
			{
				$('.buttonPublicar').each(function () {
															jQuery(this).hide();
														});
				$('#oAviso').hide(); // Ocultamos el "o" del guardar del último tab, ya que como no tiene botón de próximo paso ni de comprar quedaría "o guardar" sin nada adelante 
			}
			else
			{
				$('.buttonPublicar').each(function () {
															jQuery(this).val($('#textPublicar').val());
															jQuery(this).unbind('click', ComprarCreditos);
															jQuery(this).show();
														});
				$('#oAviso').show();
			}
		}
	}
	/*else
	{
		disablePlanTabs();
	}*/
}

//Cambiamos pais de publicacion
function changeCountryPosting()
{
	if (jQuery('#PAIS').val() == 0)
	{
		jQuery('#tabPlanPublicacion').html('<div class="edNota"><p>'+jQuery('#textNoPaisSeleccionado').html()+'</p></div>');
	}
	else
	{
		jQuery('#PAIS').attr('disabled', 'disabled');
		jQuery('#tabPlanPublicacion').html('<IMG alt="Cargando..." src="/images/avisos/ajax-loader.gif"/>');
		// now if I join our inputs using '&' we'll have a query string
		var req = jQuery.ajax({
			type: "POST",
			data: "pais_publicacion="+$("#PAIS").val(),
			url: 'e_cambiar_pais_publicacion.ngmf',
			success: function(r) {
			  	jQuery('#tabPlanPublicacion').html(r);
			  	jQuery('#PAIS').removeAttr('disabled');
			}
		});
	}
	return false;
}
/* end eda_tabplan.js *//* eda_tabdescr.js */
function html_entity_decode(str) {
	if(str === undefined)
	{
		return '';
	}
	
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;	
}

//Calidad
function setCalidadTitulo(calidad)
{
	switch(calidad)
	{
		case 1: //buena
			jQuery('#imgCalidadTituloBuena').attr("src", "/images/avisos/cal-big-ok.gif");
			jQuery('#imgCalidadTituloRegular').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadTituloMal').attr("src", "/images/avisos/cal-big-no.gif");
			break;
				
		case 2: //regular
			jQuery('#imgCalidadTituloBuena').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadTituloRegular').attr("src", "/images/avisos/cal-big-reg.gif");
			jQuery('#imgCalidadTituloMal').attr("src", "/images/avisos/cal-big-no.gif");
			break;
			
		case 3: //mala
			jQuery('#imgCalidadTituloBuena').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadTituloRegular').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadTituloMal').attr("src", "/images/avisos/cal-big-mal.gif");
			break;
	}
}

function setCalidadDescripcion(calidad)
{
	switch(calidad)
	{
		case 1: //buena
			jQuery('#imgCalidadDescrBuena').attr("src", "/images/avisos/cal-big-ok.gif");
			jQuery('#imgCalidadDescrRegular').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadDescrMal').attr("src", "/images/avisos/cal-big-no.gif");
			break;
				
		case 2: //regular
			jQuery('#imgCalidadDescrBuena').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadDescrRegular').attr("src", "/images/avisos/cal-big-reg.gif");
			jQuery('#imgCalidadDescrMal').attr("src", "/images/avisos/cal-big-no.gif");
			break;
			
		case 3: //mala
			jQuery('#imgCalidadDescrBuena').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadDescrRegular').attr("src", "/images/avisos/cal-big-no.gif");
			jQuery('#imgCalidadDescrMal').attr("src", "/images/avisos/cal-big-mal.gif");
			break;
	}
}


function calcCalidadTitulo(texto)
{
	jQuery.ajax({
		type: 'POST',					
		data: 'TEXTO='+escape(texto)+'&TIPO=1',
		url:  "e_calcular_calidad_texto.ngmf",
		dataType: "json",
		/*beforeSend: function(xhr)
					{
						
					},*/
		success: function(data) 
				 {	
					var object = eval(data);					
					setCalidadTitulo(object.calidad);		
					
					//oculto todas las descripciones de las recomendaciones y su contenedor
					jQuery('#ulRecomendCalidadTitulo').hide();
					jQuery('#ulRecomendCalidadTitulo').parent().hide();
					jQuery('.calidadTituloParams').hide();
					
					//muestro las recomendaciones que necesito
					var keysQueNoCumplen = object.keysNoCumplen;
					var countKeysQueNoCumplen = keysQueNoCumplen.length;
					if(countKeysQueNoCumplen > 0)
					{					
						jQuery('#ulRecomendCalidadTitulo').show(); //muestro el contenedor
						jQuery('#ulRecomendCalidadTitulo').parent().show();
						
						for( var i = 0 ; i < countKeysQueNoCumplen ; i++ )
						{
							var key = keysQueNoCumplen[i];
							jQuery('#calidadTituloParam'+key).show();
						}
					}
				 }
	});
}

jQuery(document).ready(function() {
									//attacheo el calculo de la calidad del titulo al evento blur del control
									jQuery('#TITULOPUESTO').blur( function(){ calcCalidadTitulo( jQuery('#TITULOPUESTO').val() ) } );
									jQuery('#TITULOPUESTO').blur( function(){ refreshSimilarsPostings(); } );
									
									//corro por primera vez el calculo de la calidad del titulo
									if( jQuery('#TITULOPUESTO').val().length > 0 ) {
										calcCalidadTitulo(jQuery('#TITULOPUESTO').val())
									}
});
						

function calcCalidadDescripcion(texto)
{
	jQuery.ajax({
		type: 'POST',					
		data: 'TEXTO='+escape(texto)+'&TIPO=2',
		url:  "e_calcular_calidad_texto.ngmf",
		dataType: "json",
		/*beforeSend: function(xhr)
					{
						
					},*/
		success: function(data) 
				 {	
					var object = eval(data);					
					setCalidadDescripcion(object.calidad);		
					
					//oculto todas las descripciones de las recomendaciones y su contenedor
					jQuery('#ulRecomendCalidadTexto').hide();
					jQuery('.calidadTextoParams').hide();
					
					//muestro las recomendaciones que necesito
					var keysQueNoCumplen = object.keysNoCumplen;
					var countKeysQueNoCumplen = keysQueNoCumplen.length;
					if(countKeysQueNoCumplen > 0)
					{					
						jQuery('#ulRecomendCalidadTexto').show(); //muestro el contenedor
						
						for( var i = 0 ; i < countKeysQueNoCumplen ; i++ )
						{
							var key = keysQueNoCumplen[i];
							jQuery('#calidadTextoParam'+key).show();
						}
					}
				 }
	});
}

function handleTinyMCEChangeEvent(inst) 
{
	if (inst.isDirty()) //si no cambio nada, no recalculo
	{		
		var texto = html_entity_decode(inst.getBody().innerHTML);
		//var texto = inst.getContent({format : 'text'});
		calcCalidadDescripcion(texto);
	}
}

//tinyMCE
tinyMCE.init({
        handle_event_callback : "descripcion_HandleEvent",
        onchange_callback : "handleTinyMCEChangeEvent",
        setup : function(ed, e, o) {
			ed.onInit.add(initializeTinyMCE);
			ed.onPaste.add( function(ed, e, o) {
		        ed.execCommand('mcePasteText', true);
		        return tinymce.dom.Event.cancel(e);
			});
        },
        mode : "textareas",
        language : "es",
        theme : "advanced",
        mode : "exact",
        elements : "avisos",
        inline_styles : false,
        gecko_spellcheck : true,
        plugins : "paste,spellchecker",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_buttons1 : "bold,italic,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,undo,redo,separator,charmap,pastetext,pasteword,selectall,separator,spellchecker",
        theme_advanced_buttons2 : "",
        spellchecker_languages : "+Espa&ntilde;ol=es,English=en,Portugues=pt",
        spellchecker_report_misspellings: false,
        paste_create_paragraphs : false,
        paste_create_linebreaks : false,
        paste_use_dialog : true,
        paste_auto_cleanup_on_paste : true,
        paste_convert_middot_lists : false,
        paste_unindented_list_class : "unindentedList",
        paste_convert_headers_to_strong : true,
        paste_insert_word_content_callback : "convertWord",
        width : "530",
        height : "350",
        valid_elements : "-a[href|target=_blank|title],-strong/-b,-em/-i,-p[dir|align],-ol,-ul,-li,br,-sub,-sup,caption[dir],-div[dir|align],-span[align],address[align]" });

function convertWord(type, content) {
    switch (type) {
        // Gets executed before the built in logic performes it's cleanups
        case "before":
            content = content; // Some dummy logic
            break;

        // Gets executed after the built in logic performes it's cleanups
        case "after":
            content = content; // Some dummy logic
            break;
    }
    return content;
}

//

//tabindex para el tinyMCE
function initializeTinyMCE()
{
	jQuery('#avisos_ifr').attr('tabindex', 2);
	//corro por primera vez el calculo de la calidad del texto del aviso
	var textoActual = tinyMCE.activeEditor.getContent();
	if( textoActual.length > 0 ) {
		var textoActualFormat = tinyMCE.activeEditor.getContent({format : 'raw'});
		calcCalidadDescripcion(textoActualFormat);
	}
}

function cargaZonas()
{
	jQuery('#zonas').parents('.required').removeClass('error');
	jQuery('#zonas').html('<small class="edLoading" style="width:115px">Cargando...</small>');
    jQuery('#zonas').load("e_zonas.ngmf?pais="+jQuery('#PAIS').val()+"&traduccion="+escape(traducir('ZGEO')));
}
function cargarPuesto() {	
	jQuery('#PUESTOS').html('<small class="edLoading">Cargando...</small>');
    jQuery('#PUESTOS').load("comboAreasGlobales.class.ngmf?puesto="+jQuery('#TITULOPUESTO').val());   
}
function cargarAreas() {
	jQuery('#PUESTOS').html('<small class="edLoading">Cargando...</small>');
    jQuery('#PUESTOS').load("comboAreasGlobales.class.ngmf?puesto="+jQuery('#TITULOPUESTO').val());   
}
function cargarAreaPuesto(idpuesto){
	idpuesto = idpuesto === undefined ? false : idpuesto;
	jQuery('#AREAS').parents('.required').removeClass('error');
	jQuery('#AREAS').html('<small class="edLoading">Cargando...</small>');
	jQuery('#OFICIOS').html('<small class="edLoading">Cargando...</small>');
	jQuery('#OFICIOS').load("e_areasglobales.ngmf?categoria="+escape(jQuery('#CATEGORIA').val()), 
								function(){
											jQuery('#AREA').change(function(){actualizarPostulometro();});								
											jQuery('#AREA').removeClass('input_carga');
											jQuery('#OFICIO').removeClass('input_carga');
											jQuery('#CATEGORIA').removeClass('input_carga');
										});
}
function changeComboAreaGlobal() {
	var x=jQuery('#TITULOPUESTO').val();
	if(x.length){
		jQuery('#CATEGORIAS').parents('.required').removeClass("error");
		jQuery('#CATEGORIAS').html('<small class="edLoading">Cargando...</small>');
		jQuery('#AREAS').parents('.required').removeClass("error");
		jQuery('#AREAS').html('<small class="edLoading">Cargando...</small>');
		jQuery('#OFICIOS').html('<small class="edLoading">Cargando...</small>');
		jQuery('#CATEGORIAS').load("e_areasglobales.ngmf?titulo="+escape(jQuery('#TITULOPUESTO').val()),
										function(){
											jQuery('#AREA').change(function(){actualizarPostulometro();});								
											jQuery('#AREA').removeClass('input_carga');
											jQuery('#OFICIO').removeClass('input_carga');
											jQuery('#CATEGORIA').removeClass('input_carga');
										});
	}
}	

//attacheo al combo de areas la actualizacion del postulometro
jQuery(document).ready(function(){jQuery('#AREA').change(function(){actualizarPostulometro();});});

function changeCombos(){
	cargaZonas();
    cargaZonasCiudades();
    mostrarOpcionesEcuador();
	//jQuery('#planes').html('<IMG style="BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BORDER-BOTTOM-STYLE: none"  alt=""  src="/images/ajax-loader.gif">');
    //jQuery('#planes').load("e_planes.ngmf?pais="+jQuery('#PAIS').val()+"&traduccion="+escape(traducir('PLAN')), '');	    
}
//funcion que determina cual es la moneda del pais a donde va estar publicado el país,
//esto es porque tenemos algunas empresas que publican en paises distintos a su origen 
function moneda_de_pais_de_publicacion(){
	if (jQuery('#PAIS').val()==13){
		jQuery('#MONEDADESDE').html('desde Bs. F.');
		jQuery('#MONEDAHASTA').html('hasta BS. F.');
		
	}
	else{
		jQuery('#MONEDADESDE').html('desde $');
		jQuery('#MONEDAHASTA').html('hasta $');
	}
}


function mostrarOpcionesEcuador(){
    var idPaisEcuador = 9;

    if(jQuery('#PAIS').val() == idPaisEcuador){
        jQuery('#descCorporativos').css('display','block');
        jQuery('#descDiscapacidad').css('display','block');
        jQuery('#descPortalesEspeciales').css('display','block');
    }else{
        jQuery('#descCorporativos').css('display','none');
        jQuery('#descDiscapacidad').css('display','none');
        jQuery('#descPortalesEspeciales').css('display','none');
    }
    $('#ZONAGEOGRAFICA').focus();
}

function cargaZonasCiudades(){
    jQuery('#zonas_ciudades').html('<small class="edLoading" style="width:115px">Cargando...</small>');
	jQuery('#zonas_ciudades').load("e_zonas_ciudades.ngmf?zona="+jQuery('#ZONAGEOGRAFICA').val()+"&traduccion="+escape(traducir('ZGEO')));
}

function cargarNombreOficio(){
	var id=document.getElementById('OFICIO').selectedIndex;
	document.getElementById('OFICIODENOMINACIONES').value=document.getElementById('OFICIO').options[id].text;
	
	//actualizo el postulometro
	actualizarPostulometro();
}

//Control de nombre de empresa
function managePublicarNombreEmp()
{
	jQuery('#NOMBREALT').hide();
	return true;
}

jQuery(document).ready(function() {
	switch($("input[name='DESEA']:checked").attr('id'))
	{
		case 'pubNom':
			managePublicarNombreEmp();
		break;
		case 'pubNada':
			manageNoPublicarNombreEmp();
		break;
		case 'pubDesc':
			managePublicarNombreEmpAlt();
		break;
	}
});

function manageNoPublicarNombreEmp()
{
	//vacio el nombre alternativo y lo oculto
	jQuery('#NOMBREALT').val(''); 
	jQuery('#NOMBREALT').hide();
	return true;
}
function managePublicarNombreEmpAlt()
{
	jQuery('#NOMBREALT').show();
	return true;
}

//Control de Cvs por Email
function manageNoRecibirPorMail()
{
	jQuery('.criterios').hide();
	return true;
}
function manageRecibirPorMail()
{
	jQuery('.criterios').hide();
	return true;
}
function manageRecibirPorMailCondicion()
{
	jQuery('.criterios').show();
	return true;
}


function descripcion_HandleEvent(e)
{
	if(e.type == 'keydown' || e.type == 'click')
	{
		//saco el mensaje de error
		jQuery('#DESCRIPCION_CHECK').parents('.required').removeClass('error');
		//pongo el formulario como dirty
		setDirty(); 
	}
	//alert(e.type)
	return true;
}

//desplegable de filtros de mail
jQuery(document).ready(function() {
	// Expand only the active menu, which is determined by the class name
	jQuery(".desplegable > li > a.desplegado ").find("+ ul").slideToggle("medium");

	// Toggle the selected menu's class and expand or collapse the menu
	jQuery(".desplegable > li > a").click(function() {
		jQuery(this).toggleClass("desplegado").find("+ ul").slideToggle("medium");
		return false;
	});
});

//desplegable de avisos anteriores y similares
function activarDesplegables(idParent)
{
	// Expand only the active menu, which is determined by the class name
	jQuery("#"+idParent+" .desplegableAvisos > li > a.desplegado ").find("+ span").slideToggle("medium");

	// Toggle the selected menu's class and expand or collapse the menu
	jQuery("#"+idParent+" .desplegableAvisos > li > a").click(function() {
		jQuery(this).find("+ span").slideToggle( "medium" );
		jQuery(this).parent().toggleClass("desplegado"); 		
		return false;
	});
}

jQuery(document).ready(function() {
	activarDesplegables('divModelosAvisos');
	
	//agrego funcionalidad al link de copiar texto del aviso
	jQuery(".linkCopiarAviso").click(function() {
		return copyTextFromPreviousPosting(this);
	});
});

function copyTextFromPreviousPosting(object)
{
	var textoActual = tinyMCE.activeEditor.getContent();
	//si ya tenia algo escrito, pido confirmacion antes de pisarselo
	if( textoActual.length <= 0 || ( textoActual.length > 0 && confirm("Esta seguro que desea reemplazar el texto del aviso?") ) )
	{
		var texto = jQuery(object).parent().find("span").html();			
		texto = html_entity_decode(texto);
		tinyMCE.activeEditor.setContent(texto); //reemplazo el texto
		calcCalidadDescripcion(texto); //recalculo la calidad
	}
	return false;
}

function copyTextFromSimilarPosting()
{
	var textoActual = tinyMCE.activeEditor.getContent();
	//si ya tenia algo escrito, pido confirmacion antes de pisarselo
	if( textoActual.length <= 0 || ( textoActual.length > 0 && confirm("Esta seguro que desea reemplazar el texto del aviso?") ) )
	{
		var texto = jQuery('#divCajaAvisosSimilares').find('#divTextoSimilar').html();			
		texto = html_entity_decode(texto);
		tinyMCE.activeEditor.setContent(texto); //reemplazo el texto
		calcCalidadDescripcion(texto); //recalculo la calidad
		closeSimilarPopUp();
	}
	return false;
}

function closeSimilarPopUp()
{
	removeGreyCover();
	$('#divCajaAvisosSimilares').hide();
	
	return false;
}

// Acción para cambiar pais de publicacion
$(document).ready(function() {
	$('#PAIS').change(function() {
		changeCountryPosting();
		return false;
	});
});
//

//Ejecutamos los avisos similares si estamos editando un posting
jQuery(document).ready(function() {
	if($("#TITULOPUESTO").val() != "")
	{
		refreshSimilarsPostings();
	}
});
//

//Actualizar los avisos similares
function refreshSimilarsPostings()
{
	jQuery('#divModelosAvisosSimilares').html('<small class="edLoading" style="border-width:0px; color: #ffffff;">Cargando...</small>');
	// now if I join our inputs using '&' we'll have a query string
	var ajax_timeout;
	var req = jQuery.ajax({
		type: "POST",
		data: "data="+$("#TITULOPUESTO").val(),
		url: 'e_editorial_avisos_similares.ngmf',
		success: function(r) {
		  	if(ajax_timeout) {
		      clearTimeout(ajax_timeout);
		    }
		  	jQuery('#divModelosAvisosSimilares').html(r);
		}
	});

	// Wait for 15 seconds
	ajax_timeout = setTimeout(function(){
	  // If the request is still running, abort it.
	  if ( req ) req.abort();
	}, 15000);
	return false;
}

function showPreviewSimilarPostings(idPosting)
{
	$('#divLinkCopyText').html(''); //Sacamos link de copiar
	createGreyCover();
	$('#divCajaAvisosSimilares').show();
	
	jQuery('#divCajaAvisosSimilares').find('#divTextoSimilar').html('<small class="edLoading" style="border-width:0px; color: #ffffff;">Cargando...</small>');
	
	if(typeof reqSimilarPosting != 'undefined')
	{
		reqSimilarPosting.abort();
		reqSimilarPosting = '';
	}
	if(typeof timeoutSimilarPosting != 'undefined')
	{	
		if(timeoutSimilarPosting) {
		      clearTimeout(timeoutSimilarPosting);
		}
	}
	
	reqSimilarPosting = jQuery.ajax({
		type: "POST",
		data: "IDAVISO="+idPosting,
		url: 'e_preview_texto_similar.ngmf',
		success: function(r) {
		  	if(timeoutSimilarPosting) {
		      clearTimeout(timeoutSimilarPosting);
		    }
		  	jQuery('#divCajaAvisosSimilares').find('#divTextoSimilar').html(r);
		}
	});
	
	jQuery('#divCajaAvisosSimilares').find("#linkCerrarSimilar").click(function() {
		reqSimilarPosting.abort();
	});
	
	// Wait for 15 seconds
	timeoutSimilarPosting = setTimeout(function(){
	  // If the request is still running, abort it.
		if ( reqSimilarPosting )
		{
			reqSimilarPosting.abort();
		} 
		jQuery('#divCajaAvisosSimilares').find('#divTextoSimilar').html(jQuery('#avisoSimilarError').html());
	}, 15000);
	return false;
}
/* end eda_tabdescr.js *//* eda_tabdetalle.js */
function changeTypeQuestion(object, name)
{
	var parent = $(object).parents('#'+name).find('#preguntaContenido');
	var element = null;
	var num_question = $(object).parents('#'+name).find('#numeroPregunta').val();
	var old_class = '';
	switch($(object).val())
	{
		case '0':
			element = cloneElement($('#contenidosModelo').find('#tipoNueva'));
			setQuestionNames(element, num_question, '0');
		break;
		case '1':
			element = cloneElement($('#contenidosModelo').find('#tipoAbierta'));
			setQuestionNames(element, num_question, '1');
		break;
		case '2':
			element = cloneElement($('#contenidosModelo').find('#tipoChoice'));
			setQuestionNames(element, num_question, '2');
		break;
		case '4':
			element = cloneElement($('#contenidosModelo').find('#tipoNivel'));
			setQuestionNames(element, num_question, '4');
		break;
	}
	
	if(element != null)
	{
		old_class = parent.find('*').attr('class'); // Copiamos la clase anterior asi sabemos si tiene first o no
		parent.find('*').remove();
		element.attr('class', old_class);
		appendElement(parent, element);
	}
	
	return false;
}

function addQuestion()
{
	var element = $('#preguntaModelo');
	var element2 = $('#contenidosModelo #tipoNueva');
	var clon = cloneElement(element); //Clonamos el objeto pregunta a partir del modelo oculto
	var clonTipoNueva = cloneElement(element2);
	var parent = element.parent(); //Guardamos el objeto donde haremos el append de la nueva pregunta
	var num_question = parseInt($('#cantidadPreguntas').val()) + 1;
	$('#cantidadPreguntas').val(num_question);

	clon.find('#numeroPregunta').val(num_question);
	
	clon.find("#preguntaContenido").append(clonTipoNueva);
	
	setQuestionNames(clonTipoNueva, num_question, '0');

	if($('#preguntaFirst').val() == 'first') //Si es la primera pregunta agregamos la clase first para el borde de arriba
	{
		addFirstClass(clon);
		$('#preguntaFirst').val('');
	}
	appendElement(parent, clon);
	
	return false;
}

function addFirstClass(object)
{
	object.find('#preguntaContenido').find('*').addClass('first');
}

function setQuestionNames(object, num_question, type)
{
	switch (type)
	{
		case '0':
			object.find('#tipoPregunta').attr('name','tipoPregunta_'+num_question);
		break;
		case '1':
			object.find('#tipoPregunta').attr('name','tipoPregunta_'+num_question);
			object.find('#TEXTO_ABIERTA').attr('name','TEXTO_ABIERTA_'+num_question);
		break;
		case '2':
			object.find('#tipoPregunta').attr('name','tipoPregunta_'+num_question);
			object.find('#TEXTO_MC').attr('name','TEXTO_MC_'+num_question);
			object.find('#cantidadRespuestas').attr('name','cantidadRespuestas_'+num_question);
			object.find('#respuestaChoicePrimera').find('#TEXTO_OPCION').attr('name','TEXTO_OPCION_'+num_question+'_1');
			object.find('#respuestaChoicePrimera').find('#RADIO_OPCION').attr('name','RADIO_OPCION_'+num_question);
			object.find('#respuestaChoicePrimera').find('#cantidadRespuestas').attr('name','numeroRespuesta_'+num_question+'[]');
			object.find('#respuestaChoiceModelo').find('#TEXTO_OPCION').attr('name','TEXTO_OPCION_'+num_question+'_');
			object.find('#respuestaChoiceModelo').find('#RADIO_OPCION').attr('name','RADIO_OPCION_'+num_question);
			object.find('#respuestaChoiceModelo').find('#cantidadRespuestas').attr('name','numeroRespuesta_'+num_question+'[]');
		break;
		case '4':
			object.find('#tipoPregunta').attr('name','tipoPregunta_'+num_question);
			object.find('#TEXTO_NIVEL').attr('name','TEXTO_NIVEL_'+num_question);
			object.find('#NIVEL_EXP').attr('name','NIVEL_EXP_'+num_question);
			object.find('#ANOS').attr('name','ANOS_'+num_question);
			object.find('#ULTIMA').attr('name','ULTIMA_'+num_question);
			object.find('#IMPORTANCIA').attr('name','IMPORTANCIA_'+num_question);
		break;
	}
}

function deleteQuestion(ubicationObject)
{
	var element = $(ubicationObject).parents('#pregunta');
	
	if ($('#preguntas').find('#preguntaGuardada').length == 0)
	{
		/*Averiguamos si el que vamos a eliminar es el primero asi agregamos la clase first al que está segundo, esto es necesario
		si no hay cargadas preguntas guardadas con anterioridad*/
		var first;
		var second;
		$('body').find('#pregunta .numeroPregunta').each(
			function(i)
			{
				if(i == 0)
				{
					first =  $(this);
				}
				if(i == 1)
				{
					second = $(this);
				}
			}
		);
		
		if(element.find('#numeroPregunta').val() == first.val() && second != null)
		{
			deleteElement(element,  function(){addFirstClass(second.parents('#pregunta')); element.remove();});
		}
		else if (second == null)
		{
			deleteElement(element,  function(){$('#preguntaFirst').val('first'); element.remove();});
		}
		else
		{
			deleteElement(element);
		}
	}
	else
	{
		deleteElement(element);
	}
	
	return false;
}

function addChoiceAnswer(ubicationObject)
{
	var element = $(ubicationObject).parents('#pregunta').find('#respuestaChoiceModelo');
	var clon = cloneElement(element); //Clonamos el objeto respuesta choice a partir del modelo oculto

	var num_answers = parseInt(element.parents('#respuestasChoice').find('#cantidadRespuestas').val()) + 1;

	element.parents('#respuestasChoice').find('#cantidadRespuestas').val(num_answers);

	setChoiceAnswerNames(clon, num_answers);
	
	clon.find('#numeroRespuesta').val(num_answers);
	clon.find('#orden_respuesta').html(num_answers);
	
	var parent = $(ubicationObject).parents('#pregunta').find('#respuestasChoice'); //Guardamos el objeto donde haremos el append de la nueva respuesta choice
	appendElement(parent, clon);
	
	return false;
}

function setChoiceAnswerNames(object, num_answer)
{
	object.find('#TEXTO_OPCION').attr('name', object.find('#TEXTO_OPCION').attr('name') + num_answer);
	object.find('#RADIO_OPCION').val(num_answer);
}

function deleteChoiceAnswer(ubicationObject)
{
	var element = $(ubicationObject).parents('#respuestaChoice');
	deleteElement(element, function(){reorderAnswers(ubicationObject); element.remove();});
	
	return false;
}

function reorderAnswers(ubicationObject)
{
	var element = $(ubicationObject).parents('#respuestaChoice');
	var num_answers = $(ubicationObject).parents('#pregunta').find('#cantidadRespuestas').val();
	var num_delete = parseInt(element.find('#numeroRespuesta').val());

	if (num_delete < num_answers)
	//Si no es la última respuesta tenemos que restar 1 a los números de las respuestas posteriores
	{
		$(ubicationObject).parents('#pregunta').find('#respuestasChoice > p').each(
			function(i)
			{
				var num = parseInt($(this).find('#numeroRespuesta').val());
				if(num_delete < num)
				{
					$(this).find('#orden_respuesta').html(num - 1);
					$(this).find('#numeroRespuesta').val(num-1);
					var vec = $(this).find('#TEXTO_OPCION').attr('name').split("_");
					$(this).find('#TEXTO_OPCION').attr('name', 'TEXTO_OPCION_'+vec[2]+'_'+(num - 1));
					$(this).find('#RADIO_OPCION').val(num - 1);
				}
			}
		)
	}

	$(ubicationObject).parents('#pregunta').find('#cantidadRespuestas').val(parseInt($(ubicationObject).parents('#pregunta').find('#cantidadRespuestas').val())-1);
	
	if(element.find('#RADIO_OPCION').attr('checked'))
	{
		$(ubicationObject).parents('#pregunta').find('#respuestaChoicePrimera > #RADIO_OPCION').attr('checked','checked');
	}
}

function changeGreetingText(object)
{
	var text = $('#AGRADECIMIENTO');
	
	switch($(object).val())
	{
		case "0":
			text.val('');
			text.attr('disabled', 'disabled');
			text.addClass('disabledField');
		break;
		case "1":
			text.val('');
			text.removeAttr('disabled');
			text.removeClass('disabledField');
		break;
		case "2":
			text.val($('#texto_agradecimiento_1').html());
			text.removeAttr('disabled');
			text.removeClass('disabledField');
		break;
		case "3":
			text.val($('#texto_agradecimiento_2').html());
			text.removeAttr('disabled');
			text.removeClass('disabledField');
		break;
		case "4":
			text.val($('#texto_agradecimiento_3').html());
			text.removeAttr('disabled');
			text.removeClass('disabledField');
		break;
		case "5":
			text.val($('#texto_agradecimiento_4').html());
			text.removeAttr('disabled');
			text.removeClass('disabledField');
		break;
	}
	
	return false;
}

//Control de tipo de trabajo
function manageChangePrimerEmpleo()
{
	var oTipoDeTrabajo = jQuery('#TIPODETRABAJO');
	if(jQuery('#PRIMEREMPLEO').attr('checked'))
	{		
		oTipoDeTrabajo.addClass('disabledField');
		oTipoDeTrabajo.attr("disabled", "disabled");
	}
	else
	{
		oTipoDeTrabajo.removeClass('disabledField');
		oTipoDeTrabajo.removeAttr("disabled");
	}
	return true;
} 
/* end eda_tabdetalle.js *//* eda_tablogo.js */
//Logo
function loadNewLogo()
{
	jQuery('#logoOpciones').hide();
	jQuery('#logoCarga').show();
	return false;
}

function cancelLoadNewLogo()
{
	jQuery('#logoCarga').hide();
	jQuery('#logoOpciones').show();
	return false;
}

function cancelCropNewLogo()
{
	jQuery('#logoCrop').hide();
	jQuery('#logoOpciones').show();
	jQuery('#images_logos').show();
	return false;
}

function uploadLogoFileToCrop()
{
	//muestro el loading
	jQuery('#LOGOSUBIR').hide();
	jQuery('#LOGOVOLVER').hide();
	jQuery('#disyuncionSubirCancelar').hide();
	jQuery('#loadingSubirLogo').show();

	//subo el archivo
	jQuery.ajaxFileUpload
	(
		{
			url:'e_modificarlogo_crop.ngmf?accion=upload&idImage='+jQuery('#idImage').val(), 
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: "json",
			success: function (data, status)
			{						
				if(data == '1')
				{
					//Reseteamos valores del crop
					jQuery('#x').val(0);
					jQuery('#y').val(0);
					jQuery('#w').val(0);
					jQuery('#h').val(0);
					//Ocultamos los divs de carga y logos
					jQuery('#logoCarga').hide();
					jQuery('#images_logos').hide();
					//Actualizamos imagenes en pantalla
					var Digital = new Date();
					jQuery('#image_crop').attr('src',jQuery('#image_crop').attr('src').replace(/cb=([0-9])*/, 'cb='+Digital.getHours()+Digital.getMinutes()+Digital.getSeconds()));
					jQuery('#logo_preview_big').attr('src',jQuery('#logo_preview_big').attr('src').replace(/cb=([0-9])*/, 'cb='+Digital.getHours()+Digital.getMinutes()+Digital.getSeconds()));
					//Inicializamos las imagenes de preview
					jQuery('#logo_preview_big').css({
						width: '0px',
						height: '0px',
						marginLeft: '-' + '0px',
						marginTop: '-' + '0px'
					});
					//
					jQuery('#image_crop').load(function (){
						//Eliminamos Jcrop anterior
						jQuery('.jcrop-holder').remove();
						jQuery.Jcrop('#image_crop').destroy();
						//Creamos nuevo Jcrop
						jQuery('#logoCrop').show();
						jQuery.Jcrop('#image_crop').setOptions({
							aspectRatio: (66/29),
							onChange: updateCrop,
							onSelect: updateCrop,
							bgColor: 'white',
							allowResize: true
						});
					});
				}
				else
				{
					// TODO: Cambiar el alert por un mensaje
					alert('Formato y/o tamaño no válido.');
				}
				jQuery('#LOGOSUBIR').show();
				jQuery('#LOGOVOLVER').show();
				jQuery('#disyuncionSubirCancelar').show();
				jQuery('#loadingSubirLogo').hide();
			},
			error : function(data, status, e)
			{
				jQuery('#LOGOSUBIR').show();
				jQuery('#LOGOVOLVER').show();
				jQuery('#disyuncionSubirCancelar').show();
				jQuery('#loadingSubirLogo').hide();
				alert("Ocurrió un error al subir la imagen.\nPor favor inténtelo nuevamente con una imagen más pequeña. Ancho Máximo 1500px."); 	
			}
		}
	);
	jQuery('#fileToUpload').val('');
	return false;
}
function updateCrop(c)
{
	jQuery('#x').val(c.x);
	jQuery('#y').val(c.y);
	jQuery('#w').val(c.w);
	jQuery('#h').val(c.h);
	
	if (parseInt(c.w) > 0)
	{
		var rx = 128 / c.w;
		var ry = 56 / c.h;

		jQuery('#logo_preview_big').css({
			width: Math.round(rx * jQuery('#image_crop').attr('width')) + 'px',
			height: Math.round(ry * jQuery('#image_crop').attr('height')) + 'px',
			marginLeft: '-' + Math.round(rx * c.x) + 'px',
			marginTop: '-' + Math.round(ry * c.y) + 'px'
		});
		
		rx = 66 / c.w;
		ry = 29 / c.h;
		
		jQuery('#logo_preview_small').css({
			width: Math.round(rx * jQuery('#image_crop').attr('width')) + 'px',
			height: Math.round(ry * jQuery('#image_crop').attr('height')) + 'px',
			marginLeft: '-' + Math.round(rx * c.x) + 'px',
			marginTop: '-' + Math.round(ry * c.y) + 'px'
		});
	}
}

function uploadLogoFile(idempresa)
{
	if (!parseInt($('#w').val()))
	{
		//TODO: Cambiar mensaje
		alert('Debe seleccionar una región');  
	}
	else
	{
		jQuery("#loading").ajaxStart(function(){
			$('#logoEmpBig').html('<small class="edLoading">Cargando...</small>');
			$('#logoEmpSmall').html('<small class="edLoading">Cargando...</small>');
		});
		
		var sAccion = isLoggedEmpresa() ? 'crop' : 'cropTmp'; 
		
		jQuery.ajaxFileUpload
		(
			{
				url:'e_modificarlogo_crop.ngmf?accion='+sAccion+'&idImage='+jQuery('#idImage').val()+'&x='+$('#x').val()+'&y='+$('#y').val()+'&w='+$('#w').val()+'&h='+$('#h').val(), 
				secureuri:false,
				fileElementId:'fileToUpload',			
				success: function (data, status)
				{				
					if(jQuery('#logoEmpBig').size() == 0 && jQuery('#logoEmpSmall').size() == 0){
						$('#logoEmpBig').html();
						$('#logoEmpSmall').html();
					}else{
						var Digital=new Date();						
						jQuery('#logoEmpBig').attr('src', '/empresas/images/logos_empresas/tmp/logoCropped_' + jQuery('#idImage').val() + '.gif?cb='+Digital.getHours()+Digital.getMinutes()+Digital.getSeconds());
					}				
				}
			}
		);
		jQuery('#fileToUpload').val('');
		jQuery('#logoCrop').hide();
		jQuery('#logoOpciones').show();
		$('#images_logos').show();
	}
	return false;
}

function deleteLogoFile()
{
	return false;
}
//

// Vista Previa Video
function previewVideo()
{
	jQuery('#mensajeVideoPreview').hide();
	jQuery('#errorVideoPreview').hide();
	jQuery('#mostrarVideoPreview').html('<small class="edLoading" style="border-width:0px; color: #ffffff;">Cargando...</small>');
	jQuery('#mostrarVideoPreview').show();
	// now if I join our inputs using '&' we'll have a query string
	var ajax_timeout;
	var req = jQuery.ajax({
		type: "POST",
		data: "url_video="+$("#VIDEO_AVISO").val(),
		url: 'e_videopreview.ngmf',
		success: function(r) {
		  	if(ajax_timeout) {
		      clearTimeout(ajax_timeout);
		    }
		  	jQuery('#mostrarVideoPreview').html(r);
		}
	});

	// Wait for 20 seconds
	ajax_timeout = setTimeout(function(){
	  // If the request is still running, abort it.
	  if ( req ) req.abort();
	  jQuery('#mensajeVideoPreview').hide();
	  jQuery('#mostrarVideoPreview').hide();
	  jQuery('#errorVideoPreview').show();
	}, 20000);
	return false;
}

function deletePreviewVideo()
{
	jQuery('#VIDEO_AVISO').val('');
	jQuery('#ELIMINARVIDEO').hide();
	jQuery('#mostrarVideoPreview').hide();
	jQuery('#errorVideoPreview').hide();
	jQuery('#mensajeVideoPreview').show();
	return false;
}
//

//Mensajes a cargar cuando entramos a la pestaña de Logo, Video, Mapa
$(document).ready(function() {
	jQuery('#tabsMain').bind('tabsshow', function(event, ui){	
		if($('#tabsMain').tabs('option', 'selected') == 3)
		{
			if($("input[name='PLANPUBLICACION']:checked").attr('id') == 'plnHome')
			{
				$('#alertVideoHome').hide();
				$('#VIDEOSUBMIT').show();
				$('#VIDEO_AVISO').removeAttr('disabled');
				$('#VIDEO_AVISO').removeClass('disabledField');
			}
			else
			{
				$('#alertVideoHome').show();
				$('#VIDEO_AVISO').attr('disabled', 'disabled');
				$('#VIDEO_AVISO').addClass('disabledField');
				$('#VIDEOSUBMIT').hide();
				//Lo siguiente es casi igual que la función deletePreviewVideo, sólo que no quiero borrar el contenido del texto del video
				jQuery('#ELIMINARVIDEO').hide();
				jQuery('#mostrarVideoPreview').hide();
				jQuery('#errorVideoPreview').hide();
				jQuery('#mensajeVideoPreview').show();
			}
		}
	});
});

var map = {
	noList: false,
	notFound: "",
	calle: "",
	lat: 8.537981,
	lng: -80.782127,
	
	list: {
		toggle: function (hide) {
			$("#direccionSelect").parent().toggle(!hide);
		},
		
		clear: function () {
			$("#direccionSelect li:not(.template)").remove();
		},
		
		add: function (i, iconUrl, addressParts, onClick) {
			var newItem = $("#direccionSelect li.template").clone().
				appendTo("#direccionSelect").addClass(i % 2 ? "" : "odd").removeClass("template");
			newItem.find("img").attr("src", iconUrl);
			newItem.find("a").text(addressParts.shift()).click(onClick);
			newItem.find("span").text(addressParts.join(", ") || "...");
		}
	},
	
	setValues: function (values) {
		$.each(values, function (i) { $("#MAPA"+i.toUpperCase()).val(map[i] = values[i]); });
	},
	
	toggleDisabled: function () {
		disabled = $("#noUsaMapa").attr("checked");
		$("#MAPACALLE, #MAPALAT, #MAPALNG, #MAPASUBMIT").attr("disabled", disabled);
		$("#MAPACALLE")[disabled ? "addClass" : "removeClass"]("disabledField");
		$("#mapaDisable").toggle(disabled);
		$("#errorMapaWrapper").toggle(!disabled);
		this.list.toggle(disabled || this.notFound || this.noList);
	},
	
	searchLocation: function () {
		this.noList = false;
		this.calle = $("#MAPACALLE").val();
		this.geocoder.getLocations(this.calle, function (response) { map.listAddresses(response); });
	},
	
	toggleNotFound: function (notFound) {
		if (this.notFound === notFound) return;
		this.notFound = notFound;
		$("#errorMapaWrapper")[notFound ? "addClass" : "removeClass"]("error");
		if (notFound)
			this.setValues({lat: null, lng: null});
		this.list.toggle(notFound);
		this.mapControl.setZoom(notFound ? 2 : 15);
	},
	
	selectAddress: function (i, address) {
		var latlng = this.markers[i].getLatLng();
		this.mapControl.setCenter(latlng);
		this.setValues({calle: address, lat: latlng.lat(), lng: latlng.lng()});
		$("#direccionSelect li").removeClass("selected");
		$("#direccionSelect li:nth-child("+(i + 2)+")").addClass("selected");
	},
	
	listAddresses: function (response) {
		this.mapControl.clearOverlays();
		this.markers = [];
		this.list.clear();
		var success = (response && response.Status.code == 200);
		this.toggleNotFound(!success);
		if (success)
			$(response.Placemark).each(function (i, place) {
				var letter = String.fromCharCode("A".charCodeAt(0) + i);
				var address = place.address;
				var click = function () { map.selectAddress(i, address); };
				var letteredIcon = new GIcon(G_DEFAULT_ICON);
				letteredIcon.image = "http://www.google.com/mapfiles/marker"+letter+".png";
				map.markers[i] = new GMarker(new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]), {icon: letteredIcon});
				GEvent.addListener(map.markers[i], "click", click);
				map.mapControl.addOverlay(map.markers[i]);
				map.list.add(i, letteredIcon.image, address.split(", "), click);
				if (i == 0)
					click();
			});
	}
};
function loadMap() {
	if (!GBrowserIsCompatible()) return;
	var hasDefLatLng = (!!parseFloat($("#MAPALAT").val()) || !!parseFloat($("#MAPALNG").val()));
	if (hasDefLatLng) {
		map.lat = parseFloat($("#MAPALAT").val());
		map.lng = parseFloat($("#MAPALNG").val());
	}
	map.mapControl = new GMap2(document.getElementById("mapaPreview"), {size: new GSize(350, 300)});
	var latlng = new GLatLng(map.lat, map.lng);
	map.mapControl.setCenter(latlng, hasDefLatLng ? 15 : 2);
	var mapOptions = map.mapControl.getDefaultUI();
	mapOptions.controls.menumaptypecontrol = false;
	map.mapControl.setUI(mapOptions);
	map.geocoder = new GClientGeocoder();
	map.list.toggle(true);
	$("body").unload(GUnload);
	
	if (hasDefLatLng) {
		map.mapControl.addOverlay(new GMarker(latlng));
		map.noList = true;
	} else if ($("#MAPACALLE").val()) {
		map.searchLocation();
	} else {
		$("#noUsaMapa").attr("checked", true);
		map.toggleNotFound(true);
		map.toggleDisabled();
	}
	
	$("#MAPACALLE").keypress(function (e) {
		if (e.which == 13) {
			map.searchLocation();
			return false;
		}
	});
	
	$("#noUsaMapa, #lblNoUsaMapa")[jQuery.browser.msie ? "click" : "change"](function () { map.toggleDisabled(); });
	$("#MAPASUBMIT").click(function () { map.searchLocation(); });
	
	$("#ALTA").click(function () {
		if ($("input[name=PLANPUBLICACION]:checked").val() == 90) {
			$("#noUsaMapa").attr("checked", true);
			map.toggleDisabled();
		}
	});
	
	setTimeout('jQuery("#mapaPreview span").css("white-space", "normal");', 5000);
}

$(function () {
	var googleMapsKey = $("#MAPA_API_KEY").val();
	$.getScript("http://maps.google.com/maps?file=api&v=2&key="+googleMapsKey+"&sensor=false&async=2&callback=loadMap");
	$('#link_alert_video_home').click(function() {
		$('#tabsMain').tabs('select', 1);
		return false;
	});	
});
/* end eda_tablogo.js *//* eda_tabaviso.js */
//Vista Previa
function showPreview(){
	var NOMBRE_EMP_ALT = $('#NOMBREALT').val();
	var IDPAIS = $('#PAIS').val();	
	var CIUDAD = $('#CIUDAD').val();
	var Z_DESC = (jQuery('#ZONAGEOGRAFICA').val() > 0) ? jQuery('#ZONAGEOGRAFICA').find('option:selected').html() : '';
	var PAI_DEN = (jQuery('#PAIS').val() > 0) ? jQuery('#PAIS').find('option:selected').html() : '';
	var APARECEEMP = ($("input[name='DESEA']:checked").val() == 0)? 'true' : 'false';
	var AREA_DENO = (jQuery('#AREA').val() > 0) ? jQuery('#AREA').find('option:selected').html() : '';
	var DESCRIPCION = ($('#avisos').length) ? ( tinyMCE.activeEditor ? tinyMCE.activeEditor.getContent() : jQuery('[name=DESCRIPCION]').val() )  : CIUDAD = $('#avisoshi').val();
	var PUESTO = $('#TITULOPUESTO').val();
	var CANTIDAD_VACANTES = $('#CANTIDADVACANTES').val();
	var MINIMO = $('#MINIMO').val();
	var MAXIMO = $('#MAXIMO').val();
	var DENOMFREC = jQuery('#FRECUENCIA').find('option:selected').html();
	var NETOBRUTO = jQuery('#TIPOSALARIO').val();
	if($('#PRIMEREMPLEO').is(':checked'))
	{
		var TIPO_DEN = $('#PRIMEREMPLEO_DENO').val();
	}
	else
	{
		var TIPO_DEN = (jQuery('#TIPODETRABAJO').val() > 0) ? jQuery('#TIPODETRABAJO').find('option:selected').html() : '';
	}
	var SEXO = $("input[name='CBSEXO']:checked").val();
	var PLANPUBLICACION = $("input[name='PLANPUBLICACION']:checked").val();
	var DESCRIPCION = escape(DESCRIPCION);
	DESCRIPCION = DESCRIPCION.replace(/\+/g, '%2b');
	var VIDEO_AVISO = $('#VIDEO_AVISO').val();
	var MAPACALLE = $("#MAPACALLE").val();
	var MAPALAT = $("#MAPALAT").val();
	var MAPALNG = $("#MAPALNG").val();

	jQuery('.avisoPreview').html('<IMG alt="Cargando..." src="/images/avisos/ajax-loader.gif"/>');
	// now if I join our inputs using '&' we'll have a query string
	
	if(typeof reqPreview != 'undefined')
	{
		reqPreview.abort();
		reqPreview = '';
	}
	if(typeof timeoutPreview != 'undefined')
	{	
		if(timeoutPreview) {
		      clearTimeout(timeoutPreview);
		}
	}

	var usaMapa = (!$("#noUsaMapa").attr("checked") && MAPACALLE && !!(parseFloat(MAPALAT) || parseFloat(MAPALNG)));
	reqPreview = jQuery.ajax({
		type: 'POST',
		data: 'NOMBRE_EMP_ALT='+escape(NOMBRE_EMP_ALT)
											 +'&DESCRIPCION='+DESCRIPCION
											 +'&IDPAIS='+IDPAIS
											 +'&CIUDAD='+escape(CIUDAD)
											 +'&Z_DESC='+escape(Z_DESC)
											 +'&PAI_DEN='+escape(PAI_DEN)
											 +'&APARECEEMP='+APARECEEMP
											 +'&SEXO='+SEXO
											 + ( jQuery('#logoEmpBig').attr("src").indexOf('logoCropped_') > 0 ? '&IDIMAGE='+jQuery('#idImage').val() : '' ) 
											 +'&AREA_DENO='+escape(AREA_DENO)
											 +'&IND_DENO='+escape('')
											 +'&PUESTO='+escape(PUESTO).replace(/\+/g, '%2B')
											 +'&CANTIDAD_VACANTES='+CANTIDAD_VACANTES
											 +'&MINIMO='+MINIMO
											 +'&MAXIMO='+MAXIMO
											 +'&DENOMFREC='+escape(DENOMFREC)
											 +'&NETOBRUTO='+escape(NETOBRUTO)
											 +'&TIPO_DEN='+escape(TIPO_DEN)
											 +'&PLANPUBLICACION='+PLANPUBLICACION
											 +'&VIDEO_AVISO='+VIDEO_AVISO
											 +'&UTF8_ENCODE=true'
											 +(usaMapa ?
												 '&MAPACALLE='+escape(MAPACALLE)
												 +'&MAPALAT='+escape(MAPALAT)
												 +'&MAPALNG='+escape(MAPALNG) :
												 ''),
		url: 'e_posting_preview.ngmf',
		error: function (xhr, ajaxOptions, thrownError)
		{
			try {
				idStatusRequest = xhr.status;
			}
			catch(e){
				idStatusRequest = -1;
			}
			if(idStatusRequest!=200)
			{
				var bHasBeenLostConnection = idStatusRequest==0;
				
				if(timeoutPreview) {
					clearTimeout(timeoutPreview);
				}
				
				jQuery('.avisoPreview').html('');//saco la ruedita
				
				if(bHasBeenLostConnection)
				{
					showErrorConexion('Mensaje error: ' + ajaxOptions + '. Id Status request: ' + idStatusRequest);
				}
				else
				{
					showErrorGenerico('Mensaje error: ' + ajaxOptions + '. Id Status request: ' + idStatusRequest);
				}
			}					
		},
		success: function(r) {
		  	if(timeoutPreview) {
		      clearTimeout(timeoutPreview);
		    }
		  	jQuery('.avisoPreview').html(r);
		  	if (GBrowserIsCompatible() && $("#mapa div").length) {
				var map = new GMap2($("#mapa div")[0]);
				var latlng = new GLatLng($("#MAPALAT").val() || -34.6036918, $("#MAPALNG").val() || -58.3809586);
				map.setCenter(latlng, 15);
				var mapOptions = map.getDefaultUI();
				mapOptions.controls.menumaptypecontrol = false;
				mapOptions.controls.maptypecontrol = false;
				mapOptions.zoom.scrollwheel = false;
				map.setUI(mapOptions);
				if ($("#MAPALAT").val())
					map.addOverlay(new GMarker(latlng));
			}
		}
	});

	// Wait for 15 seconds
	timeoutPreview = setTimeout(function(){
	  // If the request is still running, abort it.
	  if ( reqPreview ) reqPreview.abort();
	}, 15000);
	return false;

}

$(document).ready(function() {
	jQuery('#tabsMain').bind('tabsshow', function(event, ui){	
		if($('#tabsMain').tabs('option', 'selected') == 4)
		{
			showPreview();
		}
	});
});
/* end eda_tabaviso.js */