
//global variables
var gBookBox = '';
var gCarBox = '';
var gTab1 = '';
var gTab2 = '';
var gTab3 = '';


//css classes
var gCurrClass = 'active';
var gEnabClass = 'enabled';

//previous step
var previousStep = 1;
//value from previous step
var valor = '';
var texto = '';
var oferta = false;
var isAeropuerto = false;

var returnUrl = '';

var current_extras;


function isEdit ()
{
	var loc = document.location.href;
	var tokens = loc.split('/');
	
	return ( (tokens.length>3) && (tokens[3]=='cliente') 
				|| ( (tokens.length>4) && (tokens[4]=='cliente') ) );
}

function goBookingStep(requestUri)
{

  if (0 == $('#book_process').length)
    return false;

	var xhr;
	var step = requestUri;
			 
	if (requestUri == '')
	{
		if (isEdit())
			return false;
		else
			requestUri = '1';
	}  
			  
	//complete url 
	if (!oferta)
		requestUri = '/' + langUrl + 'reserva/paso' + requestUri + '/';
	else
	{
		requestUri = '/' + langUrl + 'reserva/paso' + requestUri + '_oferta/';
		oferta = false;
	}

	if (valor!='')
	{
		var postdata = 'paso='+previousStep+'&valor='+valor+'&texto='+texto;
			
		if (isAeropuerto)
		  postdata += '&aeropuerto=1'		  
		else
		  postdata += '&aeropuerto=0';		  		  
	}
	else
		var postdata = '';

	if (isEdit())
		postdata += '&origen=edit';
	else
		postdata += '&origen=public';

	// reset value for next 'back' event
	valor = '';
	texto = '';
		
	//load requested content
	xhr = $.ajax(
	{
		type: "POST",
		url: requestUri,
		data: postdata,
		statusCode: {
			205: 	function() 
					{
    			  document.location.href = '/' + langUrl;
  				}
		},		
		beforeSend: function() {
		  $('#step1_main').html( $('#update_loading').html() );		  
	    $('.step_main').html( $('#update_loading').html() );		  
		},
		success: function(data) 
		{ 
			//show/hide elements before display new content
			 switch (step) 
			 {
			   case '2': $('.booking_hide').hide(); $('#page_content').addClass('booking'); break;			   
		      case '7': $('.start_booking').hide(); $('#page_content').removeClass('booking'); break;
			 }
		        
		   gBookBox.html(data);
		   
		   //resize overlay after loading car-list
		   if (isEdit() && 7 == step)
		   {
		    if (!stupidIE())
		      expandLBOverlay();		     
		    else
		      $('.lbo').css({height:'3000px'});
		   }		   
		   
		}
	});

   
 
}//goBookingStep



function updateCalendar (date)
{
	// Get initial year, month and day
	var tokens = date.split('-');

	// Are we in step2 or in step5?
	var step;
	var contexto;
	if ($('#step2').length!=0)
	{
		step = 2;
   	contexto = 'Recogida';   
	}
	else
 	{
		step = 5;
		contexto = 'Devolucion';  
	}

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Cambiar Mes', contexto]);

	// Are we in edit or in main page
   var origen;
   if (isEdit())
     origen='edit';
   else
     origen='public';

	$.ajax (
	{
		type: 'POST',
		url: '/' + langUrl + 'reserva/calendario',
		data: 'year=' + tokens[0] + '&month=' + tokens[1] + '&day=' + tokens[2] + '&step=' + step + '&origen=' + origen + '&mobile=0',
		beforeSend: function() {
		  $('#cal_wrap').html( $('#update_loading').html() );
		},
		success: function(data)
		{
			$('#cal_wrap').html (data);
		}
	});
}//updateCalendar


function init() 
{

  if (typeof(initCliente)=='function')  initCliente();
  if (typeof(initReserva)=='function')  initReserva();
  if (typeof(initModificar)=='function')  initModificar();
  if (typeof(initTpv)=='function')  initTpv();

  gBookBox = $('#book_process');
  gCarBox = $('#car_selection');
  step1 = $('#bs_1');
  step2 = $('#bs_2');
  step3 = $('#bs_3');

  //init history callback
  $.history.init(goBookingStep);
  

  // front
  $('#logo').click ( function() {
    _gaq.push(['_trackEvent', 'Tendencias', 'Click Home', 'Logo']);
  } );

  $('#main_menu .inicio_reservas').click ( function() {
    _gaq.push(['_trackEvent', 'Tendencias', 'Click Home', 'Inicio-Reservas']);
  } );

  //step-2
  $('#step1 a').live('click', function()
  {
    valor = $(this).attr('rel');
    texto = $(this).attr('lang');    
    isAeropuerto = $(this).parents('#airport_offices').length != 0;
    previousStep = 1;

    	_gaq.push (['_trackEvent', 'Datos Reserva', 'Oficina Recogida', valor]);
  });  

  //month previous and next links
  $('.calendar_switch').live('click', function () 
  {
    updateCalendar($(this).attr('rel'));
    return false;
  });  


	
  //step-3
  $('#step2 .month_wrap a').live('click', function()
  { 
    valor = $(this).attr('rel');
    texto = $(this).attr('lang');
    previousStep = 2;

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Dia Recogida', valor]);
  });  
  
  
  //step-4
  $('#step3 a').live('click', function()
  { 
    valor = $(this).attr('rel');
    texto = $(this).attr('lang');
    previousStep = 3;

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Hora Recogida', valor]);
  });

  //step-5
  $('#step4 a').live('click', function()
  { 
    valor = $(this).attr('rel');
    texto = $(this).attr('lang');
    previousStep = 4;

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Oficina Devolucion', valor]);
  });  

  $('#devolucion_info a').live('click', function()
  {
    if (isEdit())
    {
		previousStep = 4;
      texto = '&nbsp;';
    }

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Cambiar Oficina Devolucion']);
  });
  
  //step-6
  $('#step5 .month_wrap a').live('click', function()
  { 
    valor = $(this).attr('rel');
    texto = $(this).attr('lang');
    previousStep = 5;

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Dia Devolucion', valor]);
  });  
  
  
  //step-7
  $('#step6 a').live('click', function()
  { 
    valor = $(this).attr('rel');
    texto = $(this).attr('lang');

    if ($('#oferta_seleccionada').length > 0)
      oferta = true;

    previousStep = 6;

	_gaq.push (['_trackEvent', 'Datos Reserva', 'Hora Devolucion', valor]);
  });

  
  // select car category
  $('#group_selection ul li input').live('change', function(event)
  {  
    var visibles = $('#group_selection ul li input:checked').length; 
   
    if (1 == visibles)
      $('#group_selection ul li input:checked').attr('disabled','disabled'); 
    else
      if (visibles > 1)
        $('#group_selection ul li input:checked').removeAttr('disabled');
  
    var rel = $(this).attr('rel');

    if ($(this).attr('checked'))
      $('.'+rel).fadeIn('fast');
    else
    	$('.'+rel).fadeOut('fast');

    if ( $(this).attr('checked') == 'checked' )
	   _gaq.push (['_trackEvent', 'Eleccion Vehiculo', 'Activar Filtro' /*, nombre categoria */ ]);
    else
	   _gaq.push (['_trackEvent', 'Eleccion Vehiculo', 'Desactivar Filtro' /*, nombre categoria */ ]);

  });
  
  //select car
  /*
  $('#step7 .car_wrap').live('click', function(e){
    
    var button = $(this).children('.button');
    selectCarFromList(button.attr('rel'), button.attr('texto'));
    
    _gaq.push (['_trackEvent', 'Eleccion Vehiculo', 'Reservar Grupo' ]);//, codigo grupo ]);
  });*/
  
  $('#car_list .button').live('click', function() {

    var button = $(this);
    selectCarFromList(button.attr('rel'), button.attr('texto'));

	_gaq.push (['_trackEvent', 'Eleccion Vehiculo', 'Reservar Grupo' /*, codigo grupo */]);   
  });
  
  
  $('#book_button').live('click', function() {
    $('#reserva_form').submit();
  });
  
  $('#login_cliente').click(function()
  {
    $('.reserva_pestana').hide();
    $('#reserva_login').slideDown('fast');
  });
  
  $('.reserva_pestana').click(function(){
    $('.reserva_pestana').toggleClass('active');
  });
    
  $('#confirmar_reserva').click(function(){
    location.href = '/' + langUrl + 'reserva/bono';
  });


  
  //modificar reserva
  $('#reserva_main').click(function(){
    openLightbox('/reserva/modificar');
  });
  
  /*$('.tab1 .prevInfo a').live ('click', function(){
    	_gaq.push (['_trackEvent', 'Datos Reserva', 'Modificar Oficina Devolucion']);   
  }); 

  $('.tab2 .prevInfo a').live ('click', function(){
    	_gaq.push (['_trackEvent', 'Datos Reserva', 'Modificar Dia y Hora Devolucion']);   
  });*/
  
  //form_tabs
  $('#form_tabs .new').live('click', function(){
    activateNewCustomerTab ();
	_gaq.push (['_trackEvent', 'Formulario Cliente', 'Elegir Tipo Formulario', 'Nuevo']);
    return false;
  });
  $('#form_tabs .customer').live('click', function(){
    activateOldCustomerTab ();
	_gaq.push (['_trackEvent', 'Formulario Cliente', 'Elegir Tipo Formulario', 'Cliente']);
    return false;
  });
  
  $('#customer_submit_button').live('click', function(){
    updateClientFormExtras();
    
    var postdata = 'email=' + $('#o_email').val() + '&password=' + $('#o_password').val();
    var requestUri = '/' + langUrl + 'reserva/comprobar';

    $.ajax(
	 {
		type: "POST",
		url: requestUri,
		data: postdata,
		statusCode: {
			205: 	function() 
					{
    			  document.location.href = '/' + langUrl;
  				}
		},		
		
		success: function(data) 
		{ 
			result = JSON.parse ( fixJsonData(data) );

         if (result.success == 'true')
			{
				$('#new_client_form').html ( result.code );
				updateSubmitText ();
				activateNewCustomerTab ();
				$('#login_cliente_result .loading').hide();
			}
			else
			{
				$('#old_client_form').html (result.code);
			}
		}
	});

   return false;
  });

  
  //ofertas portada
  /*
  if (!stupidIE()) {
  $('#offers li').mouseenter(function(){
    $(this).find('.price').effect("shake", { times:2, direction:'down' }, 50);
  }); }
  */
  
  //click en oferta
  $('#offers li').click(function()
  {
    returnUrl = location.href;
    var numOferta = $(this).attr ('rel');
    var idTarifa = $('#id_tarifa_oferta_' + numOferta).attr('rel'); 
    $('#book_process').remove();    
    var aux = $('.start_booking').html();

    openLightbox('/'+ langUrl +'reserva/paso1/num_oferta/'+numOferta+'/id_tarifa/'+idTarifa+'/', 940, '<div id="oferta_loader"><div class="lb-close"></div><h1 class="start_booking">'+aux+'</h1><div id="book_process"><div class="loading"></div></div><br class="clear" /></div>', true);

    gBookBox = $('#book_process');

    _gaq.push(['_trackEvent', 'Ofertas', 'Click Oferta', numOferta]);

    return false;
  });

  // click en oferta principal
  $('#main_offer').click(function()
  {
    _gaq.push(['_trackEvent', 'Ofertas', 'Click Oferta', 'Principal']);
  });
  
  
  //ordenar lista de coches
  $('#sort_car_list a').live('click', function(){
    var li = $(this).parents('li');    
    var id = li.attr('id');
    var order = 1; //asc order by default
    
    switch (id) 
    {
      case 'sort_by_seats': 
        sortArray = ['.feature_seats', '.price']; order = -1;
	     _gaq.push (['_trackEvent', 'Eleccion Vehiculo', 'Tamano']);     
        break;  
      default: 
        sortArray = ['.price', '.feature_seats'];
	     _gaq.push (['_trackEvent', 'Eleccion Vehiculo', 'Precio']);   
        break;      
    }      
    
    $('#sort_car_list li').removeClass('active');
    li.addClass('active');
    
    sortCarList(sortArray, order);
    return false;
  });
  


  
  
   //show lost pass form
  $('#btn_cliente_pass_lost').live('click', function()
  {
    $('#f_acceso_cliente .login_cliente').hide();
    $('#f_acceso_cliente .lost_pass').show('slide',{direction:'right'},'fast');
	 _gaq.push (['_trackEvent', 'Formulario Cliente', 'Recuperar Contrasena']);
    return false;
  });
  
  
  //show client form login
  $('#btn_cliente_form_login').live('click', function()
  {
    $('#f_acceso_cliente .lost_pass').hide();
    $('#f_acceso_cliente .login_cliente').show('slide',{direction:'right'},'fast');
	 _gaq.push (['_trackEvent', 'Formulario Cliente', 'Cancelar Recuperar Contrasena']);
    return false;
  });
  
  



  $('#open_terms, #open_privacy, #open_faq, #open_legal').live('click', function() 
  { 
    var url = $(this).attr('href');
    openLBPage( url );
    return false;
  });
  
  
  
  $('#terminos_select .country_selection li').live('click', function()
  {
  	var self = $(this);
  	var id = self.attr('rel');
  	var tbox = $('#terminos_select');
  	
  	self.removeClass('unselected');
		self.siblings().addClass('unselected');
		tbox.find('.dates_selection').hide();
  	
  	if (tbox.find('#ds'+id).length)
  	{
			$('#ds'+id).show('normal');
  	}
  	else {
  		loadTermsAndConditions(id);
  	}
  });
  
  
  $('#terminos_select .dates_selection li').live('click', function()
  {
  	var self = $(this);
  	var id = self.attr('rel');
  	
  	loadTermsAndConditions(id);
  });

  
  
  //resaltar dias de la reserva en el calendario
  $('#step5 .month td').live('mouseenter', function()
  {
    $('#step5 .month td.hv').removeClass('hv');
    
    if ($(this).has('a')) 
    {  
      var hover_date = $(this).find('a').attr('rel');  
      
      $('#step5 .month td a').each(function()
      { 
        var self = $(this);
        if (self.attr('rel') <= hover_date)
          self.parent().addClass('hv');
        else
          return;
      });    
    }//if
  });
  
  
  
  $('#step5 .month').live('mouseleave', function(){
    $('#step5 .month td.hv').removeClass('hv');
  });
  
  
  
  
  /** ofertas portada **/  
  $('.lb-close').live('click', function()
  {
    if ( $(this).parents('#oferta_loader').length > 0 )
    {
      $('#book_process').html( $('#update_closing').html() );
      //location.href = '/'+langUrl;  
      location.href = returnUrl;
    }
    else 
    {
      closeLightbox();
    }
  });
  
  
  
  $('.car_features .feat_wrap').live('mouseenter', function()
  {
    if (stupidIE())
      return;
      
    var self = $(this);
    var ttext = '';
    if (self.find('img').length>0)
      ttext = self.find('img').attr('alt') + ': ' + self.find('.feature_subindex:first').text();
    else
      ttext = self.find('span').attr('title');    
    
    showTooltip(self, ttext, 200, 15);
  });
  
  $('.car_features .feat_wrap').live('mouseleave', function(){
    hideTooltip( $(this) );
  });
  

  // Bono

  $('.btn_imprimir_pdf').live('click', function () {
    window.open($(this).attr('href'), $(this).attr('target'), 'width=750,height=600,menubar=no,scrollbars=yes,toolbar=yes');
	 _gaq.push (['_trackEvent', 'Bono', 'Imprimir Bono']);
    return false;
  } );

  $('.btn_descargar_pdf').live('click', function () {
	_gaq.push (['_trackEvent', 'Bono', 'Descargar PDF']);
  } );
  
  
  

}//init



//load terms and conditions
function loadTermsAndConditions(id)
{

	$.ajax(
	{
		type: 'POST',
		url: '/' + langUrl + 'terminos/id/' + id + '/',
		beforeSend: function() {
			$('.lb-scroll').html( $('#update_loading').html() );
		},		
		success: function(data) {
			$('.lb-scroll').html (data);
		}
	});

}



/*** click en el boton de la chapa del coche **/
function selectCarFromList(c_rel, c_texto) 
{
	var protocol = 'https://';
	var dest_domain = window.location.hostname;
	
	if (dest_domain != 'www.goldcar.es')
		protocol = 'http://';
	
  if ( $('#car_list').attr('rel') == 'edit' )
    var action = '/' + langUrl + 'cliente/guardarCambios';
  else
    var action = protocol + dest_domain + '/' + langUrl + 'reserva/convertir_post/';
    
  $('form#step7_form').attr('action',action);
  $('form#step7_form #valor').attr('value',c_rel);
  $('form#step7_form #texto').attr('value',c_texto);
  $('form#step7_form #destino').attr('value', protocol + dest_domain + '/' + langUrl + 'reserva/reservar/');
  $('form#step7_form').submit();

}







/** ordenar lista de coches **/

function sortCarList(sortArray, order)
{

  //default: asc (1)
  //for desc use '-1'
  if ('undefined' == typeof(order)) order = 1;

  if ( 0 == $('.car_list').length)
    return false;

  var sA = sortArray;
  
  var sortedList = $.makeArray($('.car_wrap')).sort(function(o, n) 
  {    
    result = 0;
    var o_f1 = parseFloat($(o).find(sA[0]).text());
    var n_f1 = parseFloat($(n).find(sA[0]).text());
    var o_f2 = parseFloat($(o).find(sA[1]).text());
    var n_f2 = parseFloat($(n).find(sA[1]).text());
    
    //sort by first feature
    if ( o_f1 < n_f1)
      result = -1*order;
    else if ( o_f1 > n_f1 )
      result = 1*order;
    //sort by second feature
    else if ( o_f2 < n_f2 )
      result = -1*order;    
    else if ( o_f2 > n_f2 )
      result = 1*order;    
      
    return result;      
  });
    
  $('.car_list').html(sortedList);  

  return false;
}

function activateNewCustomerTab ()
{
	 $('#form_tabs').removeClass('customer_selected').addClass('new_selected');
    $('#f_acceso_cliente').removeClass('active');
    $('#new_form').addClass('active');
}

function activateOldCustomerTab ()
{
	$('#form_tabs').removeClass('new_selected').addClass('customer_selected');
	$('#new_form').removeClass('active');
	$('#f_acceso_cliente').addClass('active');   
}

function fixJsonData(data) 
{
	return data.replace(/(\r\n|\n|\r|\t)/gm, '');
}

function build_current_extras()
{
	build_current_extra_counter=0;
	current_extras=new Array();
	$('.extra_select').each ( function () {
		current_extras[build_current_extra_counter]=new Array($(this).attr('name'),$(this).val());
		build_current_extra_counter++;
	});	
}


function updateSubmitText()
{
 
	$('#price_ent_2').html ($('#price_ent_1').html());
	$('#price_ex_2').html ($('#price_ex_1').html());
	//$('#price_dec_2').html ($('#price_dec_1').html());
	
	if ($('#other:checked').length>0)
    $('#select_contry_wrap').show();
  
	
}//updateSubmitText

function recalculatePrice()
{
	build_current_extras();
	
	// Build parameters string
	var poststring = '';
	if (isEdit())
		poststring += 'origen=edit';
	else
		poststring += 'origen=public';
	recalculate_extra_counter=0;
	$('.extra_select').each ( function () {
		if (poststring!='')
			poststring += "&";
		poststring += $(this).attr('name') + '=' + $(this).val();
		recalculate_extra_counter++;
	});
	$('#p_checkin_checkbox').each ( function () {
		if (poststring!='')
			poststring += "&";
		poststring += $(this).attr('name') + '=' + $(this).attr('checked')
	});
	$('#p_checkin_hidden').each ( function () {
		if (poststring!='')
			poststring += "&";
		poststring += $(this).attr('name') + '=' + $(this).val();
	});

	//load requested content
	$.ajax(
	{
		type: 'POST',
		url: '/' + langUrl + 'reserva/calcular/',
		data: poststring,
		beforeSend: function() {
		  $('#final_price').html ('<div class="loading"></div>');
		},
		success: function(data)
		{
			$('#final_price').html (data);
			if(typeof(initReserva)=='function')
				updateSubmitText();
		}
	});
}//recalculatePrice

function get_too_many_extras_from_form(this_select)
{
	total_extras_count=0;
	total_extra_change_counter=0;
	for(current_extra in current_extras)
	{
		if(current_extras[total_extra_change_counter][0]==this_select.attr('name'))
		{
			total_extras_count += parseInt(this_select.val(),10);
			old_val = parseInt(current_extras[total_extra_change_counter][1],10);
		}
		else
			total_extras_count += parseInt(current_extras[total_extra_change_counter][1],10);
			
		total_extra_change_counter++;
	}
	if (total_extras_count>3)
		return true;
	else
		return false;
}

$(document).ready(init);

