/* related content handler on the work section
 * author Samuil Gospodinov [01.09.2011]
 */

/* Backbone view for the modal window
 * 
 */


function RelatedContentHandler() {
	
	var relatedContentHandler = this;
	
	// parameters setup
	var relatedItemsHolder	= '.relatedContent';
	var relatedItem		= relatedItemsHolder + ' .relatedItem';
	var modalWindow		= 'modalWindowVideo'; 			//the name of the css class for the modal window
	var closeButton		= 'closeModal';				//the name of close button class for the modal window
	var modalWindowContent	= 'modalWindowContent';
	var dataContainer	= 'dataContainer';
	
	//gallery related parameters
	var galleryControlsHolder	= 'galleryControls';
	var galleryHeadingText		= 'galleryHeadingText';
	var galleryContent		= 'galleryContent';
	var galleryItemClassName	= 'galleryItem';
	var lameClickprotection		= false;			//protects the innocent user from berserk clicking
	
	//image related parameters
	var imageWrapperClass		= 'imageWrapper';
	var imageShareButtonClass	= 'imageShare';
	/* init related content handler
	 * binds each related item events
	 * this function is called after work page loads
	 * retuns void
	 */
	this.initRelatedContentHandler = function(){
				
		//bind mouse hover event
		$(relatedItem).live('mouseenter', function(){
			$(this).children('span.overlay').stop(true, true).fadeIn(50);
		});
		
		//bind mouse leave event
		$(relatedItem).live('mouseleave', function(){
			$(this).children('span.overlay').stop(true, true).fadeOut(1000, "easeOutQuad");
		});
		
		//bind click event
		$(relatedItem).live('click', function(){
			
			itemID = $(this).attr('data-item-id');
			relatedContentArea = $(this).parent(); 
			//when we click on a realtedItem we must build the mdoal gallery content and show the modal window
			relatedContentHandler.buildModalWindowContent(itemID, relatedContentArea);
		});
		
		//create the modal window for the related content
		relatedContentHandler.createModalWindow();
		
		//check for data container
		checkForDataContainer = $('#' + dataContainer);
		if(checkForDataContainer.length < 1){
			$('body').append('<div id="' + dataContainer + '"> <!-- --> </div>');
		}
	};
	
	
	/* function to create a modal window wrapper
	 * appends modal window wrapper container to the bottom of the page
	 */
	this.createModalWindow = function(){
		//build the modal window container html with the dummy way
		var html = '<div class="' + modalWindow + ' modalWindow">' +
				'<a href="javascript:;" class="' + closeButton +'"> <!-- --> </a>' +
				'<div class="' + modalWindowContent + '">'+
					'<div class="modaWindowHeader">'+
						'<span class="' + galleryHeadingText + '"></span>'+
						'<span class="' + galleryControlsHolder + '"></span>'+
					'</div>'+
					'<div class="' + galleryContent + '"> </div>'+
				'</div>'+
				
			'</div>';
			
		$('body').append(html);
		
		//bind close button event when modal container is created
		$('.' + closeButton).bind('click', function(){
			relatedContentHandler.hideModalWindow();
		});
	};
	
	/* function to build a modal window for the active item
	 * @param (Int) id - of the current item
	 * @param (DomObject) relatedContentArea - the related area
	 * updates the modal window container content
	 * this function is called when a related content item is clicked
	 * this function calls showModalWindow() when the content is build
	 */
	this.buildModalWindowContent = function(itemID, relatedContentArea){
				
		relateditems = relatedContentArea.children();
		
		
		//add section title to the modal window heading text
		$('.' + galleryHeadingText).html(relatedContentArea.attr('data-related-section-name'));
		
		var autodecrementI = 99999; //for data-showcaseid
		var autodecrementJ = 999999; //for data-uid
		
		$.each(relateditems, function(){
			
			autodecrementI++;
			autodecrementJ++;
			
			relatedItem = $(this);
			relatedItemId = relatedItem.attr('data-item-id');
			
			//add dot controls to the gallery
			var controlItem = document.createElement('a');
			controlItem.innerHTML = '<!-- -->';
			controlItem.setAttribute('href', 'javascript:;');
			controlItem.setAttribute('data-item-relation', relatedItemId);
			controlItem.onclick = relatedContentHandler.animateGalleryitem;
			$('.' + galleryControlsHolder).append(controlItem);
			
			//set the active control element
			if(relatedItemId == itemID){
				controlItem.className = 'active';
			}
			
			
			//create gallery item
			var galleryItem = document.createElement('div');
			galleryItem.setAttribute('id', 'item-' + relatedItemId);
			
			
			//if the gallery item id is equal to the clicked item id assign this item as active to the gallery
			galleryItem.className = (relatedItemId == itemID)?  galleryItemClassName + ' active' : galleryItemClassName;
			
			
			//create item title container
			var itemTitleContainer = document.createElement('div');
			itemTitleContainer.className = 'galleryItemTitle';
			var itemTitle = '';
			
			//build the title form the actuial item title + description
			if($(relatedItem).attr('data-item-title') && $(relatedItem).attr('data-item-description')){
				itemTitle = $(relatedItem).attr('data-item-title') + ' / ' + $(relatedItem).attr('data-item-description');
				
			}else{
				itemTitle = $(relatedItem).attr('data-item-title') + $(relatedItem).attr('data-item-description');
				
			}
			itemTitleContainer.innerHTML = itemTitle;
			
			
			//create additional info holder - office for the item and year of the item
			var additionalInfo = document.createElement('div');
			additionalInfo.className = 'additionalInfo';
			
			//buil additional info string
			additionalInfoString = $(relatedItem).attr('data-item-office') + ' / ' + $(relatedItem).attr('data-item-date');
			additionalInfo.innerHTML = additionalInfoString;
			
			var type = relatedItem.attr('data-item-type');
			//the all content wrapper
			var contentWrapper = document.createElement('div');
			contentWrapper.className = 'contentWrapper';
			
			//check if this well be only an image
			if(type == 'image'){

				//image wrapper
				var imageWrapper = document.createElement('div');
				imageWrapper.className = imageWrapperClass;
				imageWrapper.setAttribute('data-showcaseid', autodecrementI);
				imageWrapper.setAttribute('data-uid', autodecrementJ);
				imageWrapper.setAttribute('data-execution-id', relatedItem.attr('data-execution-id'));
				imageWrapper.setAttribute('data-work-id', relatedItem.attr('data-work-item-id'));
				imageWrapper.setAttribute('data-large_asset_type', type);
				
					//the image
					var image = document.createElement('img');
					var imageSrc = relatedItem.attr('data-item-img-src');
					image.setAttribute('src', imageSrc);
					
					
					//share button
					var imageShare = document.createElement('div');
					imageShare.className = imageShareButtonClass;
					imageShare.setAttribute('data-showcaseid', autodecrementI);
					
				$(imageWrapper).append(imageShare);
				$(imageWrapper).append(image);
				
				$(galleryItem).append(imageWrapper);
				$(galleryItem).addClass('centered');
				$(galleryItem).append(itemTitleContainer);
				$(galleryItem).append(additionalInfo);
				$('.' + galleryContent).append($(galleryItem));
			}
			else{
			
				//build video container
				
				//video controls
				var videoControlWrapper = document.createElement('div');
				videoControlWrapper.className = 'videoControlWrapper videoControlWrapper-regular';
				videoControlWrapper.setAttribute('data-showcaseid', autodecrementI);
					
					var videoControl = document.createElement('div');
					videoControl.className = 'videoControl';
					videoControl.setAttribute('data-showcaseid', autodecrementI);
					
					//play button
					var videoControlPlay = document.createElement('div');
					videoControlPlay.className = 'videoControlPlay videoControlBgPosition videoControlPlayBackgroundPlay';
					videoControlPlay.setAttribute('data-showcaseid', autodecrementI);
					
					//scrubble? button
					var videoControlScrubber = document.createElement('div');
					videoControlScrubber.className = 'videoControlScrubber';
					videoControlScrubber.setAttribute('data-showcaseid', autodecrementI);
					
					var videoControlScrubberBlue = document.createElement('div');
					videoControlScrubberBlue.className = 'videoControlScrubberBlue';
					videoControlScrubberBlue.setAttribute('data-showcaseid', autodecrementI);
					$(videoControlScrubber).append(videoControlScrubberBlue);
					
					//sound button
					var videoControlSound = document.createElement('div');
					videoControlSound.className = 'videoControlSound';
					videoControlSound.setAttribute('data-showcaseid', autodecrementI);
					
					var videoControlSoundInner = document.createElement('div');
					videoControlSoundInner.className = 'videoControlSoundInner';
					videoControlSoundInner.setAttribute('data-showcaseid', autodecrementI);
					$(videoControlSound).append(videoControlSoundInner);
					
					//fullscreen button
					var videoControlFullscreen = document.createElement('div');
					videoControlFullscreen.className = 'videoControlFullscreen videoControlBgPosition';
					videoControlFullscreen.setAttribute('data-showcaseid', autodecrementI);
					
					//share button
					var videoControlShare = document.createElement('div');
					videoControlShare.className = 'videoControlShare videoControlBgPosition';
					videoControlShare.setAttribute('data-showcaseid', autodecrementI);
				
				//showcaseImgWrapper - the video wrapper and image preview
				var showcaseImgWrapper = document.createElement('div');
				showcaseImgWrapper.className = 'showcaseImgWrapper';
				showcaseImgWrapper.setAttribute('data-showcaseid', autodecrementI);
				showcaseImgWrapper.setAttribute('data-uid', autodecrementJ);
				showcaseImgWrapper.setAttribute('data-large_asset_type', type);
				showcaseImgWrapper.setAttribute('data-execution-id', relatedItem.attr('data-execution-id'));
				showcaseImgWrapper.setAttribute('data-work-id', relatedItem.attr('data-work-item-id'));
				
					//video image
					 var FWImg = document.createElement('img');
					 FWImg.className = 'FWImg';
					 FWImg.setAttribute('data-showcaseid', autodecrementI);
					 FWImg.setAttribute('src', relatedItem.attr('data-item-img-src'));
				
				
					//showcaseImgWrapper - the video wrapper and image preview
					
					 var FWVideo = document.createElement('div');
					 FWVideo.className = 'FWVideo';
					 FWVideo.setAttribute('data-showcaseid', autodecrementI);
					 FWVideo.setAttribute('data-large_asset_type', type);
					 if (type == 'video-youtube') {
						 FWVideo.setAttribute('data-youtubevideoid', relatedItem.attr('data-item-media-src'));
					 }
					 FWVideo.setAttribute('id', 'showcase_video'+autodecrementI);
					 FWVideo.setAttribute('width', '760');
					 FWVideo.setAttribute('src', relatedItem.attr('data-item-media-src'));
					 //FWVideo.setAttribute('loop', 'loop');
					 FWVideo.setAttribute('poster', relatedItem.attr('data-item-img-src'));
					 FWVideo.setAttribute('style', 'display; block');
					 
					 var youtubeUnkillableControlsKiller = document.createElement('div');							
					 if(type != 'video-local'){
						youtubeUnkillableControlsKiller.setAttribute('data-showcaseid', autodecrementI);
						youtubeUnkillableControlsKiller.className = 'paintItBlack';
					 }
					
				//append the video components
				
				$(videoControl).append(videoControlPlay);
				$(videoControl).append(videoControlScrubber);
				$(videoControl).append(videoControlSound);
				$(videoControl).append(videoControlFullscreen);
				$(videoControl).append(videoControlShare);
				$(videoControlWrapper).append(videoControl);
				$(showcaseImgWrapper).append(FWImg);
				$(showcaseImgWrapper).append(FWVideo);
				$(showcaseImgWrapper).append(youtubeUnkillableControlsKiller);
				$(contentWrapper).append(videoControlWrapper);
				$(contentWrapper).append(showcaseImgWrapper);
				
				
				$(galleryItem).append(contentWrapper);
				/* Hours spent on trying to run the BBDO's magic code - 9
				 * please increment after each try
				 * no need to increment any more Rado has fixed their base code :) Long Live Rado
				 */
				
				
				
				
				$(galleryItem).append(itemTitleContainer);
				$(galleryItem).append(additionalInfo);
				$('.' + galleryContent).append(galleryItem);
				
				//run the_work setup that dose not work
				var params = {
					width: '760',
					height: '427'
				};
				
				setupVideoControlWrapper(videoControlWrapper, params);

				setupVideoPlayer(FWVideo, params);
				
				//autoplay function
				if(relatedItemId == itemID){
					playPauseVideo(autodecrementI);
					$(FWImg).hide();
					$('#' + dataContainer).attr('data-execution-id', relatedItem.attr('data-execution-id'));
					$('#' + dataContainer).attr('data-work-id', relatedItem.attr('data-work-item-id'));
				}

			}
			
			
		});
		
		relatedContentHandler.showModalWindow();
		relatedContentHandler.shareImage();
	};
	
	/* show modal window
	 * returns void
	 */
	this.showModalWindow = function(){
		relatedContentHandler.centerModalWindow();
		
		//binds on window resize function
		$(window).bind('resize', function(){
			relatedContentHandler.centerModalWindow();
		});
		
		$('.' + modalWindow).show();
		
		
		//bind alternative close methods events
		$('body').bind('click', function(e){
			if((!$(e.target).is('.' + modalWindow) && $(e.target).parents('.' + modalWindow).size() == 0)){
              			relatedContentHandler.hideModalWindow();
      			}
		});
		//bind escape key
		$(document).bind('keyup', function(e) {
		        if(e.keyCode==27){
		        	relatedContentHandler.hideModalWindow();
		        }
		});
	};
	
	/* hide modal window
	 * returns void
	 */
	this.hideModalWindow = function(){
		//hide the modal window
		$('.' + modalWindow).hide();
		
		//clean the modal content
		relatedContentHandler.resetControlItemsAndContent();
		
		//unbind on close events
		$('body').unbind('click');
		$(document).unbind('keyup');
		$(window).unbind('resize');
	};
	
	/* align vertical and horizontal the modal window
	 * returns void
	 */
	this.centerModalWindow = function(keepPosition){
		//get the browser dimensions
		
		var windowWidth = 0;
		var windowHeight = 0;
		//var windowOuterHeight = $('body').outerHeight();
		
		//if in modern browser
		 if(typeof( window.innerWidth ) == 'number' && typeof( window.innerHeight ) == 'number'){
			windowWidth = window.innerWidth;
			windowHeight = window.innerHeight;
		 }else{
			//for ie 8 and below
			windowWidth  = document.documentElement.clientWidth;
    			windowHeight = document.documentElement.clientHeight;
		 }
		
		windowVisibility = $('.' + modalWindow).css('display');
		
		var modalHeight = 0;
		var modalWidth = 0;
		var centerX = 0;
		var centerY = 0;
		
		//get the correct heigt and width ot the modal window 
		//(i think in the future the modal window will be with changable dimensions so i add this functionality now)
		//if the window is not already shown - calculate right dimensions
		if(windowVisibility == 'none'){
			$('.' + modalWindow).css('left', '9999px');
			$('.' + modalWindow).css('display', 'block');
			
			modalHeight = $('.' + modalWindow).outerHeight();
			modalWidth = $('.' + modalWindow).outerWidth();
			
			if(!keepPosition){
				
				centerY = (windowHeight - modalHeight) / 2;
				$('.' + modalWindow).css('position', 'fixed');
				
				
				$('.' + modalWindow).css('top', centerY+'px');
				
				
				newPosition = $('.' + modalWindow).position();
				
				$('.' + modalWindow).css('top', newPosition.top +'px');
				$('.' + modalWindow).css('position', 'absolute');
			}
			
			$('.' + modalWindow).css('display', 'none');
		}else{
			modalHeight = $('.' + modalWindow).outerHeight();
			modalWidth = $('.' + modalWindow).outerWidth();			
		}
		
		
		//calculate the center points
		//if the window inner haeight is grater than the modal height - pos fixed and we dont have scroll
		
		if(windowWidth > modalWidth){
			centerX = (windowWidth - modalWidth - 15) / 2;
		}else{
			// in this case we have a problem with the modal container visibility
			//this shoud never happen and nevertheless it does....
			centerX = (windowWidth - modalWidth) / 2;
			if(centerX < 0) centerX = 0;
		}
		
		$('.' + modalWindow).css('left', centerX+'px');
		
		
	};
	
	/* resets the gallery generated controll items
	 * returns void
	 */
	this.resetControlItemsAndContent = function(){
		pauseAllVideo();
		$('.FWVideo', '.' + modalWindow)
			.each(function() {$(this).tubeplayer("destroy");})
			.each(function() {$(this).jPlayer("destroy");})
			.remove(); 
		$('.' + galleryControlsHolder).children().remove();
		$('.' + galleryHeadingText).children().remove();
		$('.' + galleryContent).children().remove();
	};
	
	
	/* animate gallery element
	 * returns void
	 */
	this.animateGalleryitem = function(obj){
		
		if(lameClickprotection == false){
		
			//first get the element to animate to
			
			//in IE obj = window.event
			//in mozz obj.srcElement  = obj.taret
			var ie = false;
			var mozz = false;
			var animateFrom = 0;
			
			if(navigator.appName == 'Microsoft Internet Explorer'){
				ie = true;
			}else if(navigator.appName == 'Netscape'){
				mozz = true;
			}
			
			//get the data-relation-id attribute from the clicked element
			(ie)?	animateTo = window.event.srcElement.getAttribute('data-item-relation') : (mozz)? animateTo = obj.target.getAttribute('data-item-relation') : animateTo = obj.srcElement.getAttribute('data-item-relation');
			
			//animateFrom = obj.srcElement.attributes[1].value;
			
			//second get the current element to animate from
			elementTo = '#item-'+animateTo;
			elementFrom =  '#' + $('.'+galleryContent+' div.active').attr('id');
			
			
			
			if(elementTo != elementFrom){
				
				//prevent user from clicking while animating
				lameClickprotection = true;
				
				//remove the control active class
				$('.' + galleryControlsHolder + ' .active').removeClass('active');
				
				 $(elementFrom).stop(true, true).fadeOut(100, function(){
				 	
					 $(elementFrom).removeClass('active');
					 
					 $(elementTo).stop(true, true).fadeIn(100);
					 $(elementTo).addClass('active');
					 
					 testForVideo = $(elementTo).children('.contentWrapper');
					 testForImage = $(elementTo).children('.imageWrapper');
					 
					
					 
					 //update related items id's
					 if(testForVideo.length > 0){
						dataElement = $('.active .showcaseImgWrapper');
					 }else if(testForImage.length > 0){
						dataElement = $('.active .imageWrapper');
					 }
					 $('#' + dataContainer).attr('data-execution-id', dataElement.attr('data-execution-id'));
					 $('#' + dataContainer).attr('data-work-id', dataElement.attr('data-work-item-id'));
					 
					 //set the control active class
					 $('.' + galleryControlsHolder + ' a[data-item-relation=' + animateTo + ']').addClass('active');
					 //reset the clickin protection after animation completes
					 lameClickprotection = false;
					 //TO DO NESTASTIE
				 });
			}
		
		}
	};
	/* Share image functionality
	 * setups share image button
	 returns void */
	 this.shareImage = function(){
		$('.' + imageWrapperClass).each(function(){
			
			currentWrapper = $(this);
			var shareButton = currentWrapper.children('.' + imageShareButtonClass);
			
			var dataShowcaseId = currentWrapper.attr('data-showcaseId');
			var workId = currentWrapper.attr('data-uid');
			
			var hasBlurbs = false;
			var shareiMageFlag = true;
						
			//show the share button
			currentWrapper.bind('mouseenter', function(){
				shareButton.stop(true, true).animate({
					bottom: '0px'
				}, 200);					
			});
			
			//hide the share button
			currentWrapper.bind('mouseleave', function(){
				shareButton.stop(true, true).animate({
					bottom: '-45px'
				}, 200);					
			});
			
			//click function
			shareButton.click(function(){
				shareContent(dataShowcaseId, workId, hasBlurbs, shareiMageFlag);
			});
			
		});	
	};
	
	this.removeModalWindow = function(){
		$('.'+modalWindow).remove();
		$(relatedItem).die('mouseenter');
		$(relatedItem).die('mouseleave');
		$(relatedItem).die('click');
	};
}

// create a RelatedContentHandler object
var RelatedContentHandlerObject = new RelatedContentHandler();

$(document).ready(function() {
	//run the init function	- must init only on the work section
	//RelatedContentHandlerObject.initRelatedContentHandler();
});
