$(function() {   
   $(".tiphelp").mouseover(function(){ 
		id = this.id.substring(1);		
		mostrar_over_coordenada(id);		
	})
		
    $(".tiphelp").mouseout(function(){ 
		id = this.id.substring(1);		
		closeTip(id)
	})
	
	$(".cancellation_policy").click(function(){ 
		id = this.id.substring(1); 	
		if ( $("#JT"+id).length > 0 ) closeTip(id)		
		else{
			$('.JT_class').remove();
			JT_show_cancellation_policy(id);
		}
	})
 	
	$(".info_room").click(function(){ 
		id = this.id.substring(1); 	
		if ( $("#JT"+this.id).length > 0 ) closeTip(this.id)	
		else{
			$('.JT_class').remove();		
			JT_show_info_room(id);
		}
	})
})

function initValidation (id_form)
{
		
	var correcto = true;	
	// campos requeridos
	  $("#"+id_form).find(".required:visible").each(function(i) {
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	   
	   if (valor==undefined){
	   	   mark_field(id,'required');
		   correcto = false;		
	   }else 
	   		unmark_field(id,'required');
     
	   });
	  
	// Aceptar condiciones	
	if($("#accept_cond").attr("value") != undefined && $("#accept_cond:checked").val() == null){		
		mark_field('accept_cond','required');
	   correcto = false;
	}else{
		unmark_field('accept_cond','required');
	}
	  
	// campos password iguales	  
	pasw = $("#password").attr("value");		
	repasw = $("#repassword").attr("value");		
	if(pasw != undefined && pasw != ''){
		if (pasw == repasw){
   			unmark_field('password','match_password');  		
	   }else{ 
   		   mark_field('password','match_password');
		   correcto = false;
	   }  	
	}
	   
	  
	 
	// campos email
	$("#"+id_form).find(".valid_email:visible").each(function(i) {	
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	  
	   if (valor!=undefined) {
	  if (!valor.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){
	  	mark_field(id,'valid_email');
		correcto = false;
	  }else unmark_field(id,'valid_email');
	   }
	   });
	   
	 // min length
	 $("#"+id_form).find(".min_length:visible").each(function(i) {		
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	  if (valor!=undefined) {
	  if (valor.length<6){
	  	mark_field(id,'min_length');
		correcto = false;
	  }
	   else unmark_field(id,'min_length');
	  }
	   });

	 $("#"+id_form).find(".minimum:visible").each(function(i) {			 
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	  if (valor!=undefined) {
	  	id = $(this).attr("id");
	  	fieldcomp = id.substring(0, id.indexOf('_') );
	  	
	  	valor2=$("#"+fieldcomp).attr("value");
	  
	  	if (parseInt(valor)>parseInt(valor2)){
	  	correcto = false;
	  	mark_field(id,'minimum');
		}
	   else unmark_field(id,'minimum');
	  }
	   }); 	  
	 
	 return correcto;
}

function mark_field (id, type)
{	
	$("#"+id).css("background-color", "#ffffcc");	
	$("#error_"+ id + "_" + type).show();	
}

function unmark_field (id, type)
{	
	$("#"+id).css("background-color", "#FFFFFF");
	$("#error_"+ id + "_" + type).hide();
	//$("../",id).remove("span");
}

function doPost (uri, field_name, field_value){
	idForm=Math.round(Math.random()*10);
	
	htmlForm = "<form id='dyn_form' action='"+uri+"' method='POST'>";
	htmlForm+= "<input type='hidden' name='"+field_name+"' value='"+field_value+"' >";
	htmlForm+= "</form>";
	
	$("body").append(htmlForm);
	$("#dyn_form").submit();
}



function mostrar_over_coordenada(linkId){		
	url="/multi/over_coordenada/"+linkId;
	
	html = $.ajax({
  		type: "POST",
  		url: url,
  		async: false
	 }).responseText;
	
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft("_"+linkId);
	var clickElementy = getAbsoluteTop("_"+linkId) + 10; //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 150};
	if(params['link'] !== undefined){
		$('#' + linkId).bind('click',function(){window.location = params['link']});
		$('#' + linkId).css('cursor','pointer');
	}
	
	
		$("body").append("<div id='JT"+linkId+"' style='position: absolute; width: 140px;border:none;z-index:100'></div>");
		var arrowOffset = getElementWidth("_"+linkId) + 10;
		var clickElementx = getAbsoluteLeft("_"+linkId) + arrowOffset; //set x position
	
	
	
	$('#JT'+linkId).css({left: clickElementx-params['width'] +"px", top: clickElementy+"px"});
	$('#JT'+linkId).html(html);	
}

function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner	
	o = document.getElementById(objectId)
	
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}

function closeTip (id)
{
	$('#JT'+id).remove();	
}

function showAndRequire (selector, state)
{
	if (state)
	{
		$(selector).show();
		$(selector + " INPUT ").addClass("required");
	}
	else 
	{
		$(selector).hide();
		$(selector + " INPUT ").removeClass("required");
		$(selector + " INPUT ").attr("value","");
	}	
}


function clean(name, text){
	if($("#"+name).attr("value") == text){
		$("#"+name).attr("value", "");
	}		
}


function OFlash (file, width, height, bgcolor, mode) { document.write ("<object codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0 height=" + height + " width=" + width + " classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000><PARAM NAME='FlashVars' VALUE=''><PARAM NAME='Movie' VALUE='" + file + "'><PARAM NAME='Src' VALUE='" + file + "'><PARAM NAME='WMode' VALUE='" + mode + "'><PARAM NAME='Play' VALUE='-1'><PARAM NAME='Loop' VALUE='-1'><PARAM NAME='Quality' VALUE='High'><PARAM NAME='SAlign' VALUE=''><PARAM NAME='Menu' VALUE='0'><PARAM NAME='Base' VALUE=''><PARAM NAME='AllowScriptAccess' VALUE='0'><PARAM NAME='Scale' VALUE='ShowAll'><PARAM NAME='DeviceFont' VALUE='0'><PARAM NAME='EmbedMovie' VALUE='0'><PARAM NAME='BGColor' VALUE='" + bgcolor +"'><PARAM NAME='SWRemote' VALUE=''><PARAM NAME='MovieData' VALUE=''><PARAM NAME='SeamlessTabbing' VALUE='1'><PARAM NAME='Profile' VALUE='0'><PARAM NAME='ProfileAddress' VALUE=''><PARAM NAME='ProfilePort' VALUE='0'><embed src='" + file + "' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='" + width + "' height='" + height +"'  wmode= '"+mode+"'></embed></object>"); }

function popup(page, title, width, height) {	
	window.open(page, title, "width=" + width + ",height="+height+",menubar=no,scrollbars=yes");
}

function pulsaHotel(idHotel){
    window.location = "/ficha/show/"+idHotel;
}
  
function pulsaPunto(idHotel){	
	window.location = "/ficha/show/"+idHotel;
}
  
function pulsaCiudad(isoPais){
  	window.location = "/mapa/show/"+isoPais;
}

function change_lang(lang){
	url="/multi/change_lang/"+lang;	
	html = $.ajax({
  		type: "POST",
  		url: url,
  		async: false
	 }).responseText;	
	
	window.location.reload();
}

function delete_option(text){
	if(confirm(text)){
		return true;
	}else return false;
}

function tiene_disponibilidad(check_availability, id_lang, id_hotel, check_in, check_out, adults){
	if(check_availability == 1){
		url="/multi/tiene_disponibilidad/"+id_hotel+"/"+check_in+"/"+check_out + "/" + adults;	
		html = $.ajax({
  			type: "POST",
	  		url: url,
  			async: false
		 }).responseText;
	}else html = '0';
//alert(check_availability); alert(html);
	if(check_availability == 0) $('#bookonline').attr('src', '/public/img/'+id_lang+'/check_availability.gif');
	else if(check_availability == 1 && html == '0'){
		$('#bookonline').hide();
		$('#no_available').show();
	}else{
		$('#bookonline').attr('src', '/public/img/'+id_lang+'/booknow.gif');
		$('#no_available').hide();
		$('#bookonline').show();
	}
//alert(html);
	url="/multi/escribir_precio_ficha/"+id_hotel+"/"+html;	
	html = $.ajax({
  		type: "POST",
  		url: url,
  		async: false
	 }).responseText;
	
	$("#precio_from").html(html);
}

function tiene_disponibilidad_hidden(){
	$('#loading').toggle();
	check_in = $("#b_in").attr("value");
	check_out = $("#b_out").attr("value");
	cBockOnline = $("#cBockOnline").attr("value");
	id_lang = $("#id_lang").attr("value");
	id_hotel = $("#id_hotel").attr("value");
	nr_adults = $("#nr_adults").attr("value");
	$('#check_availability').attr('value', 1);
	tiene_disponibilidad(cBockOnline, id_lang, id_hotel, check_in, check_out, nr_adults);
	$('#loading').toggle();
}

function guardar_disponibilidad(donde){
	check_in = $("#b_in").attr("value");
	check_out = $("#b_out").attr("value");
	nr_adults = $("#nr_adults").attr("value");
	nr_children = $("#nr_children").attr("value");
	if($("#check_availability").length == 0) check_availability = "none";
	else if($("#check_availability:checked").length == 0) check_availability = 0;
	else check_availability = 1;
	
	url="/multi/guardar_disponibilidad/"+check_availability+"/"+check_in + "/" +check_out + "/" +nr_adults + "/" + nr_children + "/"+donde;	
	html = $.ajax({
  		type: "POST",
  		url: url,
  		async: false
	 }).responseText;
}

function restarFechas(fechaInicio,fechaFin){
	var diferencia = fechaFin.getTime() - fechaInicio.getTime();
	var dias = Math.round(diferencia / (1000 * 60 * 60 * 24))
	return dias;
}

function mostrar_aviso_tiempo(){
	check_in = $("#b_in").attr("value");
	check_out = $("#b_out").attr("value");
	
	url="/multi/diferencia_dias/"+check_in + "/" +check_out;	
	var	dias = $.ajax({
			type: "POST",
			url: url,
			async: false
		 }).responseText;
	
	if(dias > 30) $("#alert_30_days").show();
	else $("#alert_30_days").hide();
}

function JT_show_cancellation_policy(linkId){	
	html = $('#cancellation_policy_'+linkId).html();
	//alert(html);
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft("_"+linkId);
	var clickElementy = getAbsoluteTop("_"+linkId) + 10; //set y position
	
	var queryString = "";
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 150};
	if(params['link'] !== undefined){
		$('#' + linkId).bind('click',function(){window.location = params['link']});
		$('#' + linkId).css('cursor','pointer');
	}
	
	
		$("body").append("<div id='JT"+linkId+"' class='JT_class' style='position: absolute; width: 350px;border:none;z-index:100;border: 3px solid #000000;'></div>");
		var arrowOffset = getElementWidth("_"+linkId) + 10;
		var clickElementx = getAbsoluteLeft("_"+linkId) - 365; //set x position
	
	
	
	$('#JT'+linkId).css({left: (clickElementx) +"px", top: (clickElementy - 25)+"px"});
	$('#JT'+linkId).html(html);	
}

function JT_show_info_room(linkId){	
	url_params = $('#info_room_'+linkId).html();
	
	url="/multi/get_info_room/"+url_params;
	
	html = $.ajax({
  		type: "POST",
  		url: url,
  		async: false
	 }).responseText;
	
	html = unescape(html);
	html = html.replace(/\+/gi," ");
	
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft("_"+linkId);
	var clickElementy = getAbsoluteTop("_"+linkId) + 10; //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 150};
	if(params['link'] !== undefined){
		$('#' + linkId).bind('click',function(){window.location = params['link']});
		$('#' + linkId).css('cursor','pointer');
	}
	
	
		$("body").append("<div id='JTr"+linkId+"' class='JT_class' style='position: absolute; width: 350px;border:none;z-index:100;border: 3px solid #000000;'></div>");
		var arrowOffset = getElementWidth("_"+linkId) + 10;
		var clickElementx = getAbsoluteLeft("_"+linkId); //set x position
	
	
	
	$('#JTr'+linkId).css({left: (clickElementx-params['width']) +"px", top: (clickElementy-25)+"px"});
	$('#JTr'+linkId).html(html);	
}