var loadImg = '<img  class="loadImg right" src="http://www.trabajaendattatec.com/wp-content/plugins/extend-perfil/img/ajax-loader.gif" width="16" height="11" alt="Cargando..." />';

$(document).ready(function() {

	 $('.message').append('<a class="close" href="#" title="Cerrar este mensaje ahora">Cerrar</a>');
	 $('.message .close').click(function(){
		  $(this).parent().fadeOut();
	 })

	 $('.cancelAction').click(function(){
		  $('.ui-dialog-titlebar-close').click();
	 })

	 /**
	  * Eliminar un bloque por AJAX
	  */
	 $('.deleteItem').click(function(e){
		  e.preventDefault();
		  var elLink;
		  var elBlock = $(this).parent();
		  elLink = $(this).attr('href').split('?');

		  //alert(elLink[0]);
		  //alert(elLink[1]);
		  var elMsg = '<div id="dialog-confirm" title="¿Eliminar este item?"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>¿Está seguro que desea eliminar esta información?</p></div>';

		  $(elMsg).dialog({
			   resizable: false,
			   modal: true,
			   buttons: {
					"Si, Eliminar": function() {
						 $.ajax({
							  url: elLink[0],
							  type: "GET",
							  data: elLink[1],
							  success: function(){

								   elBlock.fadeOut();
							  }
						 });
						 $( this ).dialog( "close" );
					},
					'Cancelar': function() {
						 $( this ).dialog( "close" );
					}
			   }
		  });

		  return false;
	 })



	 /**
	  * MODIFICAR un bloque por AJAX
	  */
	 $('.modyfiItem').click(function(e){
		  e.preventDefault();
		  var elLink;
		  var este = $(this);
		  var elBlock = $(this).parent();
		  elLink = $(this).attr('href').split('?');
		  este.addClass('loading');
		  //alert(elLink[0]);
		  //alert(elLink[1]);

		  $.ajax({
			   url: elLink[0],
			   type: "GET",
			   data: elLink[1],
			   success: function(data){
					$( ".ui-dialog" ).dialog( "destroy" ).remove();
					$(data).dialog({
						 modal: true,
						 width: 'auto'
					});
					este.removeClass('loading');

					if($('.en_proceso').attr('checked')){
						 $(this).click();
					}
					
					$('.en_proceso').click(function(){
						 if($(this).attr('checked'))
						 {
							  $('[name=lxo_mes_fin],[name=lxo_ano_fin]').fadeOut();
							  $('[name=lxo_mes_fin] option[value=0], [name=lxo_ano_fin] option[value=0]').attr('selected', 'selected');
							  if($(this).attr('id')== 'sigo_estudiando'){$('[name=lxo_materias_cursadas], [name=lxo_materias_total]').parent().parent().fadeIn();}

						 }
						 else{
							  $('[name=lxo_mes_fin], [name=lxo_ano_fin]').fadeIn();
							  $('[name=lxo_mes_fin] option[value=""], [name=lxo_ano_fin] option[value=""]').attr('selected', 'selected');
							  if($(this).attr('id')== 'sigo_estudiando'){$('[name=lxo_materias_cursadas], [name=lxo_materias_total]').val('0').parent().parent().fadeOut();}
						 }


					})

					if($('[name=lxo_fecha_fin]').val() == '0000-00-00'){
						 $('#fechaActual').click();
					}
					/** Recargo la pagina cuando guarda **/

					$('.cancelAction').click(function(){
						 $('.ui-dialog-titlebar-close').click();
					})
					/**
					 *
					 * GUARDAR un bloque por AJAX
					 */
					$('input.date').datepicker({
						 changeMonth: true,
						 changeYear: true,
						 dateFormat: "yy-mm-dd",
						 yearRange: '-100:c+10'
					});
					$('.saveBlock').unbind('click');

					$('.saveBlock').click(function(e){
						 e.preventDefault();
						 var elThis = $(this);
						 var elForm =  $(this).parent('form');
						 elFormDatta = elForm.serialize();

						 if(checkInputError(elThis))
						 {
							  $.ajax({
								   url: 'http://www.trabajaendattatec.com/wp-content/plugins/extend-perfil/save-update.php',
								   type: "POST",
								   data: elFormDatta,
								   beforeSend: function(){
										elThis.addClass('loading')
								   },
								   success: function()
								   {
										elThis.removeClass('loading');
										$('.ui-state-highlight').crazyShow().html('<p>Los datos fueron guardados correctamente.</p>');
										window.location.reload();
								   }
							  });
						 }
						 else{
							  $('.ui-state-highlight').crazyShow().html('<p>Asegurate de completar todos los campos, para volver hace click en "Cancelar".</p>');
						 }
						 return false;

					})

			   }
		  });

		  return false;
	 })

	 /**
	  * AGREGAR un bloque por AJAX
	  */
	 $('.addItem').click(function(e){
		  e.preventDefault();
		  var elLink;
		  var este = $(this);
		  var elBlock = $(this).parent();
		  elLink = $(this).attr('href').split('?');
		  este.addClass('loading');

		  $

		  $.ajax({
			   url: elLink[0],
			   type: "GET",
			   data: elLink[1],
			   success: function(data){
					$( "#dialog:ui-dialog" ).dialog( "destroy" );
					$(data).dialog({
						 modal: true,
						 width: 'auto'
					});
					este.removeClass('loading');

					if($('.en_proceso').attr('checked')){
						 $(this).click();
					}
					$('.en_proceso').click(function(){
						 if($(this).attr('checked'))
						 {
							  $('[name=lxo_mes_fin],[name=lxo_ano_fin]').fadeOut();
							  $('[name=lxo_mes_fin] option[value=0], [name=lxo_ano_fin] option[value=0]').attr('selected', 'selected');
							  if($(this).attr('id')== 'sigo_estudiando'){$('[name=lxo_materias_cursadas], [name=lxo_materias_total]').parent().parent().fadeIn();}

						 }
						 else{
							  $('[name=lxo_mes_fin], [name=lxo_ano_fin]').fadeIn();
							  $('[name=lxo_mes_fin] option[value=""], [name=lxo_ano_fin] option[value=""]').attr('selected', 'selected');
							  if($(this).attr('id')== 'sigo_estudiando'){$('[name=lxo_materias_cursadas], [name=lxo_materias_total]').val('0').parent().parent().fadeOut();}
						 }

					})

					/** Recargo la pagina cuando guarda **/

					$('.cancelAction').click(function(){
						 $('.ui-dialog-titlebar-close').click();
					})
					/**
					 * GUARDAR un bloque por AJAX
					 */
					$('input.date').datepicker({
						 changeMonth: true,
						 changeYear: true,
						 dateFormat: "yy-mm-dd",
						 yearRange: '-100:c+10'
					});
					$('.saveBlock').unbind('click');

					$('.saveBlock').click(function(e){
						 e.preventDefault();
						 var elThis = $(this);
						 var elForm =  $(this).parent('form');
						 elForm = elForm.serialize();
						 if(checkInputError(elThis))
						 {
							  $.ajax({
								   url: 'http://www.trabajaendattatec.com/wp-content/plugins/extend-perfil/save-update.php',
								   type: "POST",
								   data: elForm,
								   beforeSend: function(){
										elThis.addClass('loading')
								   },
								   success: function()
								   {
										elThis.removeClass('loading');
										$('.ui-state-highlight').crazyShow().html('<p>Los datos fueron guardados correctamente.</p>');
										window.location.reload();
								   }
							  });
						 }
						 else{
							  $('.ui-state-highlight').crazyShow().html('<p>Asegurate de completar todos los campos, para volver hace click en "Cancelar".</p>');
						 }
						 return false;
					})
			   }
		  });

		  return false;
	 })

      $('#exten-pais').change(function(){

            var provinciaInput = $('<input  id="exten-provincia" name="exten-provincia" class="ccv_input required"/>');
            var provinciaSelect = $('<select id="exten-provincia" disabled="disabled" name="exten-provincia_id" class="ccv_input required"> <option value="">Seleccioná primero el pais</option></select>');
          $.ajax({
               url: 'http://www.trabajaendattatec.com/wp-content/plugins/extend-perfil/get-json.php',
               type: "POST",
               data: 'iso_country='+$(this).find('option:selected').val(),
               beforeSend: function(){
                   // elThis.addClass('loading')
               },
               success: function(r)
               {
                   if(r.length <= 0)
                   {
                       $('#exten-provincia').remove();
                       provinciaInput.appendTo('#div-exten-provincia');
                   }
                   else{
                       $('#exten-provincia').remove();
                       provinciaSelect.appendTo('#div-exten-provincia');
                       $('#exten-provincia').removeAttr('disabled');
                       $('option.added').remove();

                       $.each(r, function(index,citi){
                          $('<option class="added" value="'+citi.id+'">'+citi.name+'</option>').appendTo('#exten-provincia');

                        })
                        //elThis.removeClass('loading');
                        //$('.ui-state-highlight').crazyShow().html('<p>Los datos fueron guardados correctamente.</p>');

                   }

               }
          });

    })

	 // CHEQUEA LOS CAMPOS DEL FORMULARIO DE (((PERFIL))
	 $('.button-primary').click(function()
	 {
		  if(!checkInputErrorProfile($(this)))
		  {
			   return false;
		  }
	 })




	 /**
	  * Eliminar una entrevista
	  */
	 $('.deleteIntre').click(function(e){
		  e.preventDefault();
		  var elLink;
		  var elBlock = $(this).parent().parent();
		  elLink = $(this).attr('href');

		  //alert(elLink);

		  var elMsg = '<div id="dialog-confirm" title="¿Eliminar esta entrevista?"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>¿Está seguro que desea eliminar esta información?</p></div>';

		  $(elMsg).dialog({
			   resizable: false,
			   modal: true,
			   buttons: {
					"Si, Eliminar": function() {
						 $.ajax({
							  url: elLink,
							  type: "GET",
							  success: function(){

								   elBlock.fadeOut();
							  }
						 });
						 $( this ).dialog( "close" );
					},
					'Cancelar': function() {
						 $( this ).dialog( "close" );
					}
			   }
		  });

		  return false;
	 })


	 // AÑADIR UN COMENTARIO A LA ENTREVISTA
	 $(".addComentIntre").click(function(){
		  $( "#dialog-modal" ).dialog( "destroy" );
		  var elId = $(this).attr("id");
		  $( "[name=intre-id]").val(elId);

		  $( "#dialog-modal").dialog({
			   modal: true
		  });
	 })
	 // VER EL COMENTATARIO DE UNA ENTREVISTA
	 $('.inter-comment-open').click(function(){
		  var comentId = 'd'+$(this).attr('id');
		  $( "#"+comentId).dialog({
			   modal: true
		  })
	 })

	 // AÑADIR UN COMENTARIO A EL POSTULANTE
	 $(".people-comment").click(function(){
		  $( "#add-people-comment" ).dialog( "destroy" );
		  var elId = $(this).attr("rel");
		  $( "[name=people-id]").val(elId);

		  $( "#add-people-comment").dialog({
			   modal: true
		  });
	 })
	 // VER EL COMENTATARIO DE UN POOSTULANTE
	 $('.inter-comment-open').click(function(){
		  var comentId = 'd'+$(this).attr('id');
		  $( "#"+comentId).dialog({
			   modal: true
		  })
	 })

	 $('input.date').datepicker({
		  changeMonth: true,
		  changeYear: true,
		  dateFormat: "dd-mm-yy",
		  yearRange: '-100:c+10'
	 });


	 $('a.postular').click(function(e){e.preventDefault();

		 var postulacion = $(this).attr('id').split('p');
		 //alert(postulacion[1][1]);

		 $('#postul_id').val(postulacion[1]);
		 $('.user-postulacion-create').dialog({resizable: false,
			   modal: true, width: 'auto'})


	 })

	 $('#sendUserDatta').click(function(e){
						 e.preventDefault();
						 var elThis = $(this);
						 var elForm =  $('#userDattaForm');
						 elForm = elForm.serialize();
						 idBusqueda = $('#postul_id').val();
						 //alert(elForm+' - '+idBusqueda);
						 var urlRedirect ='http://www.trabajaendattatec.com/completa-tu-c-v/?bu='+idBusqueda;

						 $(loadImg).insertAfter(elThis);
						 if(checkInputErrorSingle(elThis))
						 {
							  $.ajax({
								   url: 'http://www.trabajaendattatec.com/wp-content/plugins/extend-perfil/save-update.php',
								   type: "GET",
								   data: elForm+'&action=savePeople',
								   beforeSend: function(){
										$(loadImg).insertAfter(elThis);
								   },
								   
								   success: function(data)
								   {
										$('.loadImg').remove();
										switch(data)
											 {
												  case'1' :

													   $('#wp_exten-user_login').addClass('errorType');
													    $('.ui-state-highlight').crazyShow().html('<p>El usuario que ingresaste ya fue elegido, Seleccioná otro por favor</p>');

													   break;
												case'2':
													 $('.ui-state-highlight').crazyShow().html('<p>Error o problema al insertar los datos basicos del usuario</p>');
													 break;

												case'4':
													 $('#exten-email').addClass('errorType');
													 $('.ui-state-highlight').crazyShow().html('<p>El email ya fué registrado, ¿Olvidaste tu contraseña? hace <a href="http://www.trabajaendattatec.com/wp-login.php?action=lostpassword" title="Recuperar contraseña">click aquí</a> para recuperarla</p>');
													 break;

												case'3':
													   $.ajax({
															url: 'http://www.trabajaendattatec.com/wp-login.php',
															type: "POST",
															data: 'log='+$("#wp_exten-user_login").val()+'&pwd='+$("#wp_exten-user_pass").val(),
															beforeSend: function(){
																 $(loadImg).insertAfter(elThis);
															},
															success: function()
															{
																 //alert(urlRedirect);
																 //window.location = urlRedirect
																 $('.loadImg').remove();
																 $('.ui-state-highlight').crazyShow().html('<p>Tus datos fueron guardados, ahora serás redirigido a la pagina para la creación de tu C.V</p>');
																 //alert(urlRedirect);
																 $('#userDattaForm').attr('action', urlRedirect).submit();

															}
													   });


													 break;


											 }
										
								   }
							  });
						 }
						 else{
							  $('.loadImg').remove();
							  $('.ui-state-highlight').crazyShow().html('<p>Asegurate de completar todos los campos, para volver hace click en "Cancelar".</p>');
						 }
						 return false;
					})
});
//Fin document Ready

$('.cancelAction').click(function(){
	 $('.ui-dialog-titlebar-close').click();
})
jQuery.fn.crazyShow = function(){
    this.show().fadeOut(600).fadeIn(300).fadeOut(300).fadeIn('slow');
	return this;
}
function checkInputError(who){

	 var losImputs = who.parent('form').find('.required').not(':hidden')
	 var errors = 0;
	 losImputs.each(function(index)
	 {
		  $(this).removeClass('errorType')
		  if(/*$(this).hasClass('required') &&*/ $(this).val() == '' || $(this).val() == '0000-00-00' || $(this).val() == 'Seleccioná el pais')
		  {
			   $(this).addClass('errorType');
			   errors++;
		  }
	 })
	 if(errors > 0){
		  return false;
	 }else{
		  return true;
	 }
}

function checkInputErrorProfile(who){

	 var losImputs = $('#your-profile').find('.required').not(':hidden')
	 var errors = 0;
	 losImputs.each(function(index)
	 {
		  $(this).removeClass('errorType')
		  if($(this).val() == '' || $(this).val() == '0000-00-00' || $(this).val() == 'Seleccioná el pais')
		  {
			   $(this).addClass('errorType');
			   errors++;
		  }

	 })
	 if(errors > 0){
		  return false;
	 }else{
		  return true;
	 }
}

function checkInputErrorSingle(who){

 var losImputs = $('#userDattaForm').find('.required').not(':hidden')
	 var errors = 0;

	 var valid = true;
	 var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	 losImputs.each(function(index)
	 {
		  $(this).removeClass('errorType')
		  if($(this).val() == '' || $(this).val() == '0000-00-00' || $(this).val() == 'Seleccioná el pais' || $(this).val() == 'TIPO' || $(this).attr('name') == 'exten-email' && !filter.test($(this).val()))
		  {
			   //alert($(this).attr('name'));
			   $(this).addClass('errorType');
			   errors++;
		  }

	 })
	 if(errors > 0){
		  return false;
	 }else{
		  return true;
	 }
}

//javascript:void(location.href='http://www.sciweavers.org/iWeb2Shot?url='+escape(location.href)+'&r='%20+%20Math.random());
