// This section doesn't wait for document.ready.  It is executed as soon as it is parsed
// this is ok for some things because the javascript file is included at the bottom of the 
// page.  Be careful what you put in this section, only put the things in that need it.
(function($){
  //	Add the class "hasJS" to the body element.
	$('body').addClass('hasJS');
})(jQuery);

jQuery(function($) {

	
	//	Add a class of "odd" to every second row in a table.
	$('table tbody tr:nth-child(odd)').addClass('odd');
	
	//Facebox
	$('a[rel*=facebox]').facebox({
		loadingImage : '/javascripts/facebox/loading.gif',
		closeImage   : '/javascripts/facebox/closelabel.gif'
	});
	
	//Facebox IE6 cludge
	if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
		$(document).bind("beforeReveal.facebox", function(){ $("select").hide();} );
		$(document).bind("close.facebox", function(){ $("select").show(); });
	}


	
	//	Add "dismiss" links to notifications.
	$('.feedback').each(function() {
		$(this).prepend('<a class="dismissal" href="#">Dismiss</a>');
	});
	//	Attach functionality to "dismiss" links in notifications.
	$('.feedback a.dismissal').click(function() {
		$(this.parentNode).slideToggle('fast');
		return false;
	})
	
	//	Add a class of "highlighted" to promo elements when they are moused over.
	$('.promo').hover(
		function() {
			$(this).addClass('highlighted');
		},
		function() {
			$(this).removeClass('highlighted');
		}
	);
	
  $('form.product fieldset.connected').each(function() {
    var selected_area = $('#tour_area_id').val();
    $('#tour_area_id').replaceWith('<select name="product[area_id]" id="tour_area_id" disabled="disabled"></select>');
    var country_id = $('#country_id').val();

    if(country_id != "") {      
      $('#tour_area_id').load('/areas?country_id='+country_id+'&format=js&all=all', null, function() {
        $('#tour_area_id option').each(function() {
          var option = $(this);
          if(option.text() == selected_area) {
            option.attr('selected', 'selected');
          }
        });
      });
      $('#tour_area_id').removeAttr('disabled');
    }
    $('#country_id').change(function() {
      $('#tour_location').val('');
      $('#location-options').hide();
      $('#location-options ul').html('');
      $('#tour_area_id').removeAttr('disabled');     
      var selected = $(this).val();
      $('#tour_area_id').load('/areas?country_id='+selected+'&format=js&all=all',
                               null,
                               function(){
                                 $('#tour_area_id').trigger('change');  
                               });
           
    });
    $('#tour_area_id').change(function() {
      var selected = $(this).val();
      $('#location-options').hide();
      $('#location-options ul').html('');
      //console.log(selected)
      $.get('/geocodes',
            'area_id='+selected,
            function (data) {
              map.setCenter(new GLatLng(data.lat, data.lng), 6);
              marker.setLatLng(new GLatLng(data.lat, data.lng));
              marker.show();
              $('#product_lat').val(data.lat)
              $('#product_lng').val(data.lng)
              $('#product_zoom').val(6)
            },
            'json');
    });
    $('#location-search').show().click(function(){
      $('#tour_location').addClass('loading');
      var country = $('#country_id option:selected').text();
      var area = $('#tour_area_id option:selected').text();
      var query = $('#tour_location').val();
      $.ajax({
        url: '/geocodes/search',
        dataType: 'json',
        data: {
          //area: area, // Removed - some locations were not being found when scoped with area
          country: country,
          query: query
        },
        success: function(data){
          var location_options = $('#location-options')
          $('#location-errors').hide();
          if (data.length === 1){
            location_options.hide();
            map.setCenter(new google.maps.LatLng(data[0].lat,data[0].lng));
            marker.setPosition(new google.maps.LatLng(data[0].lat,data[0].lng));
            $('#product_lat').val(data[0].lat)
            $('#product_lng').val(data[0].lng)
            $('#product_zoom').val(data[0].zoom)
            $('#tour_location').val(data[0].address);
          }else{
            location_options.show();
            $('ul',location_options).html('');
            $.each(data,function(){
              var location = this;
              var li = $("<li></li>");
              $('<a href="#">'+location.address+'</a>')
                .click(function(){
                  map.setCenter(new GLatLng(location.lat, location.lng), location.zoom);
                  marker.setPosition(new GLatLng(location.lat, location.lng));
                  $('#product_lat').val(location.lat)
                  $('#product_lng').val(location.lng)
                  $('#product_zoom').val(location.zoom)
                  $('#tour_location').val(location.address);
                  return false;
                })
                .appendTo(li);
              $('ul',location_options).append(li);
            });
          };          
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $('#location-errors').show()
          $('#location-errors .error').html(XMLHttpRequest.responseText);
        },
        complete: function(){
          $('#tour_location').removeClass('loading');
        }
      });
      return false
    });
  });

	//	Whenever a form element is focused, add a class of 'focused' to the containing element.
	$(':input').focus(function() {
		$('.focused').removeClass('focused');
		$(this).parents('.container').addClass('focused');
	});
	$(':input').blur(function() {
		$(this).parents('.container').removeClass('focused');
	});
	// Remove focussed state when a key has been pressed.  This is so the contextual help doesn't get in the way of resized text boxes
	$('.focused textarea').livequery(function(){
	  $(this).keyup(function(){
	    $(this).parents('.container').removeClass('focused');
	  })
	});
	
	$('.fieldWithErrors').parents('.container').addClass('error');
	
	$('input#tour_operator_company').blur(function(){
    var value = $('input#tour_operator_company')[0].value;
    if($('input#tour_operator_url')[0].value == ''){
      $('input#tour_operator_url')[0].value = cleanseString(value);
    }
  });
  

  // Track outbound links with google analytics
  // http://css.dzone.com/news/update-tracking-outbound-click
  $('a.outbound').click(function() {
    var $a = $(this);
    var category = 'outbound';
    var event = 'click';
    var label = $a.text();
    pageTracker._trackEvent(category, event, label);
  });
  

  // Track new enquiries with google anlaytics
  $('button.new-enquiry').click(function(){
    pageTracker._trackEvent('enquiry','submit');
  });
  
});

function cleanseString(value){
  value = value.toLowerCase();
  return value.replace(/\W|_/g,'');
}

//Nested forms
replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}

$('a.add-nested-item').livequery('click',function(){
  var template = eval(this.href.replace(/.*#/, ''))
  $(this.rel).append(replace_ids(template));
  return false;
});

$('.add-nested-item-lvl2').livequery('click',function(){
  var template = eval(this.href.replace(/.*#/, ''));
  var parent_id = $(this).attr('data').match(/\[(\d+)\]/)[1]; // Note, this requires that the link has a data attribute set with the f.object_name value
  var parent = $(this).closest('.parent-form')
  template = template.replace(/(attributes[_\]\[]+)\d+/g, "$1"+parent_id)
  $(this.rel,parent).append(replace_ids(template));
  return false
});


$('a.remove').livequery('click',function(){
  target = this.href.replace(/.*#/, '.');
  $(this).closest(target).hide();
  $(this).siblings('input[type=hidden]').val(1);
  return false;
});


$('a.remove-newrecord').livequery('click',function(){
  target = this.href.replace(/.*#/, '.');
  $(this).closest(target).remove();
  return false;
});

//This makes abbr styleable in IE.
document.createElement('abbr');

// @Nick Rigby - Function for form input placeholders
(function($){
  $.fn.placeholder=function(options){
    var defaults={
      defaultTextColor:"#b2adad",
      activeTextColor:"#333"
    };

    var options=$.extend(defaults,options);
	var values=new Array();

    return this.each(
		function()
		{
      		var obj=$(this);
      		obj.find('input[type=text]').each(
				function(i)
				{
					if(!$(this).val() == '')
					{
						$(this).css({color:options.defaultTextColor});
						values.push({ 'id' : $(this).attr('id'), 'value' : $(this).val() });
					}
				}
			).focus(
				function()
				{
					for(i=0;i<values.length;i++)
					{
						if($(this).attr('id') == values[i].id)
						{
							if($(this).val() == values[i].value) $(this).val('').css({color:options.activeTextColor});
						}
					}
				}
			).blur(
				function()
				{
					if($(this).val() == '')
					{
						for(i=0;i<values.length;i++)
						{
							if($(this).attr('id') == values[i].id) $(this).val(values[i].value).css({color:options.defaultTextColor});
						}
					}
				}
			);
		});
	};
})(jQuery);
// @Nick Rigby - End Function

(function($){
  $.fn.autofill=function(options){
    var defaults={
      value:'First Name',
      defaultTextColor:"#b2adad",
      activeTextColor:"#333"
    };
    var options=$.extend(defaults,options);
    return this.each(function(){
      var obj=$(this);
      if(obj.val() == options.value){obj.val('')};
      if(obj.val() == ''){
        obj.css({
            color:options.defaultTextColor
          })
          .val(options.value)
          .focus(function(){
            if(obj.val()==options.value){
              obj.val("").css({color:options.activeTextColor});
            }})
          .blur(function(){
            if(obj.val()==""){
              obj.css({color:options.defaultTextColor}).val(options.value);
            }});
      }

});};})(jQuery);


// No $.ready here, this JS is included after the 
// nav is available so don't need it
(function($){
	//	Make the targets of internal links toggleable.
	$('a.toggler').click(function() {
    $this = $(this);
		var id = $this.attr('href');
		$(id).slideToggle('fast').toggleClass('showing');
		$this.toggleClass('displaying');
		$(this.parentNode).toggleClass('displaying-parent');
		return false;
	});
	
	// Nasty kludge for the home page to hide instructional background image.
	$('.home #navigation .browse a.toggler').click(function() {
		$('.home #navigation').removeClass('displaying-parent');
		$('.home #navigation .content .showing').each(function() {
			$('.home #navigation').addClass('displaying-parent');
		});
	});

}(jQuery));

