if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
var viewportmeta = document.querySelectorAll('meta[name="viewport"]')[0];
if (viewportmeta) {
viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0';
document.body.addEventListener('gesturestart', function() {
viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
}, false);
}
}


var thisProperty = '/img/icons/this-property.png';
var officeIcon = '/img/icons/pj-map-icon.png';

$(document).ready( function() {

	$('input[name="search_all"]').click( function() {
		window.location.href = "/property-for-sale/property-for-sale.html";
	});

	$('input, textarea').placeholder(); // Setup Placeholders for older browsers
	
	// Home Page
	if ( $('#property_list_container').length ) { loadFeaturedProperties(); }
	
	$('#featured_left').click( function() {
		if ( $('#featured_property_nav #featured_left img').attr('src') != "/img/nav/left-arrow-off.png" ) {
			var newPos = parseInt($('ul#property_list').css('left')) + $('#property_list_container').width() + 15;
			$('ul#property_list').animate( { left : newPos } , 1000 );
			$('#featured_property_nav #featured_right img').attr( 'src' , '/img/nav/right-arrow.png' );
			$('#featured_property_nav #featured_left img').attr( 'src' , '/img/nav/left-arrow-off.png' );
		}
		return false;
	});
	
	$('#featured_right').click( function() {
		if ( $('#featured_property_nav #featured_right img').attr('src') != "/img/nav/right-arrow-off.png" ) {
			var newPos = parseInt($('ul#property_list').css('left')) - $('#property_list_container').width() - 15;
			$('ul#property_list').animate( { left : newPos } , 1000 );
			$('#featured_property_nav #featured_right img').attr( 'src' , '/img/nav/right-arrow-off.png' );
			$('#featured_property_nav #featured_left img').attr( 'src' , '/img/nav/left-arrow.png' );
		}
		return false;
	});
	
	//Set custom configurations
	var config = { sensitivity: 2, interval: 100, over: megaHoverOver, timeout: 500, out: megaHoverOut };
	$("ul#main_menu li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
	$("ul#main_menu li").hoverIntent(config); //Trigger Hover intent with custom configurations	
	
	if((navigator.userAgent.match(/iPad/i))) {
    	$("ul#main_menu li").bind('touchstart', function(){
   	     	$("ul#main_menu li:has(.sub) > a").click(function(){
        		$(this).find(".sub").stop().fadeTo('fast', 1).show();
        		return false;
   			 });
   	     });
   	}

	// Office Home Page
	if ( $('#office_map').length ) { loadOfficeMap( office_latitude , office_longitude , 14 ); }
	
	// Activate map on property view page
	// -----------------------------------
	if ( $('#property_map').length ) { loadNormalMap( 12 ); }
	
	$('#property_map ul li a').click( function() { 
		var mapType = $(this).attr('rel');
		
		$('#property_map ul li').removeClass( 'active' );
		$(this).parent().addClass( 'active' );
		
		if ( mapType == "extended" ) { loadNormalMap( 12 ); }
		else if ( mapType == "street" ) { loadNormalMap( 16 ); }
		else if ( mapType == "streetview" ) { loadStreetView(); }
		else if ( mapType == "similar" ) { loadSimilarProperties(); }
	});
	
	
	// Property View Page - Photo Gallery
	// -------------------------------------------
	$('#photo_gallery #photo_list_inner a').click( function() { $('#photo_gallery #mainPropertyPhoto').attr( 'src' , $(this).attr('href') ); return false; });
	//$('#photo_gallery a').hover( function() { $('#photo_gallery #mainPropertyPhoto').attr( 'src' , $(this).attr('href') ); } , function() {} );
	
	$('#photo_list #button_left').click( function() {
		
		var currentPos = parseInt($('#photo_list_inner').css('left'));
		//console.log(currentPos);
		if ( currentPos < 0 ) {
			var newPos =  currentPos + 60;
			$('#photo_list_inner').animate( { left : newPos } , 1000 );
			
			if ( newPos > 0 ) { 
				$('#photo_list #button_left img').attr( 'src' , '/img/photo-nav/left-off.png' ); 
			} else {
				$('#photo_list #button_right img').attr( 'src' , '/img/photo-nav/right-on.png' );
			}
		}
		return false;
		
	});
	
	$('#photo_list #button_right').click( function() {
		
		var accum_width = 0;
		var currentPos = parseInt($('#photo_list_inner').css('left'));
		$('#photo_list_inner').find('img').each(function() { accum_width -= $(this).width() + 10; });
		//console.log(currentPos);
		if ( currentPos >= (accum_width+300) ) {
			var newPos = currentPos - 60;
			$('#photo_list_inner').animate( { left : newPos } , 1000 );
				$('#photo_list #button_left img').attr( 'src' , '/img/photo-nav/left-on.png' ); 
			if ( newPos <= (accum_width+300) ) { $('#photo_list #button_right img').attr( 'src' , '/img/photo-nav/right-off.png' ); }
		}
		return false;
		
	});
	
	$("li#mortgagecalc a").fancybox( { 'width' : 500, 'height' : 400, 'autoScale': false, 'type': 'iframe'} );
	
	if ( $('#contact_office_map').length ) { loadAllOfficesMap(); }
	
	if ( $('#slider').length ) { 
		var height = $('#slider').height() + 'px';
		$('#slider').innerfade({ animationtype: 'fade', speed: 1500, timeout: 5000, type: 'sequence', containerheight: height });
	}
	
	if ( $('#slider_home').length ) { 
		var height = $('#slider_home').height() + 'px';
		$('#slider_home').innerfade({ animationtype: 'fade', speed: 1500, timeout: 7000, type: 'sequence', containerheight: height });
	}
	
	if ( $('#client_quotes').length ) { 
		var height = $('#client_quotes').height() + 'px';
		$('#client_quotes').innerfade({ animationtype: 'fade', speed: 1500, timeout: 5000, type: 'sequence', containerheight: height });
	}
	
	if ( $('#property_location_map').length ) { loadSearchPropertiesMap(); }
	
	
});


// ------------------------------------------------------------------------------------------
// Map Functions
// ------------------------------------------------------------------------------------------
function loadNormalMap( zoomLevel ) {
	var latLng = new google.maps.LatLng( latitude , longitude );
	var mapOptions = { zoom: zoomLevel , center: latLng , mapTypeId: google.maps.MapTypeId.ROADMAP }
	var map = new google.maps.Map( document.getElementById( "map_content") , mapOptions );
	var marker = new google.maps.Marker({ position: latLng, map: map , icon: thisProperty });  
}


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


function loadOfficeMap( latitude , longitude , zoomLevel ) {
	var latLng = new google.maps.LatLng( latitude , longitude );
	var mapOptions = { zoom: zoomLevel , 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 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 loadSearchPropertiesMap() {
	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( "property_location_map") , mapOptions );
	 var bounds = new google.maps.LatLngBounds();
	
	$('ul#property_list').find('li').each( function() {
		var location = new google.maps.LatLng( $(this).attr( 'data-latitude' ) , $(this).attr( 'data-longitude' ) );
		map_locations[counter] = $(this).attr('class');
		bounds.extend(location);
		markers[counter] = new google.maps.Marker( { position:location, map: map , title: $(this).attr( 'data-title' ), icon: thisProperty, url: $(this).attr( 'data-link' ) } );
        google.maps.event.addListener(markers[counter], 'click', function() { window.location.href = this.url; });
        map.fitBounds(bounds);
        counter++;
	});
}


function loadFeaturedProperties() {
	
	var toLoad = 0;
	if ( $(document).width() <= 480 ) { toLoad = 2; }
	else if ( $(document).width() <= 996 ) { toLoad = 8; }
	else if ( $(document).width() <= 1382 ) { toLoad = 12; }
	else { toLoad = 16; }

	$.post( '/includes/ajax.featured_properties.php' , { load: toLoad } , function(data) { if ( data != '' ) { $('#property_list').html(data); }});

}

function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    $(this).find(".sub").addClass('is_visible');
    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 

    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;	

        $(this).find(".row").each(function() {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rowWidth}); //Set Width

    }
}
//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $(this).hide();  //after fading, hide it
    	$(this).removeClass('is_visible');
  });
}



function updateConveyancingFields( value ) {
	
	$('input[name="val_property"]').removeClass('highlight');
	$('input[name="val_sale"]').removeClass('highlight');
	$('input[name="val_purchase"]').removeClass('highlight');
	
	if ( value == "Purchase" ) {
		$('input[name="val_purchase"]').addClass('highlight');
		$('input[name="val_sale"]').val('N/A');
		$('input[name="val_property"]').val('N/A');
		$('input[name="val_purchase"]').val('');
	}
	else if ( value == "Sale" ) {
		$('input[name="val_sale"]').addClass('highlight');
		$('input[name="val_purchase"]').val('N/A');
		$('input[name="val_property"]').val('N/A');
		$('input[name="val_sale"]').val('');
	}
	else if ( value == "Purchase and Sale" ) {
		$('input[name="val_sale"]').addClass('highlight');
		$('input[name="val_purchase"]').addClass('highlight');
		$('input[name="val_sale"]').val('');
		$('input[name="val_purchase"]').val('');
		$('input[name="val_property"]').val('N/A');
	}
	else if ( value == "Remortgage" ) {
		$('input[name="val_property"]').addClass('highlight');
		$('input[name="val_sale"]').val('N/A');
		$('input[name="val_purchase"]').val('N/A');
		$('input[name="val_property"]').val('');
	}
	
}

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

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


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