var base_folder = '/';
var thisProperty = '/img/icons/this-property.png';
var officeIcon = base_folder+'img/icons/office-map-icon.png';
var devMarkerIcon = base_folder+'img/icons/dev-map-icon.png';
var smallSchoolIcon = base_folder+'img/icons/school-small.png';
var smallTrainIcon = base_folder+'img/icons/train-small.png';
var largeSchoolIcon = base_folder+'img/icons/school.png';
var largeTrainIcon = base_folder+'img/icons/train.png';
var step = 25;
var scrolling = false;
var propertyScrollerLeftPosition = 0;
var propertyScrollerItemWidth = 0;
var totalSearchResultElements = 1;

var paginationIncrement = 0;
var paginationMax = 0;
var leftNavVisible 		= false;

$(document).ready( function() {
	
	$('input, textarea').placeholder();
	if ( $('#select_time input').length > 0 ) { $('#select_time input').customInput(); }
	if ( $('.land_sale_type input').length > 0 ) { $('.land_sale_type input').customInput(); }
	
	if ( $('form#adv_search select').length > 0 ) { 
		$("form#adv_search select").selectbox().bind('change', function(){
			$("form#adv_search select[name='"+$(this).attr('name')+"']").find("option[value='"+$(this).val()+"']").attr('selected',true);
		});
	}
	
	if ( $('#search_map #area_map').length > 0 ) { $("#area_map").mapz({ zoom : true, createmaps : true, mousewheel : true }); }
	
	//if ( $("#search_criteria").length > 0 ) {
	//	$("#search_criteria select").selectbox().bind('change', function(){
	//		$("form#search_criteria select[name='"+$(this).attr('name')+"']").find("option[value='"+$(this).val()+"']").attr('selected',true);
	//	});
	//}
	
	if ( $('input#custom_file_upload').length > 0 ) { triggerFileUploader( $('input#job_app_id').val() ); }
	if ( $('#development_map').length > 0 ) { loadDevelopmentMap(); }
	if ( $('#office_map').length > 0 ) { loadOfficeMap(); }
	if ( $('#map_search_content').length > 0 ) { loadBlankMap(); }
	if ( $('#search_results_map').length > 0 ) { loadPropertySearchMap(); }
	
	if ( $('#search_results_wrapper #slide_nav_right a').length > 0 ) {
		var offSetAmount = parseFloat( '-'+( $(".pagination_wrapper a.current").position().left ) ) + 125;
		$('.pagination_wrapper').animate({left: offSetAmount},'slow');
		paginationIncrement = parseFloat( $('#search_results_wrapper').attr( 'data-inc' ) );
		paginationMax 		= parseFloat( $('#search_results_wrapper').attr( 'data-max' ) );
		$('#search_results_wrapper #slide_nav_right a').bind("click", searchResultsScrollerRight );
		$('#search_results_wrapper #slide_nav_left a').bind("click", searchResultsScrollerLeft );
	}
	
	if ( $('#market_review_details').length > 0 ) { 
		$("#market_scroll_down").bind("click", function(event) { event.preventDefault(); $("#market_review_details").animate({ scrollTop: "+=" + step + "px" });})
		.bind("mouseover", function(event) { scrolling = true; scrollContent("down");})
		.bind("mouseout", function(event) { scrolling = false; });
	}
	
	if ( $('#latest_properties_wrapper #slide_nav_right').length > 0 ) { 
		initializeLatestPropertiesScroller();
		$('#latest_properties_wrapper #slide_nav_right a').bind("click", latestPropertiesScrollerRight );
		$('#latest_properties_wrapper #slide_nav_left a').bind("click", latestPropertiesScrollerLeft );
	}
	
});


function loadNextProperties( start , end , slideDir ) {
	
	$('#search_results_wrapper #loading').show();
	$('#latest_properties_wrapper #slide_nav_right a').unbind();
	$('#latest_properties_wrapper #slide_nav_left a').unbind();
	
	$.post( 
		base_folder + 'includes/ajax/load-properties.php' , 
		{ start: start, end: end, max_price: $.getUrlVar('max_price'), search_term: $.getUrlVar('search_term'), within: $.getUrlVar('within'), beds: $.getUrlVar('beds'), sort_order: $.getUrlVar('sort_order'), sort_type: $.getUrlVar('sort_type'), office: $.getUrlVar('office') },
		function( data ) {
			if ( data != false ) {
			
				totalSearchResultElements++;
			
				if ( slideDir == 'right' ) { $('ul#search_results_list').last().after( '<ul id="search_results_list" class="results_ele_'+totalSearchResultElements+'" style="left:880px;"></ul>' ); }
				else { $('ul#search_results_list').last().before( '<ul id="search_results_list" class="results_ele_'+totalSearchResultElements+'" style="left:-880px;"></ul>' ); }
				
				$.each(data, function( i , property ) {
					var propInfo = '<li>';
					if ( property.status == 'Under Offer' ) {
						propInfo += '<div class="property_photo"><a href="'+property.link+'"><img src="'+property.photos+'" alt="'+property.town+'" title="'+property.town+'" /></a><a href="'+property.link+'"><img src="/img/overlays/under-offer-small.png" alt="Under Offer" title="Under Offer" /></a></div>';
					}else if ( property.status == 'Sold' ) {
						propInfo += '<div class="property_photo"><a href="'+property.link+'"><img src="'+property.photos+'" alt="'+property.town+'" title="'+property.town+'" /></a><a href="'+property.link+'"><img src="/img/overlays/sold-small.png" alt="Sold" title="Sold" /></a></div>';
					} else if ( property.new_home == 1 ) {
						propInfo += '<div class="property_photo"><a href="'+property.link+'"><img src="'+property.photos+'" alt="'+property.town+'" title="'+property.town+'" /></a><a href="'+property.link+'"><img src="/img/overlays/new-home-small.png" alt="New Home" title="New Home" /></a></div>';
					} else {
						propInfo += '<div class="property_photo"><a href="'+property.link+'"><img src="'+property.photos+'" alt="'+property.town+'" title="'+property.town+'" /></a></div>';
					}
					propInfo += '<div class="property_details"><span>'+property.beds+' Beds</span><span>'+property.public+' Public</span></div>';
					propInfo += '<p class="address"><span>'+property.town+'</span><br/>'+property.street+'</p>';
					if ( property.price != false ) { propInfo += '<p class="price">'+property.price_type+' &pound;'+property.price+'</p>'; } 
					else { propInfo += '<p class="price">'+property.price_type+'</p>'; }
					propInfo += '<p>'+property.features+'<a href="'+property.link+'">...view details</a></p>';
					propInfo += '<ul>';
					propInfo += '<li><a href="'+property.link+'">View Images</a></li>';
					propInfo += '<li><a href="'+property.link+'">View on Map</a></li>';
					propInfo += '<li><a href="'+property.link+'">View Floorplans</a></li>';
					propInfo += '<li><a href="#">Add to Favourites</a></li>';
					propInfo += '<li><a href="'+base_folder+'index.php?action=view_office&id='+property.oid+'">Contact Branch</a></li>';
					propInfo += '</ul>';
					propInfo += '</li>';
					
					$( '.results_ele_'+totalSearchResultElements ).append( propInfo );
					
				});
				
				// Slide Next Set In...
				$('ul#search_results_list').each(function(index) {
					var startPos = parseFloat( $(this).css('left') );
					if ( slideDir == 'right' ) { 
						$(this).animate( { left: "-=810px" } , 1000 , 'linear' , function() { $('#search_results_list:not(.results_ele_'+totalSearchResultElements ).remove(); } ); 
					} else { 
						$(this).animate( { left: "+=950px" } , 1000 , 'linear' , function() { $('#search_results_list:not(.results_ele_'+totalSearchResultElements ).remove(); } ); 
					}
				});
				
				$('#search_results_wrapper #loading').hide();
				$('#latest_properties_wrapper #slide_nav_right a').bind("click", searchResultsScrollerRight );
				$('#latest_properties_wrapper #slide_nav_left a').bind("click", searchResultsScrollerLeft );
			}
		},
		'json'
	);
}


function searchResultsScrollerRight( event ) {
	event.preventDefault();
	if ( leftNavVisible ) { var paginationIndexLeft = parseFloat( $('#search_results_wrapper #slide_nav_left a').attr( 'data-index' ) ); } else { var paginationIndexLeft = 1; }
	var paginationIndexRight = parseFloat( $(this).attr( 'data-index' ) );
	
	$(this).attr( 'data-index' , (paginationIndexRight + paginationIncrement) );
	$('#search_results_wrapper #slide_nav_left a').attr( 'data-index' , (paginationIndexLeft + paginationIncrement) );
	
	// Reset Index
	if ( (paginationIndexRight + paginationIncrement) > paginationMax ) { 
		$(this).hide();
		if ( !leftNavVisible ) {
			$('#search_results_wrapper').prepend( '<div id="slide_nav_left"><a data-index="1" href="#"><img src="img/navigation/left-arrow.png" alt="Left" title="Previous" /></a></div>' );
			$('#search_results_wrapper #slide_nav_left a').bind("click", searchResultsScrollerLeft );
			leftNavVisible = true;
		} else {
			$('#search_results_wrapper #slide_nav_left a').show();
		}
	} 
	else {
		
		// Show Left button if not already visible
		if ( !leftNavVisible ) {
			$('#search_results_wrapper').prepend( '<div id="slide_nav_left"><a data-index="1" href="#"><img src="img/navigation/left-arrow.png" alt="Left" title="Previous" /></a></div>' );
			$('#search_results_wrapper #slide_nav_left a').bind("click", searchResultsScrollerLeft );
			leftNavVisible = true;
		} else {
			$('#search_results_wrapper #slide_nav_left a').show();
		}
	}
	
	// Move the page counter....
	$('.pagination a.current').next('a').addClass( 'current' );
	$('.pagination a.current:even').removeClass( 'current' );
	if ( paginationMax > 5 && paginationIndexRight > 20 ) {
		$('.pagination_wrapper').animate( { left: "-="+$('.pagination a.current').next('a').outerWidth()+"px" } );
	}
	
	loadNextProperties( paginationIndexRight , (paginationIndexRight+paginationIncrement) , 'right' );

}


function searchResultsScrollerLeft( event ) {
	event.preventDefault();
	var paginationIndexLeft = parseFloat( $(this).attr( 'data-index' ) );
	var paginationIndexRight = parseFloat( $('#search_results_wrapper #slide_nav_right a').attr( 'data-index' ) );
	
	$(this).attr( 'data-index' , (paginationIndexLeft - paginationIncrement) );
	$('#search_results_wrapper #slide_nav_right a').attr( 'data-index' , (paginationIndexRight - paginationIncrement) );
	
	// Reset Index
	if ( (paginationIndexLeft - paginationIncrement) < 1 ) { $(this).hide(); $('#search_results_wrapper #slide_nav_right a').show(); } 
	if ( (paginationIndexRight-paginationIncrement) <= paginationMax ) { $('#search_results_wrapper #slide_nav_right a').show(); }
	
	// Move the page counter....
	$('.pagination a.current').prev('a').addClass( 'current' );
	$('.pagination a.current:odd').removeClass( 'current' );
	if ( paginationMax > 5 && paginationIndexLeft > 10 ) {
		$('.pagination_wrapper').animate( { left: "+="+$('.pagination a.current').next('a').outerWidth()+"px" } );
	}
	
	loadNextProperties( paginationIndexLeft , (paginationIndexLeft+paginationIncrement) , 'left' );
	
}



function initializeLatestPropertiesScroller() {
	// Record starting postition...
	propertyScrollerLeftPosition = parseFloat( $('#latest_properties_wrapper #slide_nav_right').parent().parent().find('ul').css( 'left' ) );
	propertyScrollerItemWidth = $('#latest_properties_wrapper #slide_nav_right').parent().parent().find('ul').find('li').outerWidth(true);
	propertyScrollerRightPosition = parseFloat( ( '-' + propertyScrollerItemWidth * $('#latest_properties_wrapper #slide_nav_right').parent().parent().find('ul').children().length ) ) + ( 2 * propertyScrollerItemWidth ) + propertyScrollerLeftPosition;
	
	if ( $('#latest_properties_wrapper #slide_nav_right').parent().parent().find('ul').children().length <= 2 ) {
		$('#latest_properties_wrapper #slide_nav_left a').hide();
		$('#latest_properties_wrapper #slide_nav_right a').hide();
	} else { $('#latest_properties_wrapper #slide_nav_left a').hide(); }
}

function latestPropertiesScrollerLeft( event ) {
	event.preventDefault();
	if ( propertyScrollerLeftPosition == parseFloat( $(this).parent().parent().find('ul').css( 'left' ) ) ) {}
	else { 
		$(this).parent().parent().find('ul').animate(
			{ left: "+=" + propertyScrollerItemWidth + "px" },
			500,
			function() {
				if ( propertyScrollerLeftPosition == parseFloat( $(this).parent().parent().find('ul').css( 'left' ) ) ) { $('#latest_properties_wrapper #slide_nav_left a').hide(); $('#latest_properties_wrapper #slide_nav_right a').show(); }	
				else { $('#latest_properties_wrapper #slide_nav_right a').show(); }
			}
		);
	}
}

function latestPropertiesScrollerRight( event ) {
	event.preventDefault();
	$('#latest_properties_wrapper #slide_nav_left a').show();
	if ( propertyScrollerRightPosition == parseFloat( $(this).parent().parent().find('ul').css( 'left' ) ) ) {}
	else { 
		$(this).parent().parent().find('ul').animate(
			{ left: "-=" + propertyScrollerItemWidth + "px" },
			500,
			function() {
				if ( propertyScrollerRightPosition == parseFloat( $(this).parent().parent().find('ul').css( 'left' ) ) ) { $('#latest_properties_wrapper #slide_nav_right a').hide(); $('#latest_properties_wrapper #slide_nav_left a').show(); }
				else { $('#latest_properties_wrapper #slide_nav_left a').show(); }
			}	
		);
	}
}


function scrollContent(direction) {
    var amount = (direction === "up" ? "-=1px" : "+=1px");
    $("#review_content").animate({ scrollTop: amount }, 1, function() { if (scrolling) { scrollContent(direction); } });
}


function triggerFileUploader( folder_id ) {
	
	$('#file_upload_2').hide();
	$('#file_upload_3').hide();
	$('#file_upload_status').val( '1' );
	
	$('#custom_file_upload').uploadify({
		'uploader'       : base_folder + 'themes/uploadify/uploadify.swf',
		'script'         : base_folder + 'themes/uploadify/uploadify.php',
		'cancelImg'      : base_folder + 'themes/uploadify/cancel.png',
		'folder'		 : folder_id,
		'multi'          : true,
		'auto'           : true,
		'fileExt'        : '*.pdf;*.doc;*.docx;*.txt;*.rtf',
		'fileDesc'       : 'Document Files (.PDF, .DOC, .DOCX, .TXT, .RTF)',
		'queueID'        : 'custom-queue',
		'queueSizeLimit' : 5,
		'simUploadLimit' : 3,
		'sizeLimit'   	 : 1002400,
		'removeCompleted': true,
		'onSelectOnce'   : function(event,data) {
  			$('#status-message').text(data.filesSelected + ' files have been added to the queue.');
		},
		'onAllComplete'  : function(event,data) {
  			$('#complete-msg').html( '<p id="form_sent_message" class="success_display">Thank you for uploading your documents.</p>' );
		}
	});

}


// ------------------------------------------------------------------------------------------
// Map Functions
// ------------------------------------------------------------------------------------------
function loadBlankMap() {
	var latLng = new google.maps.LatLng( 55.861176, -4.250271 );
	var mapOptions = { zoom: 12 , center: latLng , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map = new google.maps.Map( document.getElementById( "map_search_content") , mapOptions );
}


function loadStreetView() {
	var latLng = new google.maps.LatLng( $('#view_property').attr( 'data-latitude' ) , $('#view_property').attr( 'data-longitude' ) );
	var panoramaOptions = { position:latLng, pov: { heading: 0, pitch:0, zoom:1 } };
	var myPano = new google.maps.StreetViewPanorama(document.getElementById("map_content"), panoramaOptions);
	myPano.setVisible(true);
}


function loadOfficeMap(  ) {
	var latLng = new google.maps.LatLng( $('#office_map').attr( 'data-latitude' ) , $('#office_map').attr( 'data-longitude' ) );
	var mapOptions = { zoom: 13 , center: latLng , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map = new google.maps.Map( document.getElementById( "office_map") , mapOptions );
	var marker = new google.maps.Marker({ position: latLng, map: map, icon: officeIcon });  
}


function loadDevelopmentMap() {
	var latLng = new google.maps.LatLng( $('#development_map').attr( 'data-latitude' ) , $('#development_map').attr( 'data-longitude' ) );
	var mapOptions = { zoom: 13 , center: latLng , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map = new google.maps.Map( document.getElementById( "development_map") , mapOptions );
	var marker = new google.maps.Marker({ position: latLng, map: map, icon: devMarkerIcon });  
}


function loadAllOfficesMap() {

	var mapOptions = { scrollwheel: false, zoom: 10 , center: new google.maps.LatLng(55.9054,-4.22445) , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map_locations = new Array();
	var markers = new Array();
	var counter = 0;
	var map = new google.maps.Map( document.getElementById( "contact_office_map") , mapOptions );
	
	
	$('ul#office_list_main').find('li').each( function() {
		var location = new google.maps.LatLng( $(this).attr( 'data-latitude' ) , $(this).attr( 'data-longitude' ) );
		map_locations[counter] = $(this).attr('class');
		markers[counter] = new google.maps.Marker( { position:location, map: map , title: $(this).attr( 'data-title' ), icon: officeIcon } );
        google.maps.event.addListener(markers[counter], 'click', function() { 
        	map.setCenter(location); 
        	map.setZoom(16);
        });
        counter++;
	});
	
}

function loadPropertySearchMap() {
	var mapOptions = { scrollwheel: false, zoom: 10 , center: new google.maps.LatLng(55.9054,-4.22445) , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map_locations = new Array();
	var markers = new Array();
	var counter = 0;
	var map = new google.maps.Map( document.getElementById( "search_results_map") , mapOptions );
	var bounds = new google.maps.LatLngBounds();
	
	// Get Property Data...
	var data = jQuery.parseJSON( $('#search_results_map').attr( 'data-property' ) );

	if ( data != false ) {
		$.each(data, function( i , property ) {
			var location = new google.maps.LatLng( property.latitude , property.longitude );
			bounds.extend(location);
			markers[counter] = new google.maps.Marker({ position: location, map: map , icon: thisProperty , title: property.street , url: property.link });
			google.maps.event.addListener(markers[counter], 'click', function() { window.location.href = this.url; });
			counter++;
		});
		map.fitBounds(bounds);
	}
}


// ------------------------------------------------------------------------------------------
// AJAX POST functions
// ------------------------------------------------------------------------------------------

// Homes By Email
// Retrieve the town list for the selected county
// -----------------------------------
function updateTownsList( county ) {
	var urlString = "/includes/ajax/update_hbe_locations.php?county="+escape(county);	
	$.post( urlString , {} , function(data) { $("#townsList").html( data ); }, "text" );
}

function updateSchoolSearchMap( ) {
	
	var myPopupPropertyBoxOptions = { content: '', disableAutoPan: false, maxWidth: 0, pixelOffset: new google.maps.Size( 0 , 0 ),
		zindex: null, boxStyle: { background: "#ffffff", opacity: 1, width: '250px', height: '140px' },
		infoBoxClearance: new google.maps.Size( 1, 1 ), isHidden: false, pane: 'floatPane', enableEventPropagation: false
	};
	var propertyPopupInfoWindow = new InfoBox( myPopupPropertyBoxOptions );
	
	$('form#search_criteria #loading').show();
	
	var markers = new Array();
	var counter = 0;
	
	var schoolLocation = $('select#school').val();
	var schoolRadius = $('select#within').val()
 	var latlng = schoolLocation.split(',');
	
	// Draw School location and center map...
	var latLng = new google.maps.LatLng( latlng[0] , latlng[1] );
	var mapOptions = { zoom: 12 , center: latLng , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map = new google.maps.Map( document.getElementById( "map_search_content") , mapOptions );
	var marker = new google.maps.Marker({ position: latLng, map: map , icon: largeSchoolIcon , url: latlng[2] });
	if ( latlng[2] != '' ) { google.maps.event.addListener( marker , 'click' , function() { window.open( 'http://'+this.url , '_blank' ); }); }
	var bounds = new google.maps.LatLngBounds();
	
	$.post( 
		base_folder + 'includes/ajax/map-search.php' , 
		{ location: schoolLocation , radius: schoolRadius },
		function( data ) {
			
			if ( data != false ) {
				$.each(data, function( i , property ) {
					var location = new google.maps.LatLng( property.latitude , property.longitude );
					bounds.extend(location);
					markers[counter] = new google.maps.Marker({ position: location, map: map , icon: thisProperty , title: property.street , url: property.link, content: property.html  });
					google.maps.event.addListener( markers[counter] , 'click' , function() {
						propertyPopupInfoWindow.open( map , this );
						propertyPopupInfoWindow.setContent(this.content);
						propertyPopupInfoWindow.open( map , this );
					}); 
					counter++;
				});
				
				map.fitBounds(bounds);
			}
			
			$('form#search_criteria #loading').hide();
			
		},
		'json'
	);
	
}

function updateRailwaySearchMap( ) {
	
	var myPopupPropertyBoxOptions = { content: '', disableAutoPan: false, maxWidth: 0, pixelOffset: new google.maps.Size( 0 , 0 ),
		zindex: null, boxStyle: { background: "#ffffff", opacity: 1, width: '250px', height: '140px' },
		infoBoxClearance: new google.maps.Size( 1, 1 ), isHidden: false, pane: 'floatPane', enableEventPropagation: false
	};
	var propertyPopupInfoWindow = new InfoBox( myPopupPropertyBoxOptions );
	
	$('form#search_criteria #loading').show();
	
	var markers = new Array();
	var counter = 0;
	
	var railwayLocation = $('select#railway').val();
	var railwayRadius = $('select#within').val()
 	var latlng = railwayLocation.split(',');
	
	// Draw School location and center map...
	var latLng = new google.maps.LatLng( latlng[0] , latlng[1] );
	var mapOptions = { zoom: 12 , center: latLng , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map = new google.maps.Map( document.getElementById( "map_search_content") , mapOptions );
	var marker = new google.maps.Marker({ position: latLng, map: map , icon: largeTrainIcon });
	var bounds = new google.maps.LatLngBounds();
	
	$.post( 
		base_folder + 'includes/ajax/map-search.php' , 
		{ location: railwayLocation , radius: railwayRadius },
		function( data ) {
			
			if ( data != false ) {
				$.each(data, function( i , property ) {
					var location = new google.maps.LatLng( property.latitude , property.longitude );
					bounds.extend(location);
					markers[counter] = new google.maps.Marker({ position: location, map: map , icon: thisProperty , title: property.street , url: property.link, content: property.html });
					google.maps.event.addListener( markers[counter] , 'click' , function() {
						propertyPopupInfoWindow.open( map , this );
						propertyPopupInfoWindow.setContent(this.content);
						propertyPopupInfoWindow.open( map , this );
					}); 
					counter++;
				});
				
				map.fitBounds(bounds);
			}
			
			$('form#search_criteria #loading').hide();
			
		},
		'json'
	);
	
}


// ------------------------------------------------------------------------------------------
// General Functions
// ------------------------------------------------------------------------------------------
function isIDevice() {
	if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) { return true; } 
	else { return false; }
}


function scrollAreaMap( point ) {
	var points = point.split(',');
	$("#area_map").css({ top: points[0] + "px" , left: points[1] + "px" });
}
