/* Author: 

*/

//var geocoder;
//var map;
var address;

function showMap(){
	$.fancybox(
		'<div id="propertyMap" style="width:600px; height:400px;">&nbsp;</div>',
		{
        		'autoDimensions'	: false,
			'width'         		: 600,
			'height'        		: 'auto',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none'
		}
	);

	var geocoder = new google.maps.Geocoder();
    var myOptions = {
		zoom: 14,
		//center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("propertyMap"), myOptions);
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			var marker = new google.maps.Marker({
				map: map,
				position: results[0].geometry.location
			});
		} else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
}



/* ie fix for jqueryui bug */
$.cssHooks.letterSpacing = {
	get: function ( elem, computed ) {
		var ret = parseFloat( elem.style.letterSpacing ) || 0;
		return ret;
	}
};


/* property search js */
function displayProperty(propertyID){
	// find the property from id
	for(var i=0; i < props.length; i++){
		if(props[i].propertyID == propertyID){
			var prop = props[i];
			break;
		}
	}
	
	// set the property details
	$('#propertyID').text(prop.propertyID);
	$('#referenceNumber').val(prop.propertyName);
	$('#propertyName').text(prop.propertyName);
	$('#type').text(prop.type);
	$('#buildingStyle').text(prop.buildingStyle);
	$('#situated').text(prop.situated);
	$('#heating').text(prop.heating);
	$('#parking').text(prop.parking);
	$('#garden').text(prop.garden);
	$('#councilTax').text(prop.councilTax);
	$('#shortDescription').text(prop.shortDescription);
	$('#availDate').html(prop.availDate);
	$('#price').html(prop.price + " PCM");
	if(prop.bedrooms == 1){
		$('#bedrooms').text(prop.bedrooms + " bedroom");
	} else{
		$('#bedrooms').text(prop.bedrooms + " bedrooms");
	}
	if(prop.furnished){
		$('#furnished').text("Furnished");
	} else {
		$('#furnished').text("Not Furnished");
	}
	
	// set up the gallery
	var data = prop.imageData;
	
	$('#gallery').galleria({
		transition: "fade",
		thumbCrop: true,
		imageCrop: true,
		carousel: false,
		imagePan: false,
		transitionSpeed: 2000,	
		clicknext: true,
		autoplay: 3000,
		data_source: data,
		thumbnails: "numbers"
	});
	
	
	// set up the map
	address = prop.postcode;
	
	// set the id attribute, so that the screen scrolls to the full details
	//$('.propertyDetails').attr("id",propertyID);
	//$('html,body').animate({scrollTop: $(".propertyDetails").offset().top},'slow');
	$('html,body').animate({scrollTop: 0},'slow');
	
	// show the details if necessary
	if($('.propertyDetails').is(":hidden")){
		$('.propertyDetails').slideDown("slow");//.css("display","block");
		
		// add a class for print stylesheet
		$('#findaproperty').addClass('showPropertyDetails');
	}
}


function updateLocations(region){
	var regionName = 'input.region_'+$(region).val();
	
	$(regionName).unbind('click',updatePropertyGrid);
	$(regionName).click();
	$(regionName).bind('click',updatePropertyGrid);
	/*var checked = $(region).is(':checked');
	if(checked){
		$(regionName).attr('checked','checked');
	} else {
		$(regionName).attr('checked','');
	}*/
	
	// run filter
	updatePropertyGrid();
}

function updatePropertyGrid(){
	//alert('updatePropertyGrid()');
	var propHeight = 400;// Change these values, if css changes!!!
	var propWidth = 210;
	var propSpacing= 30;
	
	$( "#priceRangeDisplay" ).html( '<span class="priceLow">' + $( "#priceRange" ).slider( "values", 0 ) + '</span> <span class="line"></span> <span class="priceHigh">' + $( "#priceRange" ).slider( "values", 1 ) ) + '</span>';
	$( "#bedroomRangeDisplay" ).html( '<span class="priceLow">' + $( "#bedroomRange" ).slider( "values", 0 ) + '</span> <span class="line"></span> <span class="priceHigh">' + $( "#bedroomRange" ).slider( "values", 1 ) ) + '</span>';
	
	var priceRangeMin = $( "#priceRange" ).slider( "values", 0 );
	var priceRangeMax = $( "#priceRange" ).slider( "values", 1 );
	
	var bedroomRangeMin = $( "#bedroomRange" ).slider( "values", 0 );
	var bedroomRangeMax = $( "#bedroomRange" ).slider( "values", 1 );
	
	var furnished = $("input[name='furnished']:checked").val();
	
	var locationArray = $.map($("input[name='location']:checked"), function(e,i) {
	    return e.value;
	});
	//alert(locationArray);
	
	var numPassed = 0;
	
	// loop each prop, to see if it passes filter
	for(var i=0; i<props.length; i++){
		p = props[i];
		var pass = true;
		
		if(p.price < priceRangeMin) pass = false;
		if(p.price > priceRangeMax) pass = false;
		
		if(p.bedrooms < bedroomRangeMin) pass = false;
		if(p.bedrooms > bedroomRangeMax) pass = false;
		
		if(furnished == 'yes' && !p.furnished) pass = false;
		if(furnished == 'no' && p.furnished) pass = false;
		
		var locationFound = false;
		for(var j=0; j < locationArray.length; j++){
			if(locationArray[j] == p.area){
				locationFound = true
				break;
			}
		}
		if(!locationFound) pass = false;
		
		if(pass)numPassed++;
		p.show = (pass && p.hidden);
		p.hide = (!pass && !p.hidden);
	}
	
	// calc grid height
	var currGridHeight = $('#propertyGrid').css('height');
	currGridHeight = currGridHeight.replace(/\D+/gi, "");
	var newGridHeight = Math.ceil(numPassed/4) * propHeight;
	//alert('updatePropertyGrid()'+currGridHeight+':'+newGridHeight);
	
	// if grid needs to grow, do it now
	if(newGridHeight > currGridHeight)$('#propertyGrid').animate({height:newGridHeight+'px'},'fast');
	
	//  hide props that failed
	for(var i=0; i<props.length; i++){
		p = props[i];
		if (p.hide) {
			$('#property_' + p.propertyID).fadeOut();
			p.hidden = true;
		}
	}	
	
	//  move props to new position
	var x = 0;
	var y = 0;
	var xPos = 0;
	var yPos = 0;
	for (var i = 0; i < props.length; i++) {
		p = props[i];
		if(p.show || !p.hidden){
			x = xPos*(propWidth+propSpacing);
			y = yPos*propHeight;
			$('#property_' + p.propertyID).animate({left:x+'px',top:y+'px'},'slow');
			xPos++;
			if(xPos == 4){
				xPos = 0;
				yPos++;
			}
		}
	}
	
	// fade in new props
	for(var i=0; i<props.length; i++){
		p = props[i];
		if (p.show) {
			$('#property_' + p.propertyID).fadeIn();
			p.hidden = false;
		}
	}	
	
	// if grid needs to shrink, do it now
	if(newGridHeight < currGridHeight)$('#propertyGrid').animate({height:newGridHeight+'px'},'fast');
}


$(document).ready(function(){
	
	// hack to look for enquiry formn submitted, and pop-up message
	//alert($('p.success').length);
	if($('p.success').length){
		var msg = $('p.success').text();
		alert(msg);
	}
	
	// set up topnav, so full li tag can be clicked
	$('#navPrimary li').click(function(){
		var href = $('a',this).attr('href');
		window.location = href;
	});
	
	// set up properties to show full details on click
	$('a.propertyLink').click(function(){
		var href = $(this).attr('href');
		var propertyID = href.replace(/\/find-a-property\/#/gi, "");
		displayProperty(propertyID);
	});
	$('div.view-more-details').click(function(){
		var href = $("a.propertyLink",this).attr('href');
		var propertyID = href.replace(/\/find-a-property\/#/gi, "");
		displayProperty(propertyID);
	});
	$('.property').click(function(){
		var id = $(this).attr('id');
		var propertyID = id.replace(/property_/gi, "");
		window.location = "/find-a-property/#" + propertyID;
	});
	$('#findaproperty div.property').click(function(){
		var id = $(this).attr('id');
		var propertyID = id.replace(/property_/gi, "");
		displayProperty(propertyID);
	});
	
	// set up filter form
	
	// price range
	$( "#priceRange" ).slider({
		range: true,
		//min: 0,
		//max: Math.max(maxPrice,1000),
		min: minPrice,
		max: maxPrice,
		values: [ minPrice, maxPrice ],
		slide: function( event, ui ) {
			$( "#priceRangeDisplay" ).html( '<span class="currencySymbolLeft">£</span><span class="priceLow">' + $( "#priceRange" ).slider( "values", 0 ) + '</span> <span class="line"></span> <span class="currencySymbolRight">£</span><span class="priceHigh">' + $( "#priceRange" ).slider( "values", 1 ) ) + '</span>';
		},
		change: function( event, ui ) {
			updatePropertyGrid();
		}
	});
	
	// bedroom range
	$( "#bedroomRange" ).slider({
		range: true,
		//min: 0,
		//max: maxBedrooms+1,
		min: minBedrooms,
		max: maxBedrooms,
		step:1,
		values: [ 1, maxBedrooms ],
		slide: function( event, ui ) {
			//$( "#bedroomRangeDisplay" ).text($( "#bedroomRange" ).slider( "values", 0 ) + " - " + $( "#bedroomRange" ).slider( "values", 1 ) );
		},
		change: function( event, ui ) {
			updatePropertyGrid();
		}
	});
	
	// furnished
	$("input[name='furnished']").change(function(){
		updatePropertyGrid();
	});
	
	// regions
	$("input[name='region']").change(function(){
		updateLocations(this);
	});
	
	// locations
	$("input[name='location']").bind('click',updatePropertyGrid);
	
	

	/* set up fancy box links */	
	//$("a.fancybox").fancybox();
	$("a.fancybox").click(function(){
		showMap();
		return false;
	});
	
	// set map options
    /*
geocoder = new google.maps.Geocoder();
    //var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
		zoom: 14,
		//center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("propertyMap"), myOptions);
*/
	
	
	// display grid at start
	updatePropertyGrid();
	
	// if a property id was passed in the url hash, show that property
	var hash = window.location.hash;
	if(hash.length) {
		hash = hash.replace(/#/gi, "");// remove the #
		displayProperty(hash);
	}	
	
});















