var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPod = navigator.userAgent.match(/iPod/i);
var isiPhone = navigator.userAgent.match(/iPhone/i);
var iOS = false;
var IE7 = (navigator.appVersion.indexOf("MSIE 7.")==-1) ? false : true;
var IE = $.browser.msie;
if(isiPad || isiPod || isiPhone) { iOS = true; }

$(document).ready(function() {
	
	
	//if(iOS) { init($('.location-map').attr('rel')); }

	var topZ = 1;
	var visibleAreaWidth = 620;
	var left = 0;
	var animating = false;
	var numImages = $('.carousel li').size();
	var frames = Math.ceil(numImages / 5);
	var currentFrame = 1;
	var showing = 1; // which large image is showing
	var geocoder;
	var map;
	var mapInited = false;
	
	if(iOS==true)
	{
		if(numImages > 1)
		{
			$('.images-relative img').click(
				function(e)
				{
					showing++;
					if(showing==numImages+1) { showing =1; }
					$('.show').removeClass('show').addClass('hide');
					$('.image-' + showing).removeClass('hide').addClass('show');
				}
			);
		}
	}
	
	
	$('.video-button').click(function(e) {
		
		e.preventDefault();
		
		if($('#video').is(':visible')) { 
			hideVideo();
		}
		else
		{
			showVideo();
		}
		
	});
		
	/* google maps */
	function init(address)
	{
		geocoder = new google.maps.Geocoder();		
		geocoder.geocode( { 'address': address}, function(results, status)
		{
			if (status == google.maps.GeocoderStatus.OK)
			{
				var image =  baseURL + '/images/icon-google-maps.png';
				
				var myOptions = {
					zoom: 15,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				}
				
				map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

				var rwMarker = new google.maps.Marker({
					position: results[0].geometry.location,	
					map: map,						
					icon: image
				});

				map.setCenter(results[0].geometry.location);
				
			} else {				
				alert("Geocode was not successful for the following reason: " + status);
			}
		});		
		
		mapInited = true;
	}

	
	function showMap()
	{
		$('#map_canvas').attr('style', 'left: 0px; z-index: 999;');
		
		// ie7 would put the controls behind the map, so this delay fixes that issue
		if(IE7==true)
		{
			setTimeout("delayZIndexForIE7()", 100);
		}
		
		$('.location-map').html('<span>Hide Map</span>');
		hideButtons();
	}
	
	var mapOn = false;
	var imageThatWasOnBeforeMapBroughtToFront;
	$('.location-map').click(
		
		function(e)
		{
			e.preventDefault();
			
			hideVideo();
			
			if(mapInited==false)
			{
				init($('.location-map').attr('rel'));
				mapInited = true;
			}
			
			if(mapOn==false) {
				mapOn = !mapOn;
				imageThatWasOnBeforeMapBroughtToFront = $('.show').attr('id');
				$('.show').removeClass('show').addClass('hide');
				showMap();
			} else {
				mapOn = !mapOn;		
				hideMap();
				if(imageThatWasOnBeforeMapBroughtToFront==undefined)
				{
					showVideo();
				}
				else
				{
					$('#' + imageThatWasOnBeforeMapBroughtToFront).removeClass('hide').addClass('show');
				}
			}
		}
	);
	
	function hideImages()
	{
		$('.show').each(function() {
			$(this).removeClass('show').addClass('hide');
		});
	}
	
	function hideMap()
	{
		$('#map_canvas').attr('style', 'left: -651px; z-index: -10;');
		$('.location-map').html('<span>Location Map</span>');
		mapOn = false;
		showButtons();
	}
	
	var videoHTMLContents;
	function hideVideo()
	{
		if($('#video').is(':visible')) {				
			
			// all browsers other than IE stop the youtube video when you navigate away from it
			// so we'll obliterate it and add it back in later
			//if(true || IE) {
				videoHTMLContents = $('#video').html();
				$('#video').html('');
			//}
			
			$('#video').hide();
			
			$('.video-button').text('Show video');
			
			if(imageThatWasOnBeforeMapBroughtToFront==undefined)
			{
				$('.image-1').addClass('show');
			}
			else
			{
				$('#' + imageThatWasOnBeforeMapBroughtToFront).removeClass('hide').addClass('show');
			}
		}
	}
	
	function showVideo()
	{
		imageThatWasOnBeforeMapBroughtToFront = $('.show').attr('id');
		$('.video-button').text('Hide video');
		hideMap();
		hideImages();
		
		//if(true || IE) {
			$('#video').html(videoHTMLContents);
		//}
		$('#video').show();
	}
	
	function hideButtons()
	{
		if(numImages > 1 && iOS==false)
		{
			$('.buttons').fadeOut(200);
		}
	}
	
	function showButtons()
	{
		if(numImages > 1 && mapOn==false && iOS==false)
		{
			if(showing==1)
			{
				$('#button-next').fadeIn(200);
			}
			else if(showing==numImages)
			{
				$('#button-previous').fadeIn(200);
			}
			else
			{
				$('.buttons').fadeIn(200);
			}	
		}
	}
	
	$('.buttons').click(
		function(e)
		{
			e.preventDefault();
							
			if(this.id=='button-previous')
			{
				if(showing > 1)
				{	
					if(!$('#video').is(':visible'))
					{
						showing--;
					}
				}
				
				if(showing==1)
				{
					$('#button-next').fadeIn(200);
					$('#button-previous').fadeOut(200);
				}
			}
			else
			{
				if(showing < numImages)
				{
					topZ++;	
					
					if(!$('#video').is(':visible'))
					{
						showing++;
					}
				}
				
				if(showing==numImages)
				{
					$('#button-previous').fadeIn(200);
					$('#button-next').fadeOut(200);
				}
			}
			
			$('.show').removeClass('show').addClass('hide');
			$('.image-' + showing).removeClass('hide').addClass('show');
			
			imageThatWasOnBeforeMapBroughtToFront = showing;
			
			hideMap();
			hideVideo();
		}
	);	
	
	$('.share').click(
		function(e)
		{
			e.preventDefault();
			$('.share-links').animate( { height: 'toggle', opacity: 'toggle' }, 1000, 'easeInOutSine');
		}
	);

	$('.carousel li a').click(
		function(e)
		{
			//if(iOS == true)
			//{
				//alert(id);
				e.preventDefault();
				
				var cssClass = $(this).attr('class');
				var id = this.id;
				
				showing = Number(cssClass.substring(11));
												
				hideMap();
				hideVideo();
				
				topZ++;
								
				$('.show').removeClass('show').addClass('hide');
				$('.image-' + showing).removeClass('hide').addClass('show');
			//}
		}
	);
	
	$('.images').hover(
		function() {
			showButtons();	
		},
		function() {
			hideButtons();
		}
	);
	
	$('.gallery-button-right').click(
		function(e)
		{
			e.preventDefault();
			if (!animating && currentFrame < frames)
			{
				animating=true;
				currentFrame++;
				left += visibleAreaWidth;
				$('.carousel').animate({ left: '-' + left }, 600, "easeInOutSine", function(){ animating=false;	});
			}
		}
	);
	
	$('.gallery-button-left').click(
		function(e)
		{
			e.preventDefault();
			if (!animating && currentFrame > 1)
			{
				animating=true;			
				currentFrame--;				
				left -= visibleAreaWidth;				
				$('.carousel').animate({ left: '-' + left }, 600, "easeInOutSine", function(){ animating=false; });
			}
		}
	);

	$('#contact-send').click(
		function(e)
		{
			e.preventDefault();
			
			var cssClass = $(this).attr('class');
			
			$.ajax({
			   type: "POST",
			   url: baseURL + "/inc/ajax-contact.php",
			   data: $("#" + cssClass + " form").serialize(),
			   success: success,
			   error: error
			 });			
			
			$('#loader').show();
			$('#contact-send').hide();
		}
	);
	
	$('.email-the-agent').click(
		function(e)
		{
			e.preventDefault();
			$('#' + this.id + '-form').animate( { height: 'toggle', opacity: 'toggle' }, 1000, 'easeInOutSine');
		}
	);	
	
	var success = function(data, textStatus, XMLHttpRequest)
	{		
		if(data=='success')
		{
			$('.contact-form form').slideUp(500)
			$('.message').html('Thanks.<br /></p><p>Your message has been sent.<br />An agent will be in touch with you shortly.</p>');
			$('.message').fadeIn();
			$('#loader').hide();
			$('#contact-send').show();
		}
		else
		{
			obj = $.parseJSON(data);
			
			var message = "Please ensure all required fields are filled<br /><ul>";
			
			for(var key in obj)
			{
				message +=	'<li>' + obj[key] + "</li>";
				$('#' + key).effect( 'highlight', null, 1000);
			}
			
			message += '</ul>';
			
			$('.message').html(message);
			$('.message').show();

			error(null, null, null);
		}
	}
	
	var error = function(event, request, settings)
	{
		$('#loader').hide();
		$('#contact-send').show();
 	}
	
	var isFavourite = false;
	$('.add-to-my-favourites-link').click(function(e){
	
		e.preventDefault();
		var id = $(this).attr('id');
		var value = $('#listing-heading').html();


		if( $('.add-to-my-favourites-link').hasClass('minus') == true) { isFavourite=true; } else { isFavourite=false; }
		
		$('.loader-favourites').show();
		$('.favourites-text').hide();
		
		$.ajax({
			type: "POST",
			url: baseURL + "/inc/manage-favourites.php?id=" + id + "&value=" + value,
			data: 'id=' + id + '&value=' + value,
			success: addToFavouritesSuccess,
			error: addToFavouritesError
		});
	});
	
	var addToFavouritesSuccess = function(data, textStatus, XMLHttpRequest)
	{
		if (!isFavourite) {
			$('.favourites-text').html('<span>Remove</span> from my favourites');
		} else {
			$('.favourites-text').html('<span>Add</span> to my favourites');
		}
		
		$('.loader-favourites').hide();
		$('.favourites-text').show();		
		
		if (data.search('<dt>')!=-1)
		{
			$('.add-to-my-favourites-link').removeClass('plus');
			$('.add-to-my-favourites-link').addClass('minus');
			$('.my-favourites dl').append(data);
		} else{
			$('.add-to-my-favourites-link').removeClass('minus');
			$('.add-to-my-favourites-link').addClass('plus');
			$('.' + data ).fadeOut(500);
		}
		
		isFavourite = !isFavourite;
	}
	
	var addToFavouritesError = function(event, request, settings)
	{	
		$('.loader-favourites').hide();
		$('.favourites-text').show();
		alert('Adding this property to your favourites is not available at this time. Please try again later.');
		isFavourite = !isFavourite;
	}
	
	$('#send-to-friend-send').click(
		function(e)
		{
			e.preventDefault();

			$.ajax({
			   type: "POST",
			   url: baseURL + "/inc/ajax-send-to-friend.php",
			   data: $(".send-to-friend-form form").serialize(),
			   success: sendToFriendSuccess,
			   error: sendToFriendError
			 });			
			
			$('.send-to-friend-loader').animate( { height: 'toggle', opacity: 'toggle' }, 1000, 'easeInOutSine');
			$('#send-to-friend-send').toggle();
		}
	);
	
	var sendToAnotherFriend = function(e)
	{
		e.preventDefault();
		$('#recipients-email').val('');
		$('.send-to-friend-form form').slideDown(500);
	}

	var sendToFriendSuccess = function(data, textStatus, XMLHttpRequest)
	{
		$('.send-to-friend-loader').hide();
		$('#send-to-friend-send').show();		
		if(data=='success')
		{
			$('.send-to-friend-form form').slideUp(500);
			$('.send-to-friend-message').html('Thanks.<br /></p><p>Your message has been sent. <a href="#" class="send-to-another-friend">Click here to send to another friend</a>.</p>');
			$('.send-to-another-friend').bind('click', sendToAnotherFriend);
			
			$('.send-to-friend-message').fadeIn();
		}
		else
		{
			obj = $.parseJSON(data);
			
			var message = "Please ensure all required fields are filled<br /><ul>";
			
			for(var key in obj)
			{
				message +=	'<li>' + obj[key] + "</li>";
				$('#' + key).effect( 'highlight', null, 1000);
			}
			
			message += '</ul>';
			
			$('.send-to-friend-message').html(message);
			$('.send-to-friend-message').show();

			error(null, null, null);
		}
	}
	
	var sendToFriendError = function(event, request, settings)
	{
		$('#loader').hide();
		$('#contact-send').show();
 	}	
	
	$('.send-to-friend').click(
		function(e)
		{
			e.preventDefault();
			$('.send-to-friend-form').animate( { height: 'toggle', opacity: 'toggle' }, 1000, 'easeInOutSine');
		}
	);
});

function delayZIndexForIE7()
{
	$('#map_canvas').attr('style', 'left: 0px; z-index: 2;');	
}
