var dragTop;
var draggable;
var gridview = false;
var zinnebeeldsite = true;
var portfolioEnabled = true;
var gridEnabled = true;

// added jquery functions
$.fn.position = function (perc, animate, boxHeight) {
	if(!boxHeight){
		boxHeight = this.height();
	}
	if (perc && animate == 'slide'){
		this.animate({ top : ($(window).height() * (perc/100)) - (boxHeight*  (perc/100))}, 400)
	} else if (perc){
	    this.css("top", ($(window).height() * (perc/100)) - (boxHeight*  (perc/100)) + "px");			
	} else {
	    this.css("top", ( $(window).height() - boxHeight ) / 2+$(window).scrollTop() + "px");		
	}
    return this;
}

$.fn.toggleSlide = function(elNew, speed)
{
  return this.each(function()
  {
     var el = $(this);
     var cur = {height: el.height()+'px'};
     el.hide();
	 elNew.show()
     var next = {height: elNew.height()+'px'};
     elNew.css(cur) // restore initial dimensions
     	.animate(next, speed, function(){
			el.removeAttr('style')
			elNew.removeAttr('style')
		})
     	.addClass('visible');
  });
};
$.fn.tooltip = function(content){
	$(this).bind('mouseover', {element:content}, function(event){
		content = event.data.element;
		el = $(this);
		tooltip = $('.' + el.attr('id'));
		if(tooltip.length){
			tooltip.fadeIn(100);
		} else if ($(this).attr('title')){
			if (!content){
				var content = $(this).attr('title')
			}
			var html = '<div style="left:-11000px;" class="tooltip '+ $(this).attr('id') +'"><div class="tooltip_wrap"><div class="tooltip_content">' + content + '<div class="tooltip_bottom"></div></div></div></div>';
			$('body').append(html);
			tooltip = $('.' + el.attr('id'));

			var totalHeight = el.height();
			totalHeight += parseInt(el.css("padding-top"), 10) + parseInt(el.css("padding-bottom"), 10); //Total Padding Width

			tooltipHeight = tooltip.height() + parseInt(tooltip.css("padding-top"), 10) + parseInt(tooltip.css("padding-bottom"), 10) + 10; //Total Padding Width
			
			var Ttop = el.offset().top - tooltipHeight + 3;
			var Tleft = el.offset().left + ((el.width() - tooltip.width())/2);
			tooltip.hide().css({top: Ttop, left: Tleft, 'z-index' : 10}).find('.tooltip_bottom').css({'width': el.width(), 'bottom' :  -(totalHeight + 10), 'padding-bottom': (totalHeight + 10)}).end().fadeIn(100);		
			var hover = false;
			$('.tooltip').live('mouseenter', function(){
				hover = true;
			})
			$('.tooltip').live('mouseleave', function(){
				hover = false;
				el.trigger('mouseleave');
			})
			$(this).bind('mouseleave', function(){
				$(this).animate({'opacity' : 1}, 300, function(){
					if(!hover){
						$('.tooltip').fadeOut(100);					
					}					
				})
			})
		}
	})
}
// document ready functions

$(document).ready(function() {	
	// browser back button change and bookmarking
	
    $.address.externalChange(function(event) {
    	if($('#background img:animated').length){
    		return true;
    	}
		var hash = event.value.split('/')
		hash = hash[1] + '_id';
		var indexMax = $('#projecten article:last').index() + $('#over_zinnebeeld_wrap article:last').index();
		if(hash != '_id'){
			$('#projecten article, #over_zinnebeeld_wrap article').each(function(index){
				var id = $(this).attr('id');
				if(id==hash){
					id = '#'+id;
					if($(id).parent().attr('id') == 'projecten'){
						if($('#over_zinnebeeld_wrap:visible').length){
							closeAbout();
						} else if($('#popup:visible').length){
							togglePopup('up');
						} else if ($('#map:visible').length){
							closeMap(dragTop);				
						}
						gotoProject($(id));
						return false;
					} else if($(id).parent().attr('id') == 'over_zinnebeeld_wrap'){
						if($('#popup:visible').length){
							togglePopup('up');
						} else if ($('#map:visible').length){
							closeMap(dragTop);				
						}
						gotoProject($('#projecten article:first'));
						gotoAbout($(id));
						return false;
					}
				} else if(indexMax == index){
					gotoProject($('#projecten article:first'));
				}									
			});		
		} else {
			gotoProject($('#projecten article:first'));
			gotoAbout($('#over_zinnebeeld_wrap article:first'));
		}
    }).internalChange(function(event){

    })
	
	if($(window).width() <= 1024){
		$('#draggable').width(1024)
	}

	
	$('a[href*="..m.."]').each(function()
	{
		var str = $(this).html();
		$(this).text(str.replace('..m..', "@"));
		
		if($(this).attr('href'))
		{
			var str = $(this).attr('href');
			$(this).attr('href',str.replace('..m..', "@"));
		}
	});
		
	
	resizeBackgroundImage($('img.visible'));
	resizeWrapper();
	draggable = $('#draggable');
	
	// slideshow buttons
	$('.next').click(function(){
		slidePortfolio('next');
		return false;
	});
	$('.prev').click(function(){
		slidePortfolio('prev');
		return false;
	});
	
	// open project popup
	$('.open_popup').click(function(){
		togglePopup('down');
		return false;
	})
	// Over zinnebeeld functies
	$('#logo_cont .over_zinnebeeld').click(function(){
		gotoAbout($('#over_zinnebeeld_wrap article:first'));
		var hash = $(this).attr('href').split('#');
		$.address.value(hash[1]);			
 		pageTracker._trackPageview('/over_zinnebeeld/'+ hash[1]);
 		return false
	})
	
	$('#logo_cont .ons_werk, #over_zinnebeeld_id a:last').click(function(){
		closeAbout();
		var hash = $('#projecten .visible').attr('id').replace('_id', '');
		$.address.value(hash);
		return false;
	})
	$('#draggable .close').click(function(){
		closeMap(dragTop);
		return false;
	})
	$('#menu a').click(function(){
		var href = $(this).attr('href') + '_id';
		if ($(href + ':hidden').length){
			$('#over_zinnebeeld_wrap article:visible').removeClass('visible').toggleSlide($(href), 200);
			$(this).parent().siblings().removeClass('active');
  			$(this).parent().addClass('active');	
		}
		var hash = $(this).attr('href').split('#');
		$.address.value(hash[1]);			
 		pageTracker._trackPageview('/over_zinnebeeld/'+ hash[1]);
 		return false;
	})
	
	//popup functies
	$('#popup .close').click(function(){
		togglePopup('up');
		return false;
	})

	$('#image_dots a:not(.active)').live('click', function(){
		toggleImage($(this));
	})
	
	$('.route_info').live('click', function(){
		gotoAbout($('#contact_id'));
		$.address.value('contact');			
		return false;	
	})
	// make horizontal banner draggable
	if($(window).height() <= 600){
		draggable.position('50');
	} else {
		draggable.position('65');
	}
	var count;
	draggable.draggable({ 
		axis : 'y', 
		scroll: false, 
		containment: 'parent', 
		handle: '.handle',
		snap: '#wrapper',
		snapTolerance: 15,
		stop: function(){
			count = 0;
		}
	});
	$('.handle').hover(function(){
		if($('#popup:hidden').length){
			$('#handle_white').stop().animate({opacity: 0.2},200);
			$('#handle_lines').stop().animate({opacity: 1.0},200);
		}
	}, function(){
		$('#handle_white, #handle_lines').stop().animate({opacity: 0.0}, 200);
	})	
	// make horizontal bar clickable and slide down
	var clickstart;
	var difference;
	$('.handle').mousedown(function(e){
		clickstart = e.pageX + e.pageY;
		draggable.removeClass('down');
		$(this).mouseup(function(e){
			difference = e.pageX + e.pageY - clickstart;
			if(!difference){
				if (!count){
					var height = $(window).height() - 52;
					dragTop = draggable.css('top');
					draggable.animate({'top' : height}, 300, 'easeOutQuart', function(){
						count = 1;						
					});
					draggable.addClass('down');
				} else {
					var dragBottom = $(window).height() - 52;
					draggable.css({'bottom': '', top : dragBottom }).animate({'top' : dragTop}, 300, 'easeOutQuart', function(){
						count = 0;						
					});
				}			
			} 
		})
	})
	
	// load the map
	$('.tooltip a.open_map').live('click', function(){
		if(!$('#map').children().length){
			initializeMap();
		} else {
			$('#map, #map_info').show();
		}
		var height = $(window).height() - 52;
		dragTop = draggable.css('top');
		draggable.animate({'top' : height}, 300, 'easeOutQuart', function(){
			count = 1;						
		});
		$('.tooltip').hide();
		draggable.draggable('disable');
		draggable.addClass('map');
		portfolioEnabled = false;
		return false;
	})	
	// grid functions
	$('#draggable .grid_toggle').click(function(){
		toggleGrid();
		return false;
	})
	$('.grid_close').live('click', function(){
		toggleGrid();
		return false;
	});
	$('.projectwrap .main').live('click', function(){
		gotoProject($('#' + $(this).parent().attr('rel')), 'fade');
		togglePopup('up');
		if($('#draggable.over_zinnebeeld:visible').length){
			closeAbout();
		}
		return false;
	})
	$('.projectwrap .sub').live('click', function(){
		gotoProject($('#' + $(this).parent().attr('rel')), 'fade');
		var image = $(this).attr('href').split('#');
		if(image[1] == 'image_0'){
			image = '';
		}
		if($('#popup:hidden').length){
			togglePopup('down', image[1]);			
		} else {
			getPopup(image[1]);
		}
		if($('#draggable.over_zinnebeeld:visible').length){
			closeAbout();
		}
		return false;
	})
	$('.grid_toggle').live('click', function(){
		$('#grid_wrap').toggleClass('expose');
		$(this).parent().toggleClass('big');
	})
	// disable grid with text input
	$('input').focus(function(){
		gridEnabled = false;
	})
	$('input').blur(function(){
		gridEnabled = true;
	})
	// tooltip
	$('footer #address').tooltip('<a class="route_info" href="#">routeinformatie</a><a class="open_map" href="#">bekijk kaart</a>');
	$('footer #typen').tooltip('<a href="mailto:info@zinnebeeld.nl">stuur een email</a>');
	$('#wrapper').click(function(){
		$('.tooltip').fadeOut();
	})
	
	$('.links a').not('.arrow').addClass('light');
	// keyboard initializations
	$(document).keydown(function(e){
		var key = 0;
		
		if (e == null){
			key = event.keyCode;
		} else{ // mozilla
			key = e.which;
		}
		
		switch(key){
		case 27:
			// esc
			togglePopup('up');
			if($('#grid:visible').length){
				hideGrid();				
			}
			if($('#map:visible').length){
				closeMap(dragTop);				
			} else if($('#draggable.over_zinnebeeld').length){
				closeAbout();
			}
			break;
		case 37:
			//left
			if($('#popup:visible').length){
				toggleImage('prev');
			} else {
				slidePortfolio('prev');
			}
			break;
		case 39:
			//right
			if($('#popup:visible').length){
				toggleImage('next');
			} else {
				slidePortfolio('next');				
			}
			break;
		case 40:
			//down
			togglePopup('down');
			return false;
			break;
		case 38:	
			//up
			togglePopup('up');
			if($('#map:visible').length){
				closeMap(dragTop);				
			}
			break;
		case 32:
			//spacebar
			toggleGrid();
			if(gridEnabled){
				return false;				
			}
			break;	
		}
	});
	// on window resize
	$(window).resize(function(){
		resizeBackgroundImage($('#background img.loaded'));
		resizeWrapper();
		if($('.ui-draggable-disabled:visible').length || $('#draggable.down').length){
			var dragBottomFixed = -draggable.height() + 15;
			draggable.css({'position': 'fixed', 'top': 'auto', 'bottom': dragBottomFixed});
		} else {
			var perc = ((draggable.offset().top + (draggable.height()/2)) / $(window).height()) * 100;
			draggable.position(perc);
		}
		$('.tooltip').remove();
		if($(window).width() <= 1024){
			$('#draggable').width(1024)
		} else {
			$('#draggable').width('100%')
		}
	});
	
});

// bring the bar down and show the popup
function togglePopup(dir, image){
	if(portfolioEnabled && $('article:visible').find('.open_popup').length){
		if(dir == 'down' && $('#popup:hidden').length){
			var height = $(window).height() - 52;
			dragTop = draggable.css('top');
			draggable.animate({'top' : height}, 300, 'easeOutQuart').addClass('down').draggable('disable');
			getPopup(image);
		} else if(dir == 'up' && $('#popup:visible').length){
			$('#popup').fadeOut(300);
			var dragBottom = $(window).height() - 52;
			draggable.css({'top': dragBottom}).removeClass('down').animate({'top': dragTop}, 300, 'easeOutQuart').css({bottom: ''}).draggable('enable');
		}		
	}
}
function getPopup(image){
	var target = $('.visible .open_popup').attr('href')
	$.ajax({
		url: target,
		success: function(html){
			$("#popup_wrap").html(html);
			$('#popup').position('50', 'none', '500').fadeIn(300);
			if(image){
				image = $('#image_dots .' + image);
				toggleImage(image);
			}
		}
	});

	id = $('.visible').attr('id').split('_id');
	pageTracker._trackPageview('/popup/'+ id[0]);
}
// slide the portfolio left or right
function slidePortfolio(dir){
	if(portfolioEnabled){
		if(dir == 'next'){
			if($('img.key').next().length){
				var key = $('img.key');
				loadImage(key.next());
				$('#projecten .visible').removeClass('visible').next().addClass('visible');
				resizeWrapper();
	
				if ($('#projecten article:last').hasClass('visible')){
					$('.next').removeClass('active');
				}
				$('.prev:not(.active)').addClass('active');
	
				key.removeClass('key').stop().animate({
					left: -$(window).width()
				}, 900, 'easeOutQuart', function(){
					$(this).removeClass('visible');
				})
				if (key.next().css('left') == '0px'){
					resizeBackgroundImage(key.next());			
					key.next().addClass('visible key').css({'left' : $(window).width()});
				}
				key.next().addClass('visible key').stop().animate({
					left: '0px'
				}, 880, 'easeOutQuart');
				
				hash = $('#projecten article.visible').attr('id').split('_id');
				$.address.value(hash[0]);			
//				window.location.hash = hash[0];
		 		pageTracker._trackPageview('/portfolio/'+ hash[0]);
			} 	
		} else {
			if($('img.key').prev().length){
				var key = $('img.key');
				loadImage(key.prev());
				$('#projecten .visible').removeClass('visible').prev().addClass('visible');
				resizeWrapper();
	
	
				if ($('#projecten article:first').hasClass('visible')){
					$('.prev').removeClass('active');
				}
				$('.next:not(.active)').addClass('active');
	
	
				key.removeClass('key').stop().animate({
					left: $(window).width()
				}, 900, 'easeOutQuart', function(){
					$(this).removeClass('visible');
				})
				if (key.prev().css('left') == '0px'){
					resizeBackgroundImage(key.prev());
					key.prev().css({'left' : -$(window).width()});
				}
				key.prev().addClass('visible key').stop().animate({ left: '0px' }, 880, 'easeOutQuart');
				
				hash = $('#projecten article.visible').attr('id').split('_id');
				$.address.value(hash[0]);
//				window.location.hash = hash[0];
		 		pageTracker._trackPageview('/portfolio/'+ hash[0]);
			}
	
		}	
	}
}
// toggle the image of the popup
function toggleImage(image){
	if(image == 'next'){
		if($('#image_dots .active').next().length){
			image = $('#image_dots .active').next();
		} else{
			image = '';
		}
	} else if(image == 'prev'){
		if($('#image_dots .active').prev().length){
			image = $('#image_dots .active').prev();			
		} else {
			image = '';
		}
	} 	
	if(image){
		image = '.'+image.attr('class');	
		$('#popup_wrap .image_wrap, #image_dots a, #captions div').removeClass('active').filter(image).addClass('active');			
	}
}
// 
function gotoProject(id, fade){
			var backgroundIndex = id.index();
			image = $('#background img:eq(' + backgroundIndex + ')');
			$('#projecten .visible').removeClass('visible');
			id.addClass('visible');
			
			$('#background img').not('#background img:eq(' + backgroundIndex + ')').removeAttr('style');
			$('#background img.visible:not(.about_us)').removeClass('visible key');

			if (fade){
				hash = $('#projecten article.visible').attr('id').split('_id');
				$.address.value(hash[0]);			
//				window.location.hash = hash[0];		
		 		pageTracker._trackPageview('/portfolio/'+ hash[0]);						
				image.hide().fadeIn(300).addClass('visible key').css({left: '0'});
				$('#fix').slideToggle();
			} else {
				image.addClass('visible key').css({left: '0'});				
			}
			resizeBackgroundImage($('img.visible'));
			resizeWrapper();
			
			loadImage($('#background img:eq(' + backgroundIndex + ')'));
			if(image.prev().length){
				$('.prev').addClass('active');
			} else {
				$('.prev').removeClass('active');
			}
			if(image.next().length){
				$('.next').addClass('active');
			} else {
				$('.next').removeClass('active');
			}
			if($('#grid:visible').length){
				hideGrid();				
			}
}
function gotoAbout(id){
			$('#draggable').addClass('over_zinnebeeld').position('20', 'slide');
			$('#over_zinnebeeld_wrap article').removeAttr('style').removeClass('visible');
			$('#menu li').removeClass('active');
			var idName = id.attr('id').split('_id');
			$('.' + idName).parent().addClass('active');
			id.addClass('visible');
			portfolioEnabled = false;				
			resizeWrapper();
			if(!$('#background .about_us').length){
				$('#background').append('<img alt="Over Zinnebeeld" src="/site/gfx/about_us.jpg" id="image_22" class="loaded visible about_us">').fadeIn(300);
				resizeBackgroundImage($('#background img:last'));
			}
}
function closeAbout(noslide){
		$('#draggable').removeClass('over_zinnebeeld').find('article').removeAttr('style');
		portfolioEnabled = true;
		$('#background img:last').fadeOut(300, function(){
			$(this).remove();
		});
		if(!noslide){
			if($(window).height() <= 600){
				draggable.position('50', 'slide');
			} else {
				draggable.position('65', 'slide');
			}			
		}
//		window.location.hash = 'portfolio';
}
// show/hide the grid/expose
function toggleGrid(){
	if(!$('#grid').length && gridEnabled){
		$("#wrapper").after('<div id="grid"><div id="grid_wrap" class="expose"></div></div>');
		$.ajax({
			url: '/site/popup/grid.php',
			success: function(html){
				$("#grid_wrap").html(html);
			}
		});
		portfolioEnabled = false;
	} else if ($('#grid:hidden').length && gridEnabled){
		$('#grid, #grid_bg').show();
		$('#grid_wrap').addClass('expose');
		portfolioEnabled = false;
	} else {
		hideGrid();
	}
}
function hideGrid(){
	$('#grid, #grid_bg').hide();
	portfolioEnabled = true;
}
function closeMap(dragTop){
	$('#map, #map_info').fadeOut(300, function(){
		var dragBottom = $(window).height() - 52;
		draggable.css({'bottom': '', 'top': dragBottom}).animate({'top' : dragTop}, 300, 'easeOutQuart', function(){
			count = 0;						
		}).draggable('enable').removeClass('map');
		portfolioEnabled = true;
	});
}
// load image
function loadImage(image){
	if(!image.hasClass('loaded')){
		var link = image.attr('id').split('_');
		image.attr('src', function(){
			return '/content/projectsbig/' + link[1] + '.jpg';
		}).addClass('loaded').load(function(){
			loadPrevNextImage(image);
		});
	} else {
		loadPrevNextImage(image);
	}
}
function loadPrevNextImage(image){
		if(image.next().not('.loaded').length){
			loadThisImage(image.next());
		}
		if (image.prev().not('.loaded').length){
			loadThisImage(image.prev());
		}
}
function loadThisImage(image){
		var link = image.attr('id').split('_');
		image.attr('src', function(){
			return '/content/projectsbig/' + link[1] + '.jpg';
		}).addClass('loaded');

}
// resize the background image
function resizeBackgroundImage(bgImage)
{
	var availableWidth = $(window).width();
	var availableHeight = $(window).height();
	var imageHeight = 800;
	var imageWidth = 1200;
	var curWidth;
	var curHeight;
	
	if(imageHeight < availableHeight || imageWidth < availableWidth)
	{
		var percWidth = Math.floor((availableWidth * 100) / imageWidth);
		var percHeight = Math.floor((availableHeight * 100) / imageHeight);
		
		if(percWidth > percHeight)
		{
			curWidth = availableWidth;
			curHeight = resizeImage(imageWidth, imageHeight, availableWidth, 0, 'returnheight');
		
		} else if(percWidth < percHeight)
		{
			curHeight = availableHeight;
			curWidth = resizeImage(imageWidth, imageHeight, 0, availableHeight, 'returnwidth');
		}
	} else
	{
		//image full size
		curHeight = imageHeight;
		curWidth = imageWidth;
	}
	
	bgImage.css('width', curWidth);
	bgImage.css('height', curHeight);
}

function resizeImage (w, h, nw, nh, coord)
{
	if(coord == 'returnheight')
	{
		var newH = Math.floor((h * nw) / w);
		return newH;
	} else if(coord == 'returnwidth')
	{
		var newW = Math.floor((w * nh) / h);
		return newW;
	}
}

function resizeWrapper(){
	var wHeight = $(window).height() + $('#draggable').height() - 19;
	$('#wrapper').height(wHeight);
}

/* map */

  function initializeMap() {
      if (GBrowserIsCompatible()) {
      		$('#map').css({'height' : ($(window).height() - 52)}).show();
		    var latlng = new google.maps.LatLng(51.9180, 4.4726);
		    

		    var myOptions = {
		      zoom: 14,
		      center: latlng,
		      mapTypeControlOptions: {
		      	style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
		      },
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
		    var image = new google.maps.MarkerImage("/site/gfx/maps_icon.png",
		      // This marker is 20 pixels wide by 32 pixels tall.
		      new google.maps.Size(23, 28),
		      // The origin for this image is 0,0.
		      new google.maps.Point(0,0),
		      // The anchor for this image is the base of the flagpole at 0,32.
		      new google.maps.Point(11, 28));

		    var shadow = new google.maps.MarkerImage("/site/gfx/maps_icon_shadow.png",
		      // This marker is 20 pixels wide by 32 pixels tall.
		      new google.maps.Size(28, 28),
		      // The origin for this image is 0,0.
		      new google.maps.Point(0,0),
		      // The anchor for this image is the base of the flagpole at 0,32.
		      new google.maps.Point(6, 28));

		    var map = new google.maps.Map(document.getElementById("map"), myOptions);
		    var myLatLng = new google.maps.LatLng(51.91791021012185, 4.4729023960876465);
			  var zinnebeeldMarker = new google.maps.Marker({
			      position: myLatLng,
			      map: map,
			      icon: image,
			      shadow: shadow
			  });
			var contentString = '<div id="info_window"><h1>zinnebeeld</h1><p>Mauritsweg 51a <br />3012 JW Rotterdam<br />010 425 80 00</p><div id="info_arrow"></div></div>';
		
			var infowindow = new google.maps.InfoWindow({
			    content: contentString,
			    maxWidth: 10,
			    pixelOffset: new GSize(14, 35)
			});

			infowindow.open(map,zinnebeeldMarker);
				google.maps.event.addListener(zinnebeeldMarker, 'click', function() {
			});
	}
  }