/*

 Limos.com search widget
 See http://www.limos.com/search_widget/example.html for details on how to create and style the widget

*/





// if jquery is not detected, we'll load it ourselves and put jquery in noConflict mode once it loads
// just in case there are other libraries loaded on the partner site that already declare the "$" function.
// Throughout this script, we specifically use "jQuery" and not "$" for just that reason.
// However, if jquery is already used on the partner site, we don't want to call 'noConclict'
// because it will likely break the partner's UI.
var noConflict = false;
var limo_jquery_ui_loaded = false;


// Load the Limos.com Search Widget
function limoWidget( p ) {
	
	// allow the host to be set in the widget call -- helpful for debugging and development
	var host = ( p.host ? p.host : 'http://www.limos.com' )
	
	// load up jQuery if not found, then wait for it to be ready
	if (typeof jQuery == 'undefined' || typeof jQuery().outerWidth == 'undefined' ) {
	  noConflict = true; 
	  limoLoadjs("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");
	  limoWaitForJQ( p ); // this will loop until jquery is detected then start the widget building over
	  return;
	}
		
	// stick the widget html in the defined target
	//widget = limoWidgetHtml();
	htmlParams='?w=1';
	if( p.contactInfo ){
    htmlParams +='&contactInfo=true'
  }
  if( p.formClass ){
    htmlParams +='&formClass='+p.formClass
  }
  if( p.inline_labels==true ){
    inline_labels +='&inline_labels='+p.inline_labels
  }
	if (typeof limoWidgetHTML == 'undefined') {
  	limoLoadjs(host+'/search-widget/widget_html.js'+htmlParams);
	  limoWaitForHTML( p ); // this will loop until jquery is detected then start the widget building over
	  return;
	}
	
	// if we are the ones loading jquery make sure we are not conflicting with whatever other libraries may be loaded
	if( noConflict ) jQuery.noConflict();
	
	// add the stylesheet
	jQuery('head').append("<link type='text/css' rel='stylesheet' media='screen' href='"+host+"/search_widget/widget_combined.css' />");
		
	// load custom jquery ui with datepicker
	limoLoadjs(host+"/search_widget/jquery-ui.js");
	
	// just a little short-hand because we'll use this many times
	var f = '#'+p.targetId;
		
	jQuery(f).html(limoWidgetHTML);

  // update misc attributes
  jQuery(f+' #limoscom #new_search').attr( 'action', host+'/index/error' );
  
  if( p.windowTarget ){
    jQuery(f+' #limoscom #new_search').attr( 'target', p.windowTarget );
  }
  if( p.headerText ){
	  jQuery(f+' #limoscom #ldcheader').html( p.headerText );
  }
  if( p.buttonText ){
	  jQuery(f+' #limoscom #search_submit').val( p.buttonText );
  }
  if( p.searchSource ){
	  jQuery(f+' #limoscom #search__search_source').val( p.searchSource );
  }
  if( p.msc ){
	  jQuery(f+' #limoscom #search_msc').val( p.msc );
  }
  if( p.msp ){
	  jQuery(f+' #limoscom #search_msp').val( p.msp );
  }
  if( p.serviceTypes ){
    // remove any values not in the new serviceTypes list
	  jQuery(f+' #limoscom #service_type option').each(function(){
	    var ov = jQuery(this).val();
	    if( ov && jQuery.inArray(ov,p.serviceTypes) == -1 ){
	      jQuery(this).remove();
	    } 
	  });
	  // remove any empty optgroups. jQuery's ":empty" selector isn't working when there is white space inside the tag
	  jQuery(f+' #limoscom #service_type optgroup').each(function() {
	    var optext = jQuery(this).text();
	    if( !optext.match('[^ ]') ) { jQuery(this).remove(); }
	  });
  }

  if( p.hiddenFields ){
    jQuery.each(p.hiddenFields,function(k,v){
      //alert('k: '+k+' / v: '+v);
      var vfield = jQuery('#'+v);
      var vval = vfield.val();
      var vid = vfield.attr('id');
      var vname = vfield.attr('name');
      vfield.parent().remove();
      jQuery("<input type='hidden' id='"+vid+"' name='"+vname+"' value='"+vval+"'/>").prependTo(f+' #limoscom #new_search');
    });
    // special case if both pickup and drop-off are removed
    if( jQuery('input#search_drop_off_time[type="hidden"]').length > 0 && jQuery('input#search_pickup_time[type="hidden"]').length > 0 ){
      jQuery('#limoscom').find("label:contains('Time')").parent().remove();
    }
  }
  
  if( p.defaultValues ){
    // go through and set the new default values of any IDs found
    for( k in p.defaultValues){
      var v = eval('p.defaultValues.' + k);
      jQuery(f+' #limoscom #'+k).val(v);
    }
  }

  if( p.extraHiddenFields ){
    jQuery.each(p.extraHiddenFields, function(k,v){
      var n = k.replace("_lb_","[").replace("_rb_","]");
      var i = k.replace("_lb_","_").replace("_rb_","");
      jQuery("<input type='hidden' id='"+i+"' name='"+n+"' value='"+v+"'/>").prependTo(f+' #limoscom #new_search');
    });
  }
 
  // tie in validation
  jQuery(f+' #new_search').submit(function(){
		return limos_validate_form(f,p);
	});

  // Disable drop off times and locations for air/cruiseports, enable only for hourly
	jQuery(f+' #service_type').change(function(){
	  limos_show_hide_drop_offs(f); limos_show_hide_drop_location(f); limos_change_labels(f);
	});
	limos_show_hide_drop_offs(f);
	limos_show_hide_drop_location(f);
	limos_update_fields();
	limos_change_labels(f);
	jQuery(f+' #search_pickup_time').change(function() {limosChangeTimeSlot(f);});

  // fade in the widget
  if( p.callback ){
     jQuery(f+' #limoscom').animate({ opacity: "show" }, 'slow', 'linear', function(){ eval(p.callback) } );
  }
  else {
    jQuery(f+' #limoscom').fadeIn('slow');
  }

  // create the date picker -- need to loop to make sure jquery UI is loaded first
  limoLoadDatePicker(f);
}



// Load a remote javascript file -- not using jquery here in case it's not loaded yet
function limoLoadjs(filename){
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
  document.getElementsByTagName("head")[0].appendChild(fileref)
}


// Loop until jQuery is loaded
function limoWaitForJQ( p ){
  if (typeof jQuery == 'undefined' || typeof jQuery().outerWidth == 'undefined' ) {
    setTimeout(function(){ limoWaitForJQ( p ) }, 500);
  }
  else limoWidget( p );
}

// Loop until widget html is loaded
function limoWaitForHTML( p ){
  if (typeof limoWidgetHTML == 'undefined') {
    setTimeout(function(){ limoWaitForHTML( p ) }, 500);
  }
  else limoWidget( p );
}

// Loop until jQuery UI is loaded, then set up the date picker
function limoLoadDatePicker(f){
	if( jQuery.ui && limo_jquery_ui_loaded ) {
	  jQuery(f+" #search_ride_date").limodatepicker({minDate:'0d',maxDate:'+1y',numberOfMonths:1});
	}
  else {
	  setTimeout(function(){ limoLoadDatePicker(f) }, 500);
  }
}


// This makes this global and callable from other functions
var limos_update_fields = function(){
	// Look for any text fields that should maintain some default value
	jQuery(".text_default").each(function(){
		// This is a weird check because if we use override, then we could have an empty 
		// field (in the case of an error on a reload)..
		if(jQuery(this).val() == ''){
			jQuery(this).addClass('text-input-help');
			jQuery(this).val(jQuery(this).attr('refid'));
		}
	});
	jQuery(".text_default").blur(function(){
		if(jQuery(this).val() == ''){
			jQuery(this).addClass('text-input-help');
			jQuery(this).val(jQuery(this).attr('refid'));
		}
	});
	jQuery(".text_default").bind('focus', function(){
		if(jQuery(this).val() == jQuery(this).attr('refid')){
			jQuery(this).removeClass('text-input-help');
			jQuery(this).val('');
		}
		return true;
	});
	// Hook up the text_default form button to clear the text_default fields so the vals don't get submitted
	var el=jQuery(".text_default:first").parents('form');

	jQuery(el).bind('submit', function(){ limos_clear_all_text_default_fields() });
}

// Goes through all the text_default input boxes and clears their default text, if it exists.
function limos_clear_all_text_default_fields(){
	jQuery(".text_default").each(function(){
		if(jQuery(this).val() == jQuery(this).attr('refid')){ jQuery(this).val(''); jQuery(this).removeClass('text-input-help'); }
	});
}



function limos_show_hide_drop_offs(f) {
	var val=jQuery(f+' #service_type :selected').val();
	if(val == 99 || val == 100 || val == 101 || val == 102 || val==''){
	  jQuery(f+' #search_between_time_div').hide();
		jQuery(f+' #search_dropoff_time_div').hide();
	}else{
	  jQuery(f+' #search_between_time_div').show();
		jQuery(f+' #search_between_time_div').css({'display':'inline'});
		jQuery(f+' #search_dropoff_time_div').css({'display':'inline'});
	}
}

function limos_show_hide_drop_location(f) {
	var val=jQuery(f+' #service_type :selected').val();
	if(val == 99 || val == 100 || val == 101 || val == 102 || val == 131072){
		jQuery(f+' #search_pickup_location_div').removeClass('wide');
		jQuery(f+' #search_dropoff_location_div').show();
	}else{	
		jQuery(f+' #search_dropoff_location_div').hide();
		jQuery(f+' #search_pickup_location_div').addClass('wide');
	}
}




// If first time is set, change second time to an hour later
function limosChangeTimeSlot(f) {
	var hs = jQuery(f+' #search_pickup_time').attr('selectedIndex');
	var et = jQuery(f+' #search_drop_off_time').attr('selectedIndex');
	if (hs <= 48) {
		var do_time_idx = hs+6;
		if (do_time_idx>48) {do_time_idx=48;}
		jQuery(f+' #search_drop_off_time').attr('selectedIndex', do_time_idx);
	} else {
		jQuery(f+' #search_drop_off_time').attr('selectedIndex', hs-48);
	}
}



function limos_change_labels(f) {
	var val=jQuery(f+' #service_type :selected').val();
	var pval=jQuery(f+' #search_pickup_place').val(); 
	var dval=jQuery(f+'#search_drop_off_place').val(); 

	if(val == 100) {
		// to airport
		jQuery(f+' #pickup_location_label').text('Pick-up address');
		jQuery(f+' #drop_off_location_label').text('Airport');
	} else if ( val == 99 ) {
		// from airport
		jQuery(f+' #pickup_location_label').text('Airport');
		jQuery(f+' #drop_off_location_label').text('Drop-off address');
	} else if (val == 102) {
		// to cruise port
		jQuery(f+' #pickup_location_label').text('Pick-up address');
		jQuery(f+' #drop_off_location_label').text('Cruiseport');
	} else if (val == 101) {
		// from cruise port
		jQuery(f+' #pickup_location_label').text('Cruiseport');
		jQuery(f+' #drop_off_location_label').text('Drop-off address');
	} else {
		jQuery(f+' #pickup_location_label').text('Pick-up address');
		jQuery(f+' #drop_off_location_label').text('Drop-off address');
	}
}


function limos_validate_form(f,p) {

	var alertmsg = '';
	var errfields = new Array();
	var extraerr = '';
	
	// clear default values
	jQuery(".text_default").each(function(){
		if(jQuery(this).val() == jQuery(this).attr('refid') ){
			jQuery(this).val('');
		}
	});
  
  if( p.contactInfo ){
    if (jQuery(f+' #passenger_first_name').val()=='')
  	{
  	  alertmsg += " 'First Name'\n";
  		errfields.push('#passenger_first_name');
  	}
  	if (jQuery(f+' #passenger_last_name').val()=='')
  	{
  	  alertmsg += " 'Last Name'\n";
  		errfields.push('#passenger_last_name');
  	}
  	if (jQuery(f+' #passenger_email').val()=='' && jQuery(f+' #passenger_phone_num').val()=='' )
  	{
  	  alertmsg += " 'Email' or 'Phone' \n";
  		errfields.push('#passenger_email');
  	}
  }
  
	svctype = jQuery(f+' #service_type').val();
	sdop = jQuery(f+' #search_drop_off_place').val();
	spup = jQuery(f+' #search_pickup_place').val();
	if (svctype=='')
	{ 
		alertmsg += " 'Type of Service'\n";
		errfields.push('#service_type');
  }
	if (jQuery(f+' #search_pax').val()=='')
	{
	  alertmsg += " 'Passengers'\n";
		errfields.push('#search_pax');
	}
	if (jQuery(f+' #search_ride_date').val()=='' )
	{
		alertmsg += " 'Date of service'\n";
		errfields.push('#search_ride_date');
	}
	if (jQuery(f+' #search_pickup_time').val()=='')
	{
		alertmsg += " 'Time of Pickup'\n";
		errfields.push('#search_pickup_time');
	}
	if ( jQuery(f+' #search_drop_off_time').val()=='' && (svctype!="99" && svctype!="100" && svctype!="101" && svctype!="102") )
	{
		alertmsg += " 'Expected drop-off Time'\n";
		errfields.push('#search_drop_off_time');
	}
	if (spup==''||spup=='Address, City, or Zip'||spup=='Airport Name, Code or City')
	{
		alertmsg += " 'Pick-up address'\n";
		errfields.push('#search_pickup_place');
	}
	if ((svctype=="99"||svctype=="100"||svctype=="101"||svctype=="102"||svctype=="131072") && (sdop==''||sdop=='Address, City, or Zip'||sdop=='Airport Name, Code or City')) 
	{
		alertmsg += " 'Drop-off address'\n";
		errfields.push('#search_drop_off_place');
	}
	if ( alertmsg=='' && svctype!="99" && svctype!="100" && svctype!="101" && svctype!="102" ) 
	{
		var drophour = parseInt(jQuery(f+' #search_drop_off_time').val().substring(0,2),10);
		if( jQuery(f+' #search_drop_off_time').val().substring(3)=="30" ) drophour += 0.5;
		var pickhour = parseInt(jQuery(f+' #search_pickup_time').val().substring(0,2),10);
		if( jQuery(f+' #search_pickup_time').val().substring(3)=="30" ) pickhour += 0.5;
		var timediff = drophour - pickhour;
		if( timediff < 0 ){ timediff += 24; /* account for times spanning midnight */ }
		if( timediff >= 12 && !confirm( 'You have selected a ride duration of '+timediff+' hours. Is this correct?\n\nClick OK to continue.' ) )
		{
	 	   alertmsg += " 'Time of Pickup'\n";
		   errfields.push('#search_pickup_time');
		   extraerr = "<br/>Please select a valid time span."
		}
	}
  
  jQuery(f+' .formError').remove(); /* clear out old errors */
	jQuery(f+' .errorRed').removeClass('errorRed');
	
	if (alertmsg!='' ) {	
		msg = "<div class='formError'><strong>Please provide all information below for accurate results.</strong>"+extraerr+"</div>";
		jQuery(msg).prependTo(f+' #limoscom');
		jQuery(errfields.toString()).each( function(){ 
			jQuery(this).parent().addClass('errorRed'); 
			jQuery(this).change(function(){
				jQuery(this).parent().removeClass('errorRed');
			});
		});
		return false;
	}
  
  
	// hide search button and show spinner -- only if no target is specified (submitting to same window)
	var tg = jQuery(f+' #limoscom #new_search').attr('target')
	if( !tg || tg == '' || tg == "_self" ){
	  if( !jQuery('#working').length ){
	    jQuery('<div style="display: none;" id="working"><img src="http://www.limos.com/images/shared/blue_spinner.gif" alt=""/> Searching...</div>').insertAfter(f+' #search_submit');
	  }
	  jQuery(f+' #search_submit').hide();
	  jQuery(f+' #working').fadeIn('slow');
	}
	return true;
}


