Mediagallery = {
    activePhotoElm: '', // var for active photo in Media Gallery

	init: function() {
       	if($('#fotogallerij').length > 0) {
       		Mediagallery.gallery('#fotogallerij');
		}
       	if($('#mediagallerij').length > 0) {
       		Mediagallery.gallery('#mediagallerij', true);
		}
    },
    
    print: function(id) {
    	var jFrame = $( "<iframe name='printFrame'></iframe>" );
    	
    	
    	sections = $(id).attr('src').split('/');
    	fileName = sections[sections.length-1];
    	
    	jFrame.attr('src', websiteGlobal.baseUrl + '/printphoto/' + fileName);
    	
    	jFrame.css( "width", "1px" );
    	jFrame.css( "height", "1px" );
    	jFrame.css( "position", "absolute" );
    	jFrame.css( "left", "-99999px" );
    	
    	jFrame.appendTo($("body"));

    	setTimeout(function(){
        	var iFrame = window.frames['printFrame'];
        	
        	iFrame.focus();
        	iFrame.print();
    		
    	}, 1000);
    	
    	setTimeout(function(){jFrame.remove();}, 60000);
    },
    
	photoSwitch: function(modalWindow, image) {
		Mediagallery.buttons();
		
		var elmImage = $('<img id="xl-image" src="'+image+'" alt=""/>');

		if(!modalWindow) modalWindow = $('div#large-picture');
		$(modalWindow).find('.imagecontainer').html(elmImage);
		
		var alt = $(activePhotoElm).find('img').attr('alt');
		$(modalWindow).find('.headertitle').html(alt);

		var photoText = $(activePhotoElm).find('input[name=phototext]').val();
		$(modalWindow).find('.phototext').html(photoText);

		// place print image direct in body so we can print it
		$(modalWindow).find('img#printfoto-img').attr('src', elmImage.attr('src'));
		$('body').append($('#printfoto').remove());
		
		// trim display image
		elmImage.attr('src', elmImage.attr('src') + '?action=fit&w=370&h=331');

		var headername = $(activePhotoElm).find('.caption').html();
		if (headername != '' && headername != null && headername != alt) {
			$(modalWindow).find('.headername span').html(headername);
			$(modalWindow).find('.headername').show();
		} else {
			$(modalWindow).find('.headername').hide();
		}
		
		Mediagallery.showModalWindow(modalWindow);
	},
	
	nextPhoto: function() {
		activePhotoElm = $(activePhotoElm).next('li');
		var image = $(activePhotoElm).find('input[name=xlarge_image]').val();
		Mediagallery.photoSwitch(null, image);
	},

	previousPhoto: function() {
		activePhotoElm = $(activePhotoElm).prev('li');
		var image = $(activePhotoElm).find('input[name=xlarge_image]').val();
		Mediagallery.photoSwitch(null, image);
	},
	
	showModalWindow: function(modalWindow, id) {
		$(modalWindow).modal({
			closeClass: 'close',
			opacity: 50,
			containerId: 'photogallery-container',
			onOpen: function (dialog) {
				dialog.overlay.fadeIn('slow', function () {
					dialog.data.hide();
					dialog.container.fadeIn('fast', function () {
						dialog.data.slideDown('normal');
					});
				});
			},
			onClose: function (dialog) {
				dialog.data.fadeOut('slow', function () {
					dialog.overlay.fadeOut('fast', function () {
						$.modal.close();
						$(modalWindow).remove();
						if($('div#large-picture').length >0) {
							$('div#large-picture').remove();
						}
						if($('div#itemcontainer').length >0) {
							$('div#itemcontainer').remove();
						}
						
					});
				});
			}
		});
	},
	
	switchModalWindow : function(modalWindow) {
		$('#photogallery-container *').fadeOut('slow', function() { $(this).remove(); } );

		modalWindow.hide();
		$('#photogallery-container').append(modalWindow);
		modalWindow.show('slow');
	},
	
	sendToFriend : {
		closeForm: function(){
			$('div#itemcontainer').fadeTo("slow", 1);
			$('div#itemcontainer-2').fadeTo("normal", 0, function() {
				$('div#itemcontainer-2').remove();
			});
			
		},
		
		showForm: function(item) {
			var modalWindow = Mediagallery.sendToFriend.getModalWindow(item);
			Mediagallery.switchModalWindow(modalWindow);
			
			// cancel sendToFriend 
			$('div#large-picture input#formcancel').click(function () {
				Mediagallery.sendToFriendClose();
			});


			$('#sendafriend_form').submit(function(){
				return false;
			});

			// close send to friend window after sending the form
			$('#photosent_footer a').click(function () {
				Mediagallery.sendToFriendClose();
				return false;
			});

			//if submit button is clicked  
		    $('form#sendafriend_form #form_submit').click(function () { 
		         //Get the data from all the fields  
		         
		         var toName = $('input[name=form_toname]');  
		         var toEmail = $('input[name=form_tomail]');  
		         var message = $('textarea[name=form_message]');  
		         var fromName = $('input[name=form_fromname]');  
		         var fromEmail = $('input[name=form_frommail]');
		         var itemID = $('input[name=form_itemid]');
		         var type = $('input[name=form_type]');
		         
		         var extravalues = '';
		         if($('input[name=form_extra]').val()){
		         	extravalues = $('input[name=form_extra]').val();
		         }
 
		         //var targetPage = window.parent.location.href;
				 
				 //remove highlights before checking fields again
				 $('form#sendafriend_form input').removeClass('hightlight');  

		         //Simple validation to make sure user entered something  
		         //If error found, add hightlight class to the text field  
		         if (fromName.val()=='') {  
		             fromName.addClass('hightlight');  
		             return false;  
		         } else fromName.removeClass('hightlight');  
		          
		         if (fromEmail.val().length < 5 || (fromEmail.val().indexOf(".") < 3) || (fromEmail.val().indexOf("@") < 1)) {  
		             fromEmail.addClass('hightlight');  
		             return false;  
		         } else fromEmail.removeClass('hightlight');   
		         		         
		         if (toName.val()=='') {  
		             toName.addClass('hightlight');  
		             return false;  
		         } else toName.removeClass('hightlight');  
		           
		         if (toEmail.val().length < 5 || (toEmail.val().indexOf(".") < 3) || (toEmail.val().indexOf("@") < 1)) {  
		             toEmail.addClass('hightlight');  
		             return false;  
		         } else toEmail.removeClass('hightlight');  
		         
         
				
		         //organize the data properly  
		         var data = 'form_toname=' + toName.val() + '&form_tomail=' + toEmail.val() + '&form_message='  
		         + encodeURIComponent(message.val()) + '&form_fromname=' + fromName.val() + '&form_frommail=' + fromEmail.val()
		         + '&form_itemid=' + itemID.val() + '&form_type=' + type.val() + '&extravalues=' + extravalues ;  
				
		         //start the ajax  
		         $.ajax({  
		             //this is the php file that processes the data and send mail  
		             url: $('#sendafriend_form').attr('action'),   
					 type: "POST",           
		             data: data,       
		             cache: false,  
		               
		             //success  
		             success: function (html) {                
		                 //if returned 1/true (send mail success)  
		                 if (html==1) {                    
		         			var modalWindow = Mediagallery.sendToFriend.getSuccessModalWindow(item);
		        			Mediagallery.switchModalWindow(modalWindow);
			             //if sendafriend.ajax.php returned 0/false (send mail failed)  
		                 } else {
		                 	alert(html);                 
		                 }
		             }         
		         });  
		        
		         //cancel the submit button default behaviours  
		        return false;  
		     });
		},
	
		getModalWindow : function(image) {
			var form = $('<form id="sendafriend_form" action="'+websiteGlobal.baseUrl+'/verstuur_foto/submit" method="post" ></form>');
			form.append('<img src="'+image+'?action=fit&w=100&h=100" id="form_thumbnail" alt="" width="100" height="100" />');
	
			form.append('<div id="input_fromname"><label>Jouw naam</label><input type="text" name="form_fromname" /></div>');
			form.append('<div id="input_frommail"><label>Jouw Emailadres</label><input type="text" name="form_frommail" /></div>');
			form.append('<div id="input_toname"><label>Naam ontvanger</label><input type="text" name="form_toname" /></div>');
			form.append('<div id="input_tomail"><label>Email ontvanger</label><input type="text" name="form_tomail" /></div>');
			form.append('<div id="text_message"><label>Bericht</label><textarea name="form_message"></textarea></div>');
	
			form.append('<input type="hidden" name="form_itemid" id="form_itemid" value="'+image+'" />');
			form.append('<input type="hidden" name="form_type" id="form_type" value="photo" />');
			form.append('<input type="hidden" name="form_extra" id="form_extra" value="media" />');
	
			var footer = $('<div id="sendafriend_footer"></div>');
			footer.append('<div id="button_submit"><input type="submit" id="form_submit" name="form_submit" value="" /></div>');
			footer.append('<div id="button_cancel"><input type="button" name="form_cancel" value="" onClick="javascript:$.modal.close()"/></div>');
			form.append(footer);
	
			var modalWindow = $('<div id="sendafriend" class="showForm" ></div>');
			modalWindow.append(form);
			return modalWindow;
		},
		
		getSuccessModalWindow: function(item) {
			var modalWindow = $('<div id="sendafriend" class="showForm" ></div>');
			modalWindow.append('<div id="photosent"><div id="photosent_footer"><a href="#" onClick="javascript:$.modal.close()"></a></div></div>');
			return modalWindow;
		}

	},
	
	photoGallery : {
	    getModalWindow: function(item, image) {
			var elmImage = $('<img id="xl-image" src="'+image+'" alt=""/>');
			activePhotoElm = $(item).parent();
	
			var sPrintLink = '<a class="print" href="javascript:Mediagallery.print(\'#printfoto-img\');" title="print foto">&nbsp;</a>';
			var sHeaderName = '<div class="headertitle"> </div><div class="headername"><span></span></div>';
			var sHeader = '<div class="headerprint"> </div><a class="ecard" href="javascript:Mediagallery.sendToFriend.showForm(\''+image+'\')"></a>';
			var sContent = '<div class="content"><div class="imagecontainer"></div></div>';
			var sFooter = '<div class="footer"><div class="close"></div></div>';
			var sScrollFooter = '<div class="footer"><div class="previous"></div><div class="close"></div><div class="next"></div></div>';
			var sMailto = '<div id="sendafriend" class="showForm"></div>';
			var sPrint = '<div id="printfoto"><img alt="" src="website/img/popups/printlogo_500.jpg"/><img alt="" id="printfoto-img" /></div>';
			
			parentList = $(item).parent().parent('ul');
			
			page = $('<div id="itemcontainer"></div>');
			
			if (parentList.is('.sportnieuws-gallerij')) {
				page.addClass('sportnieuws-photo'); 
				page.append(' \
						<div class="textcontent">' + sHeaderName + '<div class="phototext"></div></div> \
						<div class="photocontent"><div class="header">' + sPrintLink + sHeader + '</div>' + sContent + sScrollFooter + sMailto + sPrint + '</div> \
					</div>');
			} else if(parentList.is('.sport-gallerij')) {
				page.append('<div id="itemcontainer"><div class="header">' + sPrintLink + sHeaderName + sHeader + '</div>' + sContent + sFooter + sMailto + sPrint + '</div>');
			} else {
				page.append('<div id="itemcontainer"><div class="header">' + sPrintLink + sHeaderName + sHeader + '</div>' + sContent + sScrollFooter + sMailto + sPrint + '</div>');
			}
			
			var elmModal = $('<div id="large-picture"></div>');
			elmModal.append(page);
			
			$('body').append(elmModal);
			Mediagallery.photoSwitch(elmModal, image);
			
			return null;
	    }
	},
	
	youTubeVideo : {
	    getModalWindow: function(item, youTubeID) {
	    	modalWindow = $("<div id='itemcontainer'></div>");
	    	modalWindow.append("<div id='videoheader'>"+$(item).find(".caption").html().replace('<br>',' - ')+"</div>")
	    	modalWindow.append('<div id="videoplayer"><object width="320" height="229"><param name="movie" value="http://www.youtube.com/v/'+youTubeID+'&amp;hl=nl&amp;fs=1&amp;rel=0"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed src="http://www.youtube.com/v/'+youTubeID+'&amp;hl=nl&amp;fs=1&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="229"></object></div>')
	    	modalWindow.append("<div id='videodescription'>"+$(item).find("img").attr('alt')+"</div>")
	    	modalWindow.append("<div id='videoclose'><a href='#' onClick='javascript:$.modal.close();'>sluiten</a></div>")
			return modalWindow;
	    }
	},
    
	externalLink : {
		getModalWindow: function(item, url) {
    		modalWindow = $("<div id='externcontainer'><iframe src='"+url+"' width='480' height='480'></iframe><a class='close' href='#' onclick='javascript:$.modal.close();'><span>Sluiten</span></a></div>");
    		return modalWindow;
		}
    },
    
    getModalWindow: function(item) {
		var youTubeID = $(item).find('input[name=youtube_id]').val();
		if(youTubeID) return Mediagallery.youTubeVideo.getModalWindow(item, youTubeID);
		
		var image = $(item).find('input[name=xlarge_image]').val();
		if(image) return Mediagallery.photoGallery.getModalWindow(item, image);

		var link = $(item).find('a').attr('href');
		if(link) return Mediagallery.externalLink.getModalWindow(item, link);
    },
    
    showModal: function(item) {
    	modalWindow = Mediagallery.getModalWindow(item);
    	if(!modalWindow) return;
    	
    	$('body').append(modalWindow);
		Mediagallery.showModalWindow(modalWindow);
    },

	gallery: function(id, isSmall) {
		galleryListItems = $('#'+id+' ul li');
		// only activate gallery when there are more than 4 items

		if (galleryListItems.length > ((isSmall)? 3 : 4)) {
			$('#'+id+' ul').jcarousel();
		} else {
			$('#'+id+' ul').addClass('jcarousel-clip');
			if (galleryListItems.length <= 0) return;
		}

		//Show the indexes of the shown gallery-items
		$('#'+id+' #foto-index').html("bevat " + galleryListItems.length + " items <div style='display:none;'><a href='#' class='iframesbox'></a><a href='#' class='videosbox'></a><a href='#' class='fotosbox'></a></div>");
        $('#'+id+' ul .fotoitem').click(function (){ Mediagallery.showModal(this); }); 
        $('#'+id+' ul .fotoitem a').click(function (){ Mediagallery.showModal($(this).parent()); return false; });
    },

	buttons: function() {

		if ($(activePhotoElm).prev('li').length < 1) {
			$('div#large-picture .previous')
				.hide()
				.unbind('click');
		} else {
			$('div#large-picture .previous')
				.show()
				.unbind('click')
				.click(function() {
					Mediagallery.previousPhoto();
				});
		}
		if ($(activePhotoElm).next('li').length < 1) {
			$('div#large-picture .next')
				.hide()
				.unbind('click');
		} else {
			$('div#large-picture .next')
				.show()
				.unbind('click')
				.click(function() {
					Mediagallery.nextPhoto();
				});
		}

	}
}

// Run any/all init functions.
$(document).ready(function() {
  Mediagallery.init();
});