$(function(){
	//Menu Code
	$("#sideMenu").each(function(){
		$("li",this).hover(function(){ 
			$(">ul", this).fadeIn("fast"); 
		}, function(){
			$(">ul", this).fadeOut("fast"); 
		});
	});
	
	$("#property .photos").unbind().each(function(){
		$("a",this).lightBox();
	});
	
	$(".propType").change(function(e){
		if($(this).val()!=""){
			window.location = $(this).val();
		}
	});
	
	$("#search select.auto").change(function(e){
			$("#search form").submit();
	});
	
	
	//Map Code!
	var map = ".map";
	var address = $('.address').html() + " " + $('.address').attr("postcode");
	$(map).each(function(){
		if(point = $(map).attr("point")){
			point = point.split(",");
	   		placeMarkMap(map,address,[point[0],point[1]]);
		}
		else{
			//Get the address
			$("<div></div>").jmap('init', {
				'mapType':'map',
				"mapZoom":16,
				'mapShowjMapsIcon': false,
				'mapEnableType': true
			}).jmap('SearchAddress', {
		        'query': address,
		        'returnType': 'getLocations'
		    }, function(result, options){
		        var valid = Mapifies.SearchCode(result.Status.code);
		        if (valid.success) {
		       		$.each(result.Placemark, function(i, point){
		           		placeMarkMap(map,address,[point.Point.coordinates[1], point.Point.coordinates[0]]);
		                return false;
		            });
		        }
		    });
		}
	});
	runLoop();
});

function runLoop() {
	$(".photoarea").each(function(){
		
		//don't run if not enough photos
		if($(this).children().length < 3)
			return;
		
		var size = $('.photoarea *:first').outerHeight();
		var t = $(this).css('top');
		if(t){
			if(t == 'auto'){
				t = 0;
			}
			else {
				t = t.substring(0,t.length-2);
			}
			var pcThrough = Math.abs(t) / size * 100;
			var speed = 37 * (100-pcThrough) / 100 * size;	
			$('.photoarea:not(:animated)').animate({'top':'-'+ size +'px'}, speed, "linear", function(){
				$('*:first',this).appendTo(this);
				$(this).css({'top':'0px'});
				setTimeout(function(){ runLoop() }, 10);
			}).hover(function(e){
				$(this).stop();
			},function(e){
				setTimeout(function(){ runLoop() }, 10);
			});
			
			return false;
		}
	});
}

function placeMarkMap(map,address,p){
	$(map).jmap('init', {
		'mapType':'map',
		"mapZoom":16,
		'mapShowjMapsIcon': false,
		'mapEnableType': true,
		'mapCenter':p
	}).jmap('AddMarker',{
        'pointLatLng':p,
        'pointHTML':address,
		'centerMap': true
    });
}


