var zoomlevel = 0;
var zoomspeed = 500;
var dragging = false;

// store the zoomed out position to return to from a zoom in
var zoom_left = 0;
var zoom_top = 0;
var initload = 0;
	
$(document).ready(function(){
	
	$('#subnav').hide();
	
	$(document).mousemove(function(e){
      	$('.pointer').css({'left':e.pageX+10, 'top': e.pageY-15});
	}); 
 
	
	$('#logo').click(function(){
		reposition('reset');
		return false; // not strictly necessary, but IDC ~TD
	});
	

	//hotkeys
		$(document).bind('keydown', 'Ctrl+=', function (evt){
			var newwidth = $('#images').width()*1.3; 
			var newheight = $('#images').height()*1.3; 
			$('#images').animate({"width":newwidth, "height":newheight}, 200, "easeOutQuint");
			return false;
		});
	
		$(document).bind('keydown', 'Ctrl+-',function (evt){
			var newwidth = $('#images').width()*0.7; 
			var newheight = $('#images').height()*0.7; 
			$('#images').animate({"width":newwidth, "height":newheight}, 200, "easeOutQuint");
			return false;
		});

	$('#btn-gallery').click(function(){
		reposition('reset');
		$('#subnav').show();
	});
	$('#btn-about').click(function(){
		$('#about').click();
		return false;
	});
	//$('#btn-contact').click(function(){
	//	$('#contact').click();
	//	return false;
	//});
	$('#btn-spring').click(function(){
		$('#spring').click();
		return false;
	});
	$('#btn-winter').click(function(){
		$('#winter').click();
		return false;
	});
	$('#btn-summer').click(function(){
		$('#summer').click();
		return false;
	});
	$('#btn-autumn').click(function(){
		$('#autumn').click();
		return false;
	});	
	
	for(i=0;i<data.length;i++){
	 	
		getPhoto(i);
										
	}
		
	
	function getPhoto(i){
		var x = data[i].left;
		var y = data[i].top;
		//$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=9155035905a7d2240b4cfbea5b95053d&photo_id="+data[i].id+"&format=json&jsoncallback=?", function(photo){
			//var src = "http://farm"+photo.photo.farm+".static.flickr.com/"+photo.photo.server+"/"+photo.photo.id+"_"+photo.photo.secret+"_m.jpg";
	        var imgx = x/$('#images').width()*100+'%';
			var imgy = y/$('#images').height()*100+'%';				
			var src = 'img/' + data[i].id + '.png';
			var alt = (data[i].alt) ? data[i].alt : data[i].id;
			$("<img/>").attr("src", src).attr("id",data[i].id).attr("alt", alt).css({"left":imgx, "top":imgy}).addClass('clickable').appendTo("#images");
			sizeImg(data[i].id);
			
		//});
	}
	
	function sizeImg(id){
		var img = $("#"+id);
		img.load(function(){
			var parent = img.parent();
			var width = parseInt(img.width())*1.1064;
			var height = parseInt(img.height())*1.1064; 

			img.width( width/parseInt(parent.width())*100+"%" );
			img.height( height/parseInt(parent.height())*100+"%" );
		
			loadcheck();
		});
	}
	
	function loadcheck(){
		initload++;
		if(initload==data.length){
			
			//var screenwidth = ( $(window).width() ) / 10;
			//var screenheight = screenwidth * 0.51851852;
			var screenheight = ( $(window).height() ) / 10;
			var screenwidth = screenheight / 0.51851852;
			//var middle = ((screenwidth/10)*-1)+'em';
			
			screenwidth = screenwidth+'em';
			screenheight = screenheight+'em';
			$('#images').css({'top':'30px', 'width':screenwidth, 'height':screenheight});
			
			$('#loading').fadeOut(50, function(){
				//$(this).css({'background-color':'transparent'});
				$(this).remove();
				$('.pointer').fadeIn(200).animate({'opacity':1}, 8000, function(){
					$(this).fadeOut(200);
				})
			});
			
			//patch
			$('.contact-content').css({'top':$('#contact').css('top'), 'left':$('#contact').css('left')});
			
	
		
		}
	}


	$('#images').live('click', function( event ){
		if( $(event.target).is('input, textarea, .contact-content') ) return;
		if( !$(event.target).is('.clickable') ){
			dragging = false;
			reposition('reset');
		}
	
    });
	

	$('#images').bind('dragstart', function( event ){
		if( $(event.target).is('.clickable') ){
			dragging = false;
		}
	
    });

	$('#images').bind('dragend', function( event ){
		if( $(event.target).is('.clickable') ){
			dragging = true;
		}
		//console.log('left: '+event.offsetX+'; top: '+event.offsetY);
		checkBounds(event.offsetX, event.offsetY);
		
    });	
	
	$('#images').bind('drag',{distance:10}, function( event ){

	    $( this ).css({
        	top: event.offsetY,
        	left: event.offsetX
        });
    });

$('a.tmp').live('click', function(){

	window.open($(this).attr('href'));
	return false;
});

$('.clickable').live("click", function(){

	if(dragging){
		dragging=false;
		return false;
	}
	
	// contact link (google maps)
	if ( $(this).attr('id') == 'contact'){
		
		if( $('#images').hasClass('zoomed') ){

			top1 = $(this).css('top');
			left1 = $(this).css('left');
			href1 = "http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Blue+Lavender+London&sll=51.475663,-0.239553&sspn=0.008246,0.03032&ie=UTF8&ll=51.4774,-0.228353&spn=0.01716,0.060639&z=15&iwloc=A";
			$('<a/>').attr('href',href1).addClass('tmp').css({'background':'transparent','display':'block','position':'absolute', 'top':top1,'left':left1,'width':'162px', 'height':'20px','margin-top':'315px','margin-left':'450px','cursor':'pointer'}).insertAfter(this);
			return false;
		}
		
	}
	
	reposition( $(this) );
	// position links over images that need them
	// note: links are removed in reposition() function
	
	// about link (brochure)	
	if( $(this).attr('id') == 'about'){
		
		if( $('#images').hasClass('zoomed') ){

			top2 = $(this).css('top');
			left2 = $(this).css('left');
			href = "brochure.pdf";
			$('<a>').attr('href','brochure.pdf').attr('target', '_blank').css({'background':'url(../img/about_zoom_link.gif)','display':'block','position':'absolute', 'top':top2,'left':left2,'width':'182px', 'height':'20px','margin-top':'250px','margin-left':'50px','cursor':'pointer'}).insertAfter(this);
			
		}
	}
	
	
});

function checkContent(elemid){
	var clicked = $('#'+elemid);
	var contents = $('.'+elemid+'-content');
	var contentoffset = clicked.offset();
	
	if(contents.hasClass('season')){
		/*contents.css({
		    'position':'absolute', 
		    'top': clicked.css('top'), 
		    'left': clicked.css('left'), 
		    'width': clicked.width()-100, 
		    'height': clicked.height()-100,
		});*/
	}else{
		if($('#images').hasClass('zoomed')){
			contents
			.css({
				//'width':   clicked.width(),
				//'height':  clicked.height(),
				//'top':     contentoffset.top,
				//'left':    contentoffset.left,
				'position':'absolute',
				'z-index':1000
			})
			.fadeIn(100);
		
		} else {
			$('.contact-content').fadeOut(100);
			contents.fadeOut(100);
		}
	}
}

	
	
	function reposition(el){
		$('#subnav').hide();
		if(el == 'reset'){
			el=$('#images');
			zoomlevel = 0;
			el.addClass('active');
			zoom_left=0;
			zoom_top=0;
		}

		var start_left = parseFloat(el.css('left'))/100;
		var start_top = parseFloat(el.css('top'))/100;
		var cw = $(window).width();
		var ch = $(window).height();
		var left = 0;
		var top = 0;


			if(el.hasClass('active')){		
				//width = cw / 10;
				//height = width * 0.51851852;
				height = ch/10;
				width = height / 0.51851852;
				left = zoom_left;
				top = zoom_top;

				zoomlevel = 0;
				
				$('.active').removeClass('active');
								
				$('#images').removeClass('zoomed').find('a.tmp').remove();	
				$('.pointer').removeClass('move').html('click to zoom in');
				
				//revert detail on all zoomed images
				$('img.zoomedimage').each(function (i){
					lod( $(this) );
				});			
				
				$('#nav').css({'z-index':100}).animate({'opacity':1}, 500);
				
			
			}else{
				//image clicked left/top to px
				imgleft = (el.width() / 2);
				imgtop = (el.height() / 2);
			
				//if we're zoomed out set for zoomed in w/h
				if( !( $('#images').hasClass('zoomed') ) ){
					imgleft *=(534/cw*10);
					imgtop *=(277/ch*10);
				
					
				}else{
				
				}
				
				//center of screen
				windowleft = cw/2;
				windowtop = ch/2;
				
				width = 534;
				height = 277;

				//container offsets
				left =  (start_left * width * 10 - windowleft + imgleft) * -1;
				top =  (start_top * height * 10 - windowtop + imgtop) * -1;
				
				$('#images').addClass('zoomed');
				$('.pointer').addClass('move').html('grab and drag to explore').show().animate({'opacity':1}, 10000, function(){
					$(this).fadeOut(200).remove();
				});
					
				$('.active').removeClass('active');
				
				el.addClass('active');
				
			
				
			}
	
		
		//$('#images img.clickable').hide();
		//$('.blur').show();
		//$('#images').append('<img class="blur" src="img/blur.jpg" width="100%" height="100%" />');
		
		$('#images').animate({"width":width+'em', "height":height+'em', "left":left+'px', "top":top+'px'}, zoomspeed, "easeOutCubic", function(){
			
			
			offset = $('#images').offset();
			checkBounds(offset.left, offset.top);
			
			if(el.attr('id')!='images'){
				lod(el);
			}
			//$('#images img.clickable').show();
			//$('.blur').hide();
			
			
		});
	}
	
	function lod(lodelement){
	
		//level of detail toggle
		if(lodelement.hasClass('zoomedimage')){
			
			if( !( $('#images').hasClass('zoomed') ) ){
				//revert to original res
				var original = 'img/' + lodelement.attr('id') + '.png';
				lodelement.attr('src', original);
				lodelement.removeClass('zoomedimage');
			}
		
		}else{
			
			//swap for high res
			var original = 'img/' + lodelement.attr('id');
			var highres = 'img/bl_' + lodelement.attr('id') + '.jpg';
			
			//exceptions
			highres = (lodelement.attr('id')=='autumn') ? 'img/autumn_zoom.png' : highres;
			highres = (lodelement.attr('id')=='autumn5') ? 'img/autumn5_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring') ? 'img/spring_zoom.png' : highres;
			highres = (lodelement.attr('id')=='winter') ? 'img/winter_zoom.png' : highres;
			highres = (lodelement.attr('id')=='winter9') ? 'img/winter9_zoom.png' : highres;
			highres = (lodelement.attr('id')=='winter3') ? 'img/winter3_zoom.png' : highres;
			
			highres = (lodelement.attr('id')=='summer') ? 'img/summer_zoom.png' : highres;
			highres = (lodelement.attr('id')=='summer6') ? 'img/summer6_zoom.png' : highres;
			highres = (lodelement.attr('id')=='summer7') ? 'img/summer7_zoom.png' : highres;
			highres = (lodelement.attr('id')=='summer8') ? 'img/summer8_zoom.png' : highres;
			highres = (lodelement.attr('id')=='summer9') ? 'img/summer9_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring2') ? 'img/spring2_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring3') ? 'img/spring3_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring7') ? 'img/spring7_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring8') ? 'img/spring8_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring5') ? 'img/spring5_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring9') ? 'img/spring9_zoom.png' : highres;
			highres = (lodelement.attr('id')=='spring11') ? 'img/spring11_zoom.png' : highres;
			
			
			
			var originalwidth = lodelement.css('width');
			var originalheight = lodelement.css('height');
			
			$('.loader').css({'width':originalwidth, 'height': originalheight, 'left':lodelement.css('left'), 'top':lodelement.css('top')}).fadeIn();			
			
			lodelement.attr('src', highres);
			
			lodelement.load(function(){
				checkContent(lodelement.attr('id'));
				lodelement.css({ 'width': originalwidth, 'height': originalheight });
				$('.loader').fadeOut();	
			});
			lodelement.addClass('zoomedimage');
		}
		
	}
	
	
	function checkBounds(x, y){
		var padding = ($('#images').hasClass('zoomed')) ? 1000 : 0;

		var imagesboundsX = $('#images').width()+x+padding;
		var imagesboundsY = $('#images').height()+y+padding;

		var cw = $(window).width();
		var ch = $(window).height();
		var newx = null;
		var newy = null;
	
		//console.log(padding+'  = '+ x+', '+y+' | '+imagesboundsX+', '+imagesboundsY);
	
		if(imagesboundsY<ch || imagesboundsX<cw || y > padding || x > padding){
	
			if(imagesboundsY<ch || imagesboundsX<cw){
				newx = (imagesboundsX < cw) ? cw-$('#images').width() : x;
				newy = (imagesboundsY < ch) ? ch-$('#images').height() : y;
				x = newx;
				y = newy;

			}		
	
			if(y > padding || x > padding){
				newy = (y > padding) ? 0 : y;
				newx = (x > padding) ? 0 : x;
			}
		
			$('#images').animate({	left: newx, top: newy }, 300, "easeOutQuint");
		}
	}

});
