// media gallery v2
// written by Matthias on 04/02/10
// compatible with template v2 

// setting global variables
var fadeSpeed = 600;
var bgFadeSpeed = 400;
var mediaArr = new Array();
var media = 0;
var mediaImg = '';
var mediaHeading = '';
var mediaContent = '';
var browserWindowWidth = ($(window).width())-20;
var browserWindowHeight = ($(window).height())-20;
var windowWidth = ($(window).width())-20;
var windowHeight = ($(window).height())-20;
var captionHeight = 0;
var contentWidth = 0; 
var imgWidth = 0;
var imgHeight = 0;
var fileWidth = 0;
var fileHeight = 0;
var boxWidth = 800;
var boxHeight = 540;
var boxPadding = 20;
var btnHeight = 26;
var boxOffsetX = -410;
var boxOffsetY = -280;
var nextBtn = 'Next <span class="mediaDir">&raquo;</span>';
var backBtn = '<span class="mediaDir">&laquo;</span> Back';

$(window).resize(function(){ resizeWindowVars(); });

$(document).ready(function(){
	//console.log('loading gallery...');													 
	$('body').append('<div id="mediaFader"></div><!-- media fader --><div id="mediaContainer"><div id="mediaBox" class="mediaBoxLoader"><div id="mediaButtons"><div id="mediaClose">Close X</div><!-- media close --><div id="mediaNext"></div><!-- media next --><div id="mediaBack"></div><!-- media back --></div><!-- media buttons --><div id="mediaContent"></div><!-- media content --><div id="mediaLeft"><div id="mediaFile"></div><!-- media file --><div id="mediaCaption"></div><!-- media caption --></div><!-- media left --></div><!-- media box --></div><!-- media container -->');
	$('#mediaFader, #mediaContainer').hide();
	if($.browser.msie && $.browser.version == 6) {
		$('body').css('overflow-y','auto');
		$('html').css('overflow-y','hidden');
		$('#nav li').each(function(){ $(this).css('position','static'); });
	}
													 
	// setting up the functions for when an image has been clicked on
	$('#media li, #productImage li').each(function(i){
		mediaArr[(i+1)] = 'media'+(i+1);
		$(this).click(function(){
			media = i+1;
			fadeBg((i+1));
			return false;
		});
	});
	
	// close the popup
	$('#mediaContainer, #mediaClose').click(function(){
		//console.log('... closing ...');
		$('#mediaFader, #mediaContainer').fadeOut(bgFadeSpeed, function() { unloadMedia() } );
		if($.browser.msie && $.browser.version == 6) {
			$('select').each(function(){
				$(this).show();
			});
		}
	});
	
	// overrides the content from being closed when clicking inside
	$('#mediaBox').click(function(){ return false; });
	
	// move gallery to the next image
	$('#mediaNext').click(function(){
		//console.log('next has been clicked');
		if(media < mediaArr.length-1) {
			media = media+1;
			getContent(media);	
		}
	});
	
	// move gallery to the previous image
	$('#mediaBack').click(function(){
		//console.log('back has been clicked');
		if(media > 1) {
			media = media-1;
			getContent(media);	
		}
	});
	
});


// resizes the main function window
function resizeWindowVars() {
	browserWindowWidth = ($(window).width())-20;
	browserWindowHeight = ($(window).height())-20;
	windowWidth = ($(window).width())-20;
	windowHeight = ($(window).height())-20;
}


// fades the background in
function fadeBg(media) {
	//console.log('fading bg in...');
	//console.log('media: '+media);
	if($.browser.msie && $.browser.version == 6) {
		$('select').each(function(){
			$(this).hide();
		});
	}
	$('#mediaFader, #mediaContainer').fadeIn(bgFadeSpeed, getContent(media));
}

// unloads the media from the content area, so its not there next time we come
function unloadMedia(){
	$('#mediaContent').empty();
	$('#mediaCaption').empty();
	$('#mediaFile').empty();
};


// loading in the image and content
function getContent(media){
	//console.log('has faded up');	
	//console.log('is array: '+is_array(mediaArr[media]));
	//$('#mediaFile').fadeOut(fadeSpeed,function(){ $('#mediaFile').empty(); });
	$('#mediaBox').addClass('mediaBoxLoader');
	
	// show / hide the next and back btns
	$('#mediaBack, #mediaNext').empty();
	if(media < 2) {
		$('#mediaBack').css('cursor','default'); 
		$('#mediaBack').empty();
	} else {
		$('#mediaBack').css('cursor','pointer'); 
		$('#mediaBack').append(backBtn);
	}
	if(media >= mediaArr.length-1) {
		$('#mediaNext').css('cursor','default');
		$('#mediaNext').empty(); 
	} else {
		$('#mediaNext').css('cursor','pointer'); 
		$('#mediaNext').append(nextBtn);
	}
	
	// here i am getting the guid of the image so we can use ajax to get the content for the popup
	imgGuid = $('.media'+media).attr('id').replace('m','');
	$('#productMedia').length == '1' ? galType = 'product' : galType = 'gallery';

	if(!is_array(mediaArr[media])) {
		$.post(
			//'../testAjax.php',
			'?gal='+galType,
			{ guid: imgGuid },
			function(data) {
				var data = data.replace('\r\n','').split('{wt:');
				data[1] = data[1].replace('Image =','').replace('\r\n','');
				data[2] = data[2].replace('Heading =','').replace('\r\n','');
				data[3] = data[3].replace('Content =','').replace('\r\n','');
				mediaArr[media] = data;
				removeElements();
				//loadImage();
			}
		);
	} else {
		//console.log('content already loaded'); 	
		removeElements();
		//loadImage();
	}
	////console.log(mediaArr);
}

// checks if an image is an array or not
function is_array(input){
	return typeof(input)=='object'&&(input instanceof Array);
}

// load in the image so we can get the dimensions to resize the box
function loadImage(){
	//console.log('--- loading in image ---');	
	////console.log(mediaArr[media]);
	//removeElements();
	var img = new Image();
	// once the image has loaded, run the code
	$(img)
		.load(function () {
			// set the image hidden by default    
			$(this).hide();
			//console.log($(this));
			//console.log('loaded the image');
			// fade our image in to create a nice effect
			$('#mediaFile').append(this);
			imgWidth = $(this).width();
			imgHeight = $(this).height();
			////console.log('width: '+imgWidth);
			////console.log('height: '+imgHeight);
			// check if there is content
			////console.log('caption length: '+mediaArr[media][2].length);
			////console.log('content length: '+mediaArr[media][3].length);
			mediaArr[media][2].length > 1 && mediaArr[media][3].length < 1 ? captionHeight = 21 : captionHeight = 0;
			mediaArr[media][3].length > 1 ? contentWidth = 210 : contentWidth = 0;

			// adding the new constraints to the image before it gets resized
			// resize window with and height
			windowWidth = browserWindowWidth - contentWidth - boxPadding; 
			windowHeight = browserWindowHeight - captionHeight - boxPadding - btnHeight;
			////console.log('windowWidth: '+windowWidth);
			////console.log('windowHeight: '+windowHeight);
			
			////console.log('contentWidth: '+contentWidth);
			////console.log('captionHeight: '+captionHeight);
			resizeItem();
			
			// now we set the new widths and heights of the box
			boxWidth = fileWidth + contentWidth;
			boxHeight = fileHeight + captionHeight + btnHeight;
			//console.log('img width: '+imgWidth);
			//console.log('img height: '+imgHeight);
		//	//console.log('box width: '+boxWidth);
		//	//console.log('box height: '+boxHeight);
			// now we make the new off sets for the box
			boxOffsetX = -(boxWidth / 2)-10;
			boxOffsetY = -(boxHeight / 2)-10; 
			
			$('#mediaFile img').width(imgWidth);
			$('#mediaFile img').height(imgHeight);
			////console.log('------');
		//	//console.log('width: '+imgWidth);
		//	//console.log('height: '+imgHeight);
			//$(this).show();
			//setTimeout("resizeBox()",600);
			resizeBox();
		})
		.error(function () {
			alert('error loading image');
			$('#mediaFader, #mediaContainer').fadeOut(bgFadeSpeed, function() { unloadMedia() } );
		})
		.attr('src', mediaArr[media][1]).css({
			'position':'absolute',
			'top':130+'%',
			'left':130+'%'
		});
		
}


// remove elements 
function removeElements(){
	//console.log('---- resizing box ----');

	// first step we remove elements that dont need
	$('#mediaContent').fadeOut(300,function(){ $('#mediaContent').empty(); });	
	$('#mediaCaption').fadeOut(300,function(){ $('#mediaCaption').empty(); });
	$('#mediaFile img').fadeOut(300,function(){ $('#mediaFile').empty() });
	setTimeout("loadImage()",400);
	
}


// resizes the box 
function resizeBox() {
	// now we resize the width
	$('#mediaBox').animate({
		width: boxWidth,
		marginLeft: boxOffsetX
	}, fadeSpeed, function(){
		// now resize the height
		$('#mediaBox').animate({
			height: boxHeight,
			marginTop: boxOffsetY
		}, fadeSpeed, function() { loadContent() });
	});
}

// load in the content that is needed for this section
function loadContent(){
	// load in the caption and content
	//console.log('media img - : '+$('#mediaFile img').attr('src'));
	if($('#mediaFile img').attr('src') == null) { $('#mediaFile').append('<img src="'+mediaArr[media][1]+'" width="'+imgWidth+'" height="'+imgHeight+'"/>'); $('#mediaFile img').hide(); }
	if(mediaArr[media][2].length > 1 && mediaArr[media][3].length < 1) { $('#mediaCaption').html(mediaArr[media][2]).fadeIn(fadeSpeed); } // if only caption
	else if(mediaArr[media][2].length > 1 && mediaArr[media][3].length > 1) { $('#mediaContent').height(fileHeight).html('<h2>'+mediaArr[media][2]+'</h2>'+mediaArr[media][3]).fadeIn(fadeSpeed); } // if caption and content
	else if(mediaArr[media][3].length > 1) { $('#mediaContent').html(mediaArr[media][3]).height(fileHeight).fadeIn(fadeSpeed); }
	$('#mediaFile').width(fileWidth).height(fileHeight);
	$('#mediaLeft').width(fileWidth);
	$('#mediaFile img').css({
		'position':'absolute',
		'top':50+'%',
		'left':50+'%',
		'marginTop':-Math.floor(imgHeight/2),
		'marginLeft':-Math.floor(imgWidth/2)
	});
	$('#mediaFile img').fadeIn(fadeSpeed, function(){ $('#mediaBox').removeClass('mediaBoxLoader'); });
	
	//making any content links work
	$('#mediaContent a').each(function(){
		$(this).click(function(){
			window.open($(this).attr('href'));
		});
	});
}


// resizes the image
function resizeItem() {
	if (imgWidth > windowWidth) {
		imgHeight = imgHeight * (windowWidth / imgWidth); 
		imgWidth = windowWidth; 
		if (imgHeight > windowHeight)	{ 
			imgWidth = imgWidth * (windowHeight / imgHeight); 
			imgHeight = windowHeight; 
		}
	} else if (imgHeight > windowHeight) { 
		imgWidth = imgWidth * (windowHeight / imgHeight); 
		imgHeight = windowHeight; 
		if (imgWidth > windowWidth){ 
			imgHeight = imgHeight * (windowWidth / imgWidth); 
			imgWidth = windowWidth;
		}
	}
	
	imgWidth = Math.floor(imgWidth);
	imgHeight = Math.floor(imgHeight);
	
	imgWidth < 250 ? fileWidth = 250 : fileWidth = imgWidth;
	imgHeight < 250 ? fileHeight = 250 : fileHeight = imgHeight;
	

};



