$(document).ready(function() {
	// remove any borders on last LI element
	$("ul").not('.left-bar-menu, .rounders, .cruise_description_navbar, .gallery-images.cruises, .holidays, table.hotel-listing ul, .banners, .hnav ul, #airline-selector, #hotel-tabs ul, #content-tabs ul, ul.destinations, #holiday-details ul').each(function(){
		 $(this).children("li:last").css({borderRight:"0",borderBottom:"0",background:"none",paddingRight:"0",margin:"0"});
	});

	$("table.hotel-listing ul").not('ul.accomodation').each(function(){
		 $(this).children("li:last").css({border:"0",margin:"0"});
	});

	$("ul.hnav").each(function(){
		 $(this).children("li:last").css({background:'none'});
	});

	$("ul.rounders").each(function(){
		 $(this).children("li:last").css({marginBottom:0});
	});

	if ( $('hr').length ){
		$('hr').parent().is('div.hr') || $('hr').wrap('<div class="hr"></div>');

		if ( $('hr').hasClass('spacemore').length ){
			$(this).parrent('div.hr').addClass('spacemore');
		}
	}

	// fancy box
	if ($.browser.version < 9){
		// no alpha
		$.fancybox.defaults.helpers.overlay.css['background-color'] = '#000000';
	}
	$('a.fancybox').click(function (){
		var $t = $(this), m = $t.metadata();
//		console.log($t, $t.data('fancybox'));
		if (!$t.data('fancybox')){
			$.fancybox.showLoading();
			$.getJSON('/gallery/?id=' + m['id'], function (r){
				$t.data('fancybox', r);
				$.fancybox.hideLoading();
				$t.trigger('click');
			});
		}
		else{
			$.fancybox(
				$t.data('fancybox')
				, {
					'padding'			: 10,
					'nextEffect'		: 'fade',
					'nextSpeed'			: 500,
					'prevEffect'		: 'fade',
					'prevSpeed'			: 500,
					'type'			  : 'image',
					'changeFade'		: 0
				}
			);
		}

		return false;
	});


	// print this page
	$('ul.utils a.print').click(function(){
		window.print();
		return false;
	});

	// add to favourites based on browser
	$('ul.utils a.favourites, #favourites').click(function(){
		// var url = 'http://www.kenwoodtravel.com/';
		var url = location.href;
		var title = document.title || 'Kenwood Travel';

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if ( window.external ) { // IE Favorite
			window.external.AddFavorite( url, title);
		} else if (window.opera && window.print) { // Opera Hotlist
			return true;
		}
		return false;
	});

	// submit forms via A element
	$('a.submit').click(function(){
		$(this).parent('form').submit();
		return false;
	});

	// handle more text on homepage
	$(function(){
		var $ex = $('#inner-cms-trigger'), $p = $ex.parent();
		if ($ex.length){
			$p.each(function (){
				var $this = $(this);
				if ($this.is('.expanded')){
					$this
						.data('oHeight', 225)
						.data('mHeight', $this.height())
						;
					if ($this.data('oHeight') > $this.data('mHeight')){
						$ex.hide();
					}
					else{
						$ex
							.html('Read less &laquo;')
							.toggle(
							function (){$(this).html('Read more &raquo;').toggleClass('expanded').parent().removeClass('expanded').animate({height: $(this).parent().data('oHeight')}, 500);},
							function (){$(this).html('Read less &laquo;').toggleClass('expanded').parent().addClass('expanded').animate({height: $(this).parent().data('mHeight')}, 500, function (){/* $(this).css({height: 'auto'}); */});}
						);
					}
				}
				else{
					$this
						.data('oHeight', $this.height())
						.css({height: 'auto'})
						.data('mHeight', $this.height())
						.css({height: $this.data('oHeight')})
						;
					if ($this.data('oHeight') > $this.data('mHeight')){
						$ex.hide();
						$this.css({height: 'auto'});
					}
					else{
						$ex
							.toggle(
							function (){
								var $this = $(this);
								$this.data('scrollTop', $('html').scrollTop());
								$this.html('Read less &laquo;').toggleClass('expanded').parent().addClass('expanded').animate({height: $(this).parent().data('mHeight')}, 500, function (){/* $(this).css({height: 'auto'}); */});
							},
							function (){
								var $this = $(this);
								$('html,body').animate({scrollTop: $this.data('scrollTop')}, 500, null, function(){
									$this.html('Read more &raquo;').toggleClass('expanded').parent().removeClass('expanded').animate({height: $this.parent().data('oHeight')}, 500);
								});
							}
						);
					}
				}
			});
		}
	});

	// hover gallery
	$('ul.gallery-images li a').hover(
		function(){
			if ($(this).attr('href')!='#') {
				var rel = $(this).attr('href');
				if ( !$.browser.msie ) {
					$('#main-image img').hide(1,function(){
						$('#main-image img').show(1).attr('src',rel);
					});
				}
				else {
					var sample = document.getElementById("main-image");

					var old_img = $('img.old', sample).get(0);
					var new_img = $('img.new', sample).get(0);
					if (!old_img){
						old_img = $('img', sample).css({'position': 'absolute', 'top': '0px', 'left': '0px', 'z-index': 1}).addClass('old').get(0);
						$(old_img).noContext();
					}
					if (!new_img){
						new_img = document.createElement('img');
						$(new_img).css({'position': 'absolute', 'top': '0px', 'left': '0px', 'z-index': 2}).addClass('new');
						new_img.style.width = 385 + 'px';
						new_img.style.height = 245 + 'px';
						sample.appendChild(new_img);
						$('img.new', sample).noContext();
					}
					new_img.filters[0].apply();
					new_img.src = $(this).attr('href');
					new_img.title = $(this).attr('title');
					new_img.filters[0].play();
				}
			}
		},
		function(){}
	);
	$('ul.gallery-images li a').click(function(){
		return false;
	});

	// hide all images under hotel gallery
	$('a.startinggallery').siblings('a').hide();

	// don't do anything if clicking on blank links
	$('a[href="#"]').click(function(){
		return false;
	});

	// qtip for icons
	if ( $('ul.features li img').length ) {
		$('ul.features li img').qtip({
			content: $(this).attr('alt'),
			show: { when: 'mouseover', delay: 1 },
			hide: 'mouseout',
			style: {
				tip: 'topLeft',
				name: 'blue' // Inherit from preset style
			},
			position: {
			  corner: {
				 target: 'bottomRight',
				 tooltip: 'topLeft'
			  }
		   }
		});
	}

	$.fn.qtip.styles.kenwood = {
		tip: 'rightTop'
		, name: 'cream'
		, background: '#DBE8F8'
		// , background: 'transparent'
		, width: 350
		, color: '#1B467B'
		, padding: '5px'
		, border: {
			width: 1,
			radius: 0,
			color: '#A9A8A8'
		}
		, name: 'cream'
	}

	// fix top drop down menu for ie
	$('ul.dropdown li').hover(
		function(){
			$(this).children('ul').css({visibility: 'visible'});
		},
		function(){
			$(this).children('ul').css({visibility: 'hidden'});
		}
	);

	// view hotel details
	$('#viewhotel-trigger').click(function(){
		$('#hotel-description').slideToggle();
		$(this).fadeOut();

		return false;
	});

	$('#hotel-description .less').click(function(){
		$('#hotel-description').slideToggle();
		$('#viewhotel-trigger').fadeIn();

		return false;
	});

	// preload images
	if ($('ul.gallery-images li a').length){
		$('ul.gallery-images li a').preload();
	}



	$('.full_description_wrapper').each(function(){
		$(this).prepend('<br/>');
		this._height = $(this).innerHeight();
		$(this).css({
			'height': '0px',
			'overflow': 'hidden'
		});
	});

	$('.full_description_toggle').click(function(){

		if(!$(this).hasClass('toggled'))
			var controller = $('.full_description_wrapper', $(this).parent().parent().next());
		else
			var controller = $(this).parent();


		if(!controller.innerHeight()){
			this._parent = $(this).parent();
			controller.append(this);
			$(this).html('- close');
			$(this).addClass('toggled')

			controller.animate({'height': controller.get(0)._height + $(this).outerHeight() + 'px'}, 'fast', null, function(){


				});
			}
		else {
			controller.animate({'height': '0px'}, 'fast', null, function(){
				$(this).css({'overflow': 'hidden'});
				var read_more = $('.full_description_toggle', this)
				read_more.html('+ read more');
				read_more.removeClass('toggled');
				$(read_more.get(0)._parent).append(read_more.get(0));
			});

			}

	});


	$('.toggle_height').each(function(){

		var controller = document.createElement('div');
		controller._parent = this;
		controller._height = $(this).innerHeight()
		$(this).after(controller).css({'overflow': 'hidden', 'height': '0px'});
		$(controller).html('+ read more').addClass('read_more').click(function(){

			if(!$(this._parent).innerHeight()){
				$(this._parent).animate({'height': this._height + 'px'}, 'fast');
				$(this).html('- close');
				}
			else {
				$(this._parent).animate({'height': '0px'}, 'fast');
				$(this).html('+ read more');
				}

		});

	});


	//Toggle collapse
	$('.toggle_collapse').each(function(){
		var caption = this.getElementsByTagName('caption');
		if(caption[0]){
			caption = caption[0];

			$(this).addClass('toggleable');
			$(this).get(0)._height = $(this).innerHeight();
			$(this).css({
				'height': $(this).hasClass('opened') ? 'auto' : $(caption).innerHeight() + 'px',
				'overflow': 'hidden'
				});
			if($.browser.msie){
				$(this).css({
					'margin-bottom': '10px'
					});
				}

			$(caption).prepend('<span class="close">'+ ( $(this).hasClass('opened') ? 'close' : 'open' ) +'</span><span class="toggle_sign"> '+ ( $(this).hasClass('opened') ? '-' : '+' ) +' </span>').addClass('toggleable').click(function(){
				var _parent = $($(this).parent().parent());
				if(_parent.innerHeight() == $(this).innerHeight()){
					_parent.animate({'height': _parent.get(0)._height + 'px'}, 'fast', null,function(){
						$(this).css({'height': 'auto'});
						});
					$('.toggle_sign', this).html('-');
					$('.close', this).html('close');
					}

				else{
					_parent.animate({'height': $(this).innerHeight()}, 'fast', function(){
						$(this).css({'overflow': 'hidden'});
						});
					$('.toggle_sign', this).html('+');
					$('.close', this).html('open');
					}

				});

			}

	});


	// search panel switch
	/* var toLoad = $('#fieldset-loader').attr('class');
	if ( toLoad != '' || toLoad != ' ' )
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/'+toLoad+'.html');
	else
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/default.html');

	$('#flight-hotel').click(function(){
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/default.html');
	});

	$('#flight-fly').click(function(){
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/flight-drive.html');
	});

	$('#hotel-only').click(function(){
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/hotel-only.html');
	});

	$('#flight-villa-car').click(function(){
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/resorts-listing.html');
	});

	$('#flight-villa').click(function(){
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/flight-villa.html');
	});

	$('#villa-only').click(function(){
		$('#fieldset-loader').load(APP_TPL_DIR+'search-panel/villa-only.html');
	}); */

	$('input.autoclear').focus(function(){
		var currentVal = $(this).val();										// Read initial field value
		$(this).val('');														// Clear initial value

		$(this).blur(function(){
			var getNewVal = $(this).val();										// Read new input value
			if ( getNewVal == '' || getNewVal == ' ' ) {
				$(this).val(currentVal);										// Switch to initial value
			}
		});
	});
	// disable context menu on middle images
	$("div#middle img, div#middle-large img").noContext();
	$('.add-new-testimonial-link').click(function(){
		$('.add-new-testimonial').fadeIn('slow');
	});
	$('.gallery-images.cruises li:nth-child(6n)').css('margin-right',0);
});

// Define indexOf for IE
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

jQuery.fn.log = function (msg) {
  console.log("%s: %o", msg, this);
  return this;
};

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
};

