var billboardPlay=true;
$(document).ready(function() {
	if ($('#billboard').length > 0 && $('#billboard .img-holder a').length > 1) {
		$(function() {
			setInterval("billboardSwitch()",6500);
		});
	}
	$('#bbnav a').click(function() {
		billboardPressed($(this),true);
	});
	$('.metodologies .box').not('.opened').mouseover(function() {
		var hovered=$(this);
		$('.metodologies .active').not('.opened').removeClass('active');
		hovered.addClass('active');
		if (($('.metodologies .opened').length > 0) && (!hovered.hasClass('opened'))) {
			hovered.css('opacity','0.5');
		}
	});
	$('.metodologies .box').click(function() {
		var clicked=$(this);
		$('.metodologies .box').removeClass('opened active').css('opacity','1.0');
		clicked.addClass('active');
		
		if (!clicked.hasClass('opened')) {
			clicked.addClass('opened').css('opacity','1.0');
			$('.open-metodology:visible').slideUp(300);
			$('#metodology-'+clicked.attr('id').split('-')[1]+'-opened').slideDown(300);
		}
		
	});
	$('.metodologies .box').mouseout(function() {
		$(this).css('opacity','1.0');
		if (!$(this).hasClass('opened')) {
			$(this).removeClass('active');
		}
	});
	$('.open-metodology a.close').click(function() {
		$(this).parent().slideUp(300);
		$('.metodologies .box').removeClass('active opened');
	});
	if ($('#map').length > 0) {
		var stdVal=$('#start-from').val();
		$('#start-from').focus(function() {
			if ($(this).val() == stdVal) { $(this).val(''); }
		}).blur(function() {
			if ($(this).val() == '') { $(this).val(stdVal); }
		});
	}
	if ($("#start-from").length > 0) {
		$("#start-from").autocomplete({
	      source: function(request, response) {
	        geocoder.geocode( {'address': request.term }, function(results, status) {
	          response($.map(results, function(item) {
	            return {
	              label:  item.formatted_address,
	              value: item.formatted_address,
	              latitude: item.geometry.location.lat(),
	              longitude: item.geometry.location.lng()
	            }
	          }));
	        })
	      },
	      select: function(event, ui) {
			calcRoute($('#start-from').val());
	      }
	    });	
	}

	$('.arrow-up, .arrow-down').click(function() {
		$.scrollTo($(this).attr('rel'),800);
	});
	
	$('.project-arrow').hover(function() {
		$(this).next('.project-nav:eq(0)').show().nextAll('.project-nav').hide();
	},function() {
		$(this).next('.project-nav:eq(0)').hide().nextAll('.project-nav').hide();
	});
	
	$('#img-holder').mousemove(function(e) {
		if (!$('.show-me').is(':visible')) {
			var thisStage=$(this);
			var offset=thisStage.offset();
			var y=parseInt(e.pageY-offset.top);
			var x=parseInt(e.pageX-offset.left);
			var arrowHeight=parseInt($('.onstage-arrow').height());
			if (y < parseInt(arrowHeight/2)) {
				newY=0;
			} else {
				if (y < ($('#project-top').height()-parseInt(arrowHeight/2))) {
					newY=(y-parseInt(arrowHeight/2));
				} else {
					newY=($('#project-top').height()-arrowHeight);
				}
			}
			$('.onstage-arrow').css('margin-top', newY+'px');
			if ((x > 0) && (x < thisStage.width())) {
				var hasPrevImg=prevImageExists();
				if (x < (thisStage.width()/2)) {
					if (hasPrevImg) { $('#stage-left').show(); }
					$('#stage-right').hide();
				} else {
					if (hasPrevImg) { $('#stage-left').hide(); }
					$('#stage-right').show();
				}
			}
		}
	});
	$('.onstage-arrow').mouseout(function() {
		$(this).hide();
	}).click(function() {
		slideImage($(this).attr('id').split('-')[1]);
	});
	$('.show-me').click(function() {
		openGallery(0);
		showImg(0,0);
	}).mouseover(function() {
		$(this).css('background-position','170px');
	}).mouseout(function() {
			$(this).css('background-position','160px');
		});
	$('.mininav-images a').click(function() {
		showImg(actualGallery,$(this).attr('rel'));
	});
	$('.single-project').hover(function() {
		$(this).children('.overlay').animate({opacity:'1'});
	},function() {
		$(this).children('.overlay').animate({opacity:'0'});
	});
});
function nextImageExists() {
	return ($('#slide-'+actualGallery+'-'+actualImage).nextAll('img.slide').length > 0);
}
function prevImageExists() {
	return ($('#slide-'+actualGallery+'-'+actualImage).prevAll('img.slide').length > 0);
}

function openGallery(id) {
	$('.single-gallery').not('.opened').show();
	$('#galleries .opened').hide().children('div.mininav-images a.active').removeClass('active');
	$('#gallery-'+id).hide().next('.opened').fadeIn(300);
	$('.show-me:visible').hide().next('img').fadeOut();
}

function slideImage(to) {
	var actualImageElement=$('#slide-'+actualGallery+'-'+actualImage);
	var canGo=(to == 'left') ? prevImageExists() : true;
	if (canGo) {
		var willShow=(to == 'left') ? actualImageElement.prev() : actualImageElement.next();
		if (willShow.attr('id')) {
			var nextValues=willShow.attr('id').split('-');
			if (nextValues[1] != actualGallery) {
				openGallery(nextValues[1]);
			} 
			showImg(nextValues[1],nextValues[2]);
		} else {
			$('.show-me').click();
		}
	}
}

function showImg(gallery,image) {
	$('#img-holder img:visible').fadeOut(300, function() {
		toShow=$('#slide-'+gallery+'-'+image);
		toShow.fadeIn(300);
		$('#project-top').animate({height:toShow.outerHeight()}, 200);
		miniNavholder=$('#galleries .opened div.mininav-images');
		miniNavholder.children('a.active').removeClass('active');
		miniNavholder.children('a[rel='+image+']').addClass('active');
		actualGallery=gallery;
		actualImage=image;
	});	
}

function billboardSwitch() {
	if (billboardPlay) {
		var active =$('#bbnav a.active');
		var next=active.nextAll('#bbnav a');
		if (next.length == 0) {
			next=$('#bbnav a:first');
		} else {
			next=active.next();
		}
		billboardPressed(next,false);
	}
}

function billboardPressed(obj,stopMe) {
	var thisEQ=parseInt(obj.attr('id').split('-')[1]);
	var newMargin=-980*thisEQ;
	var infos=obj.attr('rel').split('*');
	$('#billboard .infos div span').fadeOut(600,function() {
		$('#billboard .infos a').html(infos[1]).attr('href',infos[2]);
		$(this).html(infos[0]).fadeIn(600);
	});
	$('#billboard .img-holder').animate({
	 	marginLeft: newMargin+"px"
	},900, function() {
		$('#bbnav a').removeClass('active').eq(thisEQ).addClass('active');
	});
	billboardPlay=(!stopMe);
}


function calcRoute(start) {
  var end = "Via XX Settembre, 14 - 84128 Salerno (SA) - Italy";
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    } else {
		alert("Impossibile trovare località.");
	}
  });
	
}
function createMap() {
	directionsDisplay = new google.maps.DirectionsRenderer();
	var latlng = new google.maps.LatLng(40.66947,14.786954);
	var myOptions = {
		zoom: 13,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map"),myOptions);
	geocoder = new google.maps.Geocoder();
	marker = new google.maps.Marker({
		position: latlng, 
		map: map, 
		title:"Insight Studio"
	});
	directionsDisplay.setMap(map);
}


