/*
  wizard functions, contains functions used by various versions of the booking wizard
*/

function round( l )
{
    var myBoxObject = new curvyCorners(inlineSettings, 'airport');
    myBoxObject.applyCornersToAll();
}

function swap(e)
{
  id = e.id.replace('link_', '');
 
  id = id.replace(/_[0-9]*/, '');

  src = $( '#fold_' + id ).attr('src');

  e.style.fontWeight = e.style.fontWeight=='bold' ? 'normal' :'bold' ;
 
  $( '#faq_' + id ).toggle();
  src.indexOf( "arrow_on.png" ) != -1 ? src=src.replace(/on/, 'off') : src=src.replace(/off/, 'on');
  $( '#fold_' + id ).attr('src', src);
}

function hotelSwap( id, hoteldata )
{
  // first, close all others:

	var arrows = $('.arrow');

  $(arrows).each(function(index, el)
  {
		var arrow_src = $(el).attr('src').replace( 'on', 'off' );
    $(el).attr('src', arrow_src);
  });
  
  $('.hotelcontent').hide();
  $('#hotelcontent_' + id ).hide();

	var arrow_src = $('#arrow_' + id).attr('src').replace( 'off', 'on' );
	$('#arrow_' + id).attr('src', arrow_src);

	$('#hotelcontent_' + id ).show();

  codeAddress( hoteldata );
}

var _activeStep = 0;

_steps = new Array
(
  new Step("step 1", 0, false),
  new Step("step 2", 1, false),
  new Step("step 3", 2, false),
  new Step("step 4", 3, false),
  new Step("step 5", 4, false),
  new Step("step 6", 5, false)    
);

function initEvents( step )
{
  document.getElementById("kop0").onclick = jumpToStep;
  document.getElementById("kop1").onclick = jumpToStep;
  document.getElementById("kop2").onclick = jumpToStep;
  document.getElementById("kop3").onclick = jumpToStep;
  document.getElementById("kop4").onclick = jumpToStep;
  document.getElementById("kop5").onclick = jumpToStep;    

	_activeStep = step;
  _steps[step].render();
  
  activateStep(step);
//  window.setTimeout('sessionExpired()', 1000 * 60 * 15);  // minuten
}

function sessionExpired()
{
  window.onbeforeunload=function(){};
  a('Uw sessie is verlopen. Omdat de prijs en beschikbaarheid van vliegtickets sterk fluctuerend zijn, moet u opnieuw de stappen doorlopen.');
  window.location.reload();
}

// class Step
function Step(name, id, valid) 
{
  var clickedStep;
  this.name = name;
  this.valid = valid;
  this.id = id;
}

  Step.prototype.myReady = function( r ) 
  {
    if ( r ) parseStep ( r, clickedStep );
  }

  Step.prototype.post = function() 
  {
    XFormSubmit( document.forms["step" + this.id], 'content' + this.id, this.myReady );
  }
  
  Step.prototype.render = function()
  {
    helpDiv = document.getElementById( "help" + this.id );
    helpDiv.style.visibility = 'visible';
    $( '#aanpas' + this.id ).hide();

  	document.getElementById( 'content' + (this.id) ).innerHTML = '<img src="../pics/wizard/loading.gif">';
    $( '#content' + (this.id) ).show();
 	
    location.hash = 'div' + (this.id);
		
		$('#content' + this.id).load("xml/step" + this.id + ".php?action=render", function(){stepMyReady()});

    dogoogle ( this.id + 1 );
  }

  function stepMyReady()
  {
    enableTooltips();
/*    catch ( e )
    {}
*/
  }

// ---

function parseStep( xmlObject, clickedStep )
{
  step = xmlObject.documentElement.getElementsByTagName('step')[0].firstChild.data;

  errorTree = xmlObject.documentElement.getElementsByTagName('errors');
  validTree = xmlObject.documentElement.getElementsByTagName('valid');

  if ( errorTree.length )
  {
    errorFields = errorTree[0].getElementsByTagName('field');
    for (x=0; x<errorFields.length; x++)
    {
      name = errorFields[x].getElementsByTagName('name')[0].firstChild.data;
      message = errorFields[x].getElementsByTagName('message')[0].firstChild.data;
      code = errorFields[x].getElementsByTagName('code')[0].firstChild.data;

      switch ( code )
      {
        case 'CONFIRM':
          //hiLightError( name );
          if ( confirm ( message ) ) 
            completeStep( step, validTree, clickedStep);
        break;
        
        default:
          hiLightError(name, message);
        break;
      }
      break;
    }
  }
  else
  {
    if ( validTree.length )
    {
      completeStep( step, validTree, clickedStep);
    }
  }
}

function completeStep(step, validTree, clickedStep)
{
  toDiv = document.getElementById( "content" + step );
  
  validCode = validTree[0].getElementsByTagName("htmlcode");
  
  toDiv.innerHTML = validCode[0].firstChild.data;
  
  if ( subtotaal = document.getElementById('subtotaal_' + (_activeStep - 1) ) )
  subtotaal.style.display = "none";
  
  finishStep (_activeStep);
  activateStep(clickedStep);
}

function removeError(name)
{
  if ( fe = document.forms[1][name] )
  {
    if ( fe.style && fe.type != 'hidden' ) 
    {
      fe.style.backgroundColor='transparent';
      fe.style.border='none';
      fe.focus();
    }
  } 
}

function activateStep(step)
{
  if ( step == 2 && window.location.href.indexOf("ssl") <= 0 )
  {
    window.location.href='to_ssl.php';
    return;
  }

	if ( step < 2 && window.location.href.indexOf("ssl") > 0 )
	{
    window.location.href='to_http.php?step=' + step;  			
    return;
	}

  _steps[ step ].render();  
  div = $("#div" + step);

  div.removeClass('stepInActive');
  div.addClass('stepActive');
 
  _activeStep = step;
}

function disableStep(step)
{
  div = $("#div" + step);

  div.addClass('stepActive');
  div.addClass('stepInActive');

  $('#content' + step + '.stepcontent').hide();
  helpDiv = $( "#help" + step );
  helpDiv.hide();
}

function finishStep(step)
{
  div = document.getElementById("div" + step);

  helpDiv = document.getElementById( "help" + step );
  helpDiv.style.visibility = 'hidden';
  $( '#aanpas' + step ).show();
}

function nextStep()
{
  clickedStep = _activeStep + 1;
  _steps[ _activeStep ].post();
}

function jumpToStep(e)
{
  var current, related;
  if (window.event) {          // IE
    current = this;
    related = window.event.toElement;
  }
  else {
    current = e.currentTarget;
    related = e.relatedTarget;
  }

  clickedStep = parseInt( current.id.replace(/kop/g, ""), 10 );
  _activeStep = parseInt( _activeStep, 10 );

  if ( clickedStep != _activeStep )
  {
    if ( clickedStep == _activeStep + 1 )
    {
      _steps[ _activeStep ].clickedStep = clickedStep;
      _steps[ _activeStep ].post();
    }
    else if ( clickedStep <= _activeStep)
    {
      for (x=0; x<_activeStep - clickedStep; x++)
      {
        if ( subtotaal = document.getElementById('subtotaal_' + (clickedStep - 1) ) )
        subtotaal.style.display = "";
        disableStep(_activeStep - x);
      }

      activateStep(clickedStep);
    }
    else
    {
      a("Vul eerste de vorige stappen in!");
    }
  }
}

function disableRow( t, c )
{
  cbArray = getElementsByClassName(document, '*', c);
	if ( t.checked )
	{
		for ( x=0; x<cbArray.length-1; x++)
		{
	  	cbArray[x].disabled = true;
	  	cbArray[x].checked = false;
	  }
	}
	else
	{
	  if (c == 'annuleringExtra') return;
		for ( x=0; x<cbArray.length-1; x++)
	  	cbArray[x].disabled = false;
	}
}

function enableAanvullend ( c )
{
  cb = document.getElementById('aanvullend_' + c);
  cb.disabled = (cb.disabled?false:true);
}

function enableAllAanvullend ( c )
{
  cbArray = getElementsByClassName(document, '*', 'annuleringExtra');
  for ( x=0; x<cbArray.length-1; x++)
	{
	  	cbArray[x].checked = false;
	  	cbArray[x].disabled = true;
	}
  
  cb = document.getElementById('aanvullend_' + c);
  cb.disabled = (cb.disabled?false:true);  
  cb.checked = (cb.checked?false:false); 
}

function getElementsByClassName(oElm, strTagName, strClassName)
{
    var arrElements = (strTagName == "*" && document.all) ? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++)
    {
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className))
        {
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

function startSearch( bedVerdeling, s1, s2 )
{
  $('#hotelsContent').html( s1 + '<br /><img src="../pics/wizard/loading.gif" alt="" />' );

  $.post('xml/getHotels.php', {bedVerdeling:bedVerdeling}, function(t){
  	$('#hotelsContent').html(t);
  });

  $('#vluchtenContent').html( s2 + '<br /><img src="../pics/wizard/vlieg2.gif" alt="" />' );

  $.post('xml/getFlights.php', {x:1}, function(t){
  	$('#vluchtenContent').html(t);
  });	
}

function dateChange(x)
{
  $.post('xml/datum.php', {chamgeMyDate:x}, function(t){
  	$('#datumContent').html(t);
  });	
}

function dateMyReady()
{
  if ( document.getElementById('vluchtenContent') ) 
    document.getElementById('vluchtenContent').innerHTML = '';
  if ( document.getElementById('hotelsContent') )
    document.getElementById('hotelsContent').innerHTML = '';
  if ( document.getElementById('hotelsVluchtenKnop') )
    document.getElementById('hotelsVluchtenKnop').style.display = 'block';
  enableTooltips();
}

function finalStep( lead_str, av_str, p_method_str )
{
	var p_method = false;
  f = document.forms['step5'];
  opmerkingen = f['opmerkingen'].value;
  aanbetaling = ( f['aanbetaling'] ) ? f['aanbetaling'].value : null;
  lead = f['lead'].options[f['lead'].selectedIndex].value;

  p_methods = f['p_method'];

  if( !p_methods.value )
  {
	  for ( i=0; i<p_methods.length; i++)
	  {
	    if ( p_methods[i].checked ) 
	    {
	      p_method = p_methods[i].value;
	      break;
	    }
	  }
	}
	else
	{
		p_method = p_methods.value;
	}
		
  av = f['av'].checked?true:false;
  nieuwsbrief = f['nieuwsbrief'].checked?1:0;

  if ( !lead )
  {
    hiLightError('lead', lead_str )
    return false;
  }

  if ( !av )
  {
    hiLightError('av', av_str )
    return false;
  }

  if ( !p_method )
  {
    hiLightError('p_method', p_method_str )
    return false;
  }

  url = 'action=final';
  
  if (opmerkingen) url += '&opmerkingen=' + encodeURIComponent(opmerkingen);
  if (lead) url += '&lead=' + encodeURIComponent(lead);
  if (p_method) url += '&p_method=' + encodeURIComponent(p_method);
  if (av) url += '&p_av=' + encodeURIComponent(av);
  if (aanbetaling) url += '&aanbetaling=' + encodeURIComponent(aanbetaling);
  if (nieuwsbrief) url += '&nieuwsbrief=' + encodeURIComponent(nieuwsbrief);
  
  window.onbeforeunload=function(){};

  $( '#loader' ).innerHTML = '<img src="../pics/wizard/loading.gif">';
	//Xpost('xml/step5.php', url, null, function(r){hideIbox(); document.write( r )});    // debug
		
	Xpost('xml/step5.php', url, null, function(r){
		window.location.href=r;
	}); //live
}

function updatePricePayMethod(f)
{
  try 
  {
    p_method = f.value;
    if ( p_method == 'C' ) alert ('<?=LOCALE_CC_NOTICE?>');
    
	  $.post( 'xml/payMethod.php', {p_method:p_method}, function(t){
	  	$('#totaalbedrag').html( '&euro;' + t );
	  } );

	  $.post( 'xml/payMethod.php', {p_method:p_method, half:true}, function(t){
	  	$('#totaalbedrag_aanbetaling_1').html(t);
	  } );
  }
  catch (e)
  {}
}

function updateActie(f)
{
  actiecode = f.value;

  $.post( 'xml/actie.php', {actiecode:actiecode}, function(t)
  {
		if ( t )
		{
      $('#update_actie').html( '<img src="../pics/wizard/accepted.gif">' );
      $('#totaalbedrag').html(t);
		}
  });
}

function showInfoBoebel( id, t )
{
   var boebel = document.getElementById( id );
   boebel.innerHTML = unescape( t );
   boebel.style.display = 'block';
}

function x(){}

function dogoogle( step )
{
  pageTracker._trackPageview("/boeking/stap" + step + ".html");
}

function swapFlights(type, s1, s2)
{
  a = getElementsByClassName(document, '*', 'hideFlight_' + type);
  
  for ( var x=0; x<a.length; x++ )
  {
    if ( a[x] )
    {
      if ( navigator.appName == "Microsoft Internet Explorer" )
      {
        a[x].style.display = a[x].style.display == 'inline' ? '' : 'inline';
      }
      else
      {
        a[x].style.display = a[x].style.display == 'table-row' ? '' : 'table-row';
      }
    }
  }

  a = getElementsByClassName( document, '*', 'avtButton_' + type )
  for ( var x=0; x<a.length; x++ )
  {
    if ( a[x] )
    {
      a[x].innerHTML = a[x].innerHTML == s1 ? s2 : s1;
    }
  }
}

// left here for old sites like FBB...
function swapFlightsOld()
{
  a = getElementsByClassName(document, '*', 'hideFlight' );
  
  for ( var x=0; x<a.length; x++ )
  {
    if ( a[x] )
    {
      if ( navigator.appName == "Microsoft Internet Explorer" )
      {
        a[x].style.display = a[x].style.display == 'inline' ? '' : 'inline';
      }
      else
      {
        a[x].style.display = a[x].style.display == 'table-row' ? '' : 'table-row';
      }
    }
  }

  a = getElementsByClassName( document, '*', 'swapFlightsKnop' )
  for ( var x=0; x<a.length; x++ )
  {
    if ( a[x] )
    {
      a[x].innerHTML = a[x].innerHTML == 'Toon' ? 'Verberg' : 'Toon';
    }
  }
}

function hoofdboekSelect(t)
{
  cbArray = getElementsByClassName(document, '*', 'cb');
  eArray = getElementsByClassName(document, '*', 'email');
  etArray = getElementsByClassName(document, '*', 'emailText');

  r = t.parentNode.parentNode;
  document.getElementById('personalia').style.display = 'block';
  
  for ( x=0; x<eArray.length; x++ )
  {
    eArray[x].disabled = false;
    eArray[x].style.display='inline';
    eArray[x].parentNode.parentNode.className = 'clear';
    etArray[x].innerHTML = '';

    if ( x==t.value )
    {
      r.className = 'hoofdboeker';
    }
  }
  return true;
}

function updateAirports( v )
{
  if ( v )
  {
  	$( '#airportsContent' ).html( '<img src="../pics/wizard/loading.gif">' );

	  $.post( 'xml/getAirports.php', {region:v}, function(t){
	  	$('#airportsContent').html(t);
	  } );	
  }
  else
  {
  	$( '#airportsContent' ).html( '' );
  }
}

function initDate( type_str, current_date )
{
  date_array = current_date.split('-');
 
	var objCurrentDate = new Date();
	objCurrentDate.setMonth( date_array[1]-1 );
	objCurrentDate.setDate( date_array[0] );
	objCurrentDate.setYear( date_array[2] );
	
	var objEarlyDateEx3 = new Date();
	objEarlyDateEx3.setMonth( date_array[1]-2 );
	objEarlyDateEx3.setDate( 1 );
	objEarlyDateEx3.setYear( date_array[2] );
	var objLateDateEx3 = new Date();
	objLateDateEx3.setMonth( date_array[1] );
	objLateDateEx3.setDate( 31 );
	objLateDateEx3.setYear( date_array[2] );
	
	var date_obj = document.getElementById('choose_' + type_str );

	date_obj.DateChooser = new DateChooser();

	date_obj.DateChooser.setCloseTime(400);
  date_obj.DateChooser.setStartDate(objCurrentDate);

  date_obj.DateChooser.setUpdateField('datum_' + type_str, 'D, j F Y');
	document.getElementById('date_'  + type_str).onclick = date_obj.DateChooser.display;

  date_obj.DateChooser.setCallBack( 

    function() 
    {
      var datum_heen = $('datum_heen').value;
      var datum_terug = $('datum_terug').value;
    

    	$.post( 'xml/check_date.php', {datum_heen:datum_heen, datum_terug:datum_terug}, function(t){
        if ( t.responseText )
        {
          hiLightError('datum_' + type_str, t.responseText )
        }
        else
          {
            removeError('datum_heen');
            removeError('datum_terug');
          }
    	}, 'text' )
    }
  );
}

function cancelCB( cb )
{
  if ( cb.name == 'all_annulering' )
  {
    if ( $('#cb_cancel_all').attr('disabled') == false )
    {
      $('#cb_cancel_all').attr('disabled', true);
      $('#cb_cancel_all').attr('checked', false);
    }
    else
      {
        $('#cb_cancel_all').attr('disabled', false);        
      }
  }
  else
    {
      id = cb.id.replace( 'cancel_', '' );
      
      if ( $('#cancel_extra_' + id).attr('disabled') == false )
      {
        $('#cancel_extra_' + id).attr('disabled', true);
        $('#cancel_extra_' + id).attr('checked', false);
      }
      else
        {
          $('#cancel_extra_' + id).attr('disabled', false);        
        }      
    }
}

/*
 * Expose error
 */
function exposeError( id, msg )
{
  $('#' + id ).css( 'background-color', '#fcc');

  $("#overlay_content").html( msg );

  $("#overlay").overlay({
      // some expose tweaks suitable for facebox-looking dialogs
      expose: {
          color: '#000',
          loadSpeed: 200,
          opacity: 0.5
      },
      closeOnClick: true,
      api: true
  }).load();
}

function hiLightError(name, msg)
{
	if ( $( '#' + name + '_err' ) )
	{
		$( '#' + name + '_err' ).addClass('hilite');
	}
  
  $("#overlay_content").html( msg );

  $("#overlay").overlay({
      // some expose tweaks suitable for facebox-looking dialogs
      expose: {
          color: '#000',
          loadSpeed: 200,
          opacity: 0.5
      },
      closeOnClick: true,
      api: true
    }).load();
}

function errorReport()
{
	var email = $('#err_mail').val();
	var message = $('#err_report').val();
	
	if ( !email )
	{
	  alert( 'Vul aub uw emailadres in.' );
		return ( false );
	}

	if ( !message )
	{
		alert( 'Schrijf aub een bericht.' );
		return( false );
	}

	$.post( "xml/err_report.php", {message:message, email:email}, function(t){alert(t);$('#err_report_container').hide()});
}
