$(document).ready(function(){
	
	// Fix select box style for IE
	$('#searchresultsbox div.input select, #searchresultsbox div.input input').wrap('<span class="selectWrap"></span>');

	
	
	var selectedPhotoId = 0;
	
	//$('#image-switcher-selected').css('opacity', 0.001);	
	$('#image-switcher a').click(function(){
		if(!$(this).is('.active')) {
			$('#image-switcher a').removeClass('active');
			$(this).addClass('active');			
			var image = $('img', $(this));
			$('#image-switcher-selected img').css('opacity', 1).stop().animate({opacity: 0.001 }, function(){
				
				var imageSrc = image.attr('src');
				var imageWidth = image.width();
				var imageHeight = image.height();
				var source = imageSrc.replace(/\/68\/50\//, '/320/240/');	
				
				$('#image-switcher-selected img').attr('src', source);
			});			
		}
		
		return false;
	});
	//$('#image-switcher a').click();
	$('#image-switcher-selected img').css('opacity', 0.999).load(function(){
		$(this).animate({opacity: 0.999 });
	})	
})

$(document).ready(function(){
	
	/**
	 * Login bar
	 */
	$('#logintab a').toggle(function(){
		$('#logincentre').height('119px');
		$('#logincentre').slideDown('normal');
	},function(){
		$('#logincentre').slideUp('fast');
	});
	
	$('#loadedRows div.rental_from input, #loadedRows div.rental_to input').each(function(i){
		$(this).attr('id', 'date-picker-' + i).datepicker({ dateFormat: 'dd/mm/yy'});
	});

	/**
	 * Rental period editor
	 */
	$('#new_rental_period').click(function(){
		$('#PeriodPriceSaveForm .emptyText').hide();
		$('#extraRowsPlaceholder').append($('#hiddenRow').html());
		$('#extraRowsPlaceholder .period_price_row:last-child .rental_description input').focus()
		attachRentalEvents();
		return false;
	})
	
	function attachRentalEvents(){
		$('#extraRowsPlaceholder div.rental_from input, #extraRowsPlaceholder div.rental_to input').each(function(i){
			$(this).attr('id', 'date-picker-extra-' + i).datepicker({ dateFormat: 'dd/mm/yy'});
		});						
		$('.deletePeriodPriceNew').click(function(){			
			if(confirm('Are you sure?')) {
				$(this).parent().parent().remove();
			}
			
			return false;
		});
	}
	attachRentalEvents();
		
	$('#PeriodPriceSaveForm .ajaxDelete').click(function(){
		var clicked = this;
		$.get($(this).attr('href'), {}, function(){
			$(clicked).parent().parent().remove();
		});
		return false;
	});
	

	var focusId = '';
	
	/**
	 * Form input hover tips
	 */
	
	function tooltipShow(id){
		tooltipId = id + '-tooltip';
		$('body').append('<div class="formHoverTip" id="' + tooltipId + '"><p>This field is required.</p></div>');
		$('#' + tooltipId).fadeOut(10).html('<p>' + $('#' + id).attr('alt') + '</p>');
		
		var position = $('#' + id).position();
		setTimeout(function(){
			$('#' + tooltipId).css( { 'top': position.top + 'px', 'left': (position.left + 315) + 'px' }).fadeIn();
		}, 20)			
	};
	
	function tooltipHide(id){
		tooltipId = id + '-tooltip';
		$('#' + tooltipId).fadeOut('fast', function(){
			$(this).remove();
		});
	}
	
	var hoverTipId = '';
	var focusTipId = '';
	/*$('textarea[alt], input[alt], select[alt]').hover(function(){
		var id = $(this).attr('id');	
		hoverTipId = id;	
		if (id != focusTipId) {
			tooltipShow(id);
		}
	}, function() {
		var id = $(this).attr('id');
		hoverTipId = '';
		if(id != focusTipId) {
			tooltipHide(id);					
		}
	}).*/
	$('textarea[alt], input[alt], select[alt]').focus(function(){
		var id = $(this).attr('id');
		focusTipId = id;
		if (id != hoverTipId) {
			tooltipShow(id);
		}
	}).blur(function(){
		var id = $(this).attr('id') + '';
		focusTipId = '';
		if (id != hoverTipId) {
			tooltipHide(id);
		}
	});
});	


jQuery.fn.textlimit=function(thelimit, speed) {
	var charDelSpeed = speed || 15;
	var toggleCharDel = speed != -1;
	var toggleTrim = true;
	if(this.attr('id') == undefined) {
		return;
	}
	
	var that = this[0];		

	jQuery('label', this.parent()).append('<br />(<span class="counter" id="' + this.attr('id') + '-counter"></span> remaining)');
	counter_el = '#' + this.attr('id') + '-counter';
	
	updateCounter();
	
	function updateCounter(){
		jQuery(counter_el).text(thelimit - that.value.length);
	};
	
	this.keypress (function(e){ if( this.value.length >= thelimit && e.charCode != '0' ) e.preventDefault() })
	.keyup (function(e){
		updateCounter();
		if( this.value.length >= thelimit && toggleTrim ){
			if(toggleCharDel){
				// first, trim the text a bit so the char trimming won't take forever
				that.value = that.value.substr(0,thelimit+100);
				var init = setInterval
					( 
						function(){ 
							if( that.value.length <= thelimit){ init = clearInterval(init); updateCounter() }
							else{ that.value = that.value.substring(0,that.value.length-1); jQuery(counter_el).text('trimming...  '+(thelimit - that.value.length)); };
						} ,charDelSpeed 
					);
			}
			else this.value = that.value.substr(0,thelimit);
		}
	});
	
};

$(document).ready(function(){
	$("#PropertyShortDescription").textlimit(150);
	$('#RegionSummary').textlimit(250);
	$("div.propertyboxsmall a, #brochureorder a, div.propertybox a, .regionboxcontents a, #whyadvertiseright a").bigTarget({ clickZone : 'div:eq(0)' });
	$(".moredetails a, #faqboxright a").bigTarget({ clickZone : 'div:eq(1)' });	
});


// bigTarget.js - A jQuery Plugin
// Version 1.0.1
// Written by Leevi Graham - Technical Director - Newism Web Design & Development
// http://newism.com.au
// Notes: Tooltip code from fitted.js - http://www.trovster.com/lab/plugins/fitted/

// create closure
(function($) {
  // plugin definition
  $.fn.bigTarget = function(options) {
    debug(this);
    // build main options before element iteration
    var opts = $.extend({}, $.fn.bigTarget.defaults, options);
    // iterate and reformat each matched element
    return this.each(function() {
      // set the anchor attributes
      var $a = $(this);
      var href = $a.attr('href');
      var title = $a.attr('title');
      // build element specific options
      var o = $.meta ? $.extend({}, opts, $a.data()) : opts;
      // update element styles
      $a.parents(o.clickZone)
        .hover(function() {
          $h = $(this);
          $h.addClass(o.hoverClass);
          if(typeof o.title != 'undefined' && o.title === true && title != '') {
            $h.attr('title',title);
          }
        }, function() {
          
          $h.removeClass(o.hoverClass);
          if(typeof o.title != 'undefined' && o.title === true && title != '') {
            $h.removeAttr('title');
          }
        })
        // click
        .click(function() {
          if(getSelectedText() == "")
          {
            if($a.is('[rel*=external]')){
              window.open(href);
              return false;
            }
            else {
              //$a.click(); $a.trigger('click');
              window.location = href;
            }
          }
        });
    });
  };
  // private function for debugging
  function debug($obj) {
    if (window.console && window.console.log)
    window.console.log('bigTarget selection count: ' + $obj.size());
  };
  // get selected text
  function getSelectedText(){
    if(window.getSelection){
      return window.getSelection().toString();
    }
    else if(document.getSelection){
      return document.getSelection();
    }
    else if(document.selection){
      return document.selection.createRange().text;
    }
  };
  // plugin defaults
  $.fn.bigTarget.defaults = {
    hoverClass  : 'hover',
    clickZone : 'li:eq(0)',
    title   : true
  };
// end of closure
})(jQuery);

