var commentsPublicObject;

Lightbox.prototype.getPageSize = function() { return lightBoxExtension.getPageSize(); }

Lightbox.prototype.changeImage_original = Lightbox.prototype.changeImage;
Lightbox.prototype.changeImage = function(imageNum) {
	Lightbox.prototype.changeImage_original.call(this, imageNum);
	
	var imageId = null;
	var imgIdentifier = decodeURI(this.imageArray[imageNum][0]);
	if(imgIdentifier) {
		var element = document.getElementById('lightbox|' + imgIdentifier.substr( imgIdentifier.lastIndexOf("/") + 1 ));
		
		try {
			imageId = parseInt(element.getAttribute('imgid'));
		} catch (e) {
		}
	}
	
	lightBoxExtension.postChangeImage(imageId);
}

var lightBoxExtension = {
	
	tellAFriendLocation:'portal/fi/kerro_kaverille',
	commentModuleId: 288,
	commentsOpen : false,
		
	createExtension: function(){
		jQuery('#imageDataContainer').append('<div id=\'lightboxextension\'><div id=\'lightboxextension_comments_link\'>Kommentit <span id=\'commentcount\'>(-)</span> &gt;&gt;</div><div id=\'lightboxextension_tellafriend_link\'>Kerro kaverille</div></div>');
		jQuery('#imageDataContainer').append('<div id="comments-public-view"><br/><br/><br/></div>');
		//Create Form	
		var galleryForm = '<form id=\'frm_imggallery_extension\' action=\'/'+ this.tellAFriendLocation +'\' method=\'post\'>';
		galleryForm += '<input type=\'hidden\' id=\'imgref\' name=\'imgref\' value=\'\'/>';
		galleryForm += '<input type=\'hidden\' id=\'imgsrc\' name=\'imgsrc\' value=\'\'/>';	
		galleryForm += '</form>';		
		jQuery('body').append( galleryForm );
	},
	
	getCurrentImageName: function(){
		return jQuery('#lightboxImage').attr('src');
	},
	
	getShortCurrentImageName: function(){
		var imgIdentifier = jQuery('#lightboxImage').attr('src');
		return (imgIdentifier) ? imgIdentifier.substr( imgIdentifier.lastIndexOf("/") + 1 ) : "";
	},
	
	getCurrentImageId : function() {
		var shortImgName = this.getShortCurrentImageName();
		var element = document.getElementById(decodeURI('lightbox|' + shortImgName));
		try {
			return parseInt(element.getAttribute('imgid'));
		} catch (e) {
		}
		
		return undefined;
	},
	
	redirectToTellAFriend: function(){
		var imgref = window.location.href;
		var hashIndex = imgref.indexOf("#");
		if ( hashIndex > -1 ){
			imgref = imgref.substr( 0 , hashIndex );
		}
		var shortImgName = this.getShortCurrentImageName();
		imgref += '#galleryimg=' + shortImgName;
		var imgSrc = this.getCurrentImageName();
		imgSrc = imgSrc.replace('/image/' , '/thumb/');
		
		jQuery('#imgref').val( imgref );
		jQuery('#imgsrc').val( imgSrc );
		jQuery('#frm_imggallery_extension').submit();
	},
	
	autoStartLightBox: function(){
	    setTimeout(function() {
	        if(document.location.hash && document.location.hash.indexOf('galleryimg')!=-1) {
	        	var imageName = document.location.hash.substr(12);
	        	if ( imageName ){
	        		var elemName = 'lightbox|'+imageName;
	        		if ( $(elemName) ){
	        			lightBox.start($(elemName));
	        		}
	        	}
	        }},
	        250
	    );
	},

	initCommentsPublicObject : function() {
		if (typeof (CommentsPublic) != "undefined") {
			var imageId = this.getCurrentImageId();
			if (imageId) {
				if (!commentsPublicObject) {
					commentsPublicObject = new CommentsPublic(
							this.commentModuleId, "comments-public-view",
							"imagegallery", imageId, {
								itemsPerPage :5
							});
				} else {
					commentsPublicObject.initialize(this.commentModuleId,
							"comments-public-view", "imagegallery", imageId, {
								itemsPerPage :5
							});
				}
				
				return true;
			}
		}
		return false;
	},
	
	postChangeImage: function(imageId) {
		this.clearComments();
		this.updateCommentCount(imageId);
	},
	
	handleComments: function(){
		if (!this.commentsOpen && this.initCommentsPublicObject()){
			this.commentsOpen = true;
		}else{
			this.clearComments();
			this.updateCommentCount();
		}
	},
	
	clearComments: function(){
		this.commentsOpen = false;
		jQuery('#comments-public-view').html('<br/><br/><br/>');
	},
	
	updateCommentCount : function(imageId) {
		if(!imageId) {
			imageId = this.getCurrentImageId();
		}
		
		if(imageId) {
			jQuery.ajax({
				url: "/portal/" + this.commentModuleId + "?a=shared-listComments&visible=true&namespace=imagegallery&targetId="+imageId+"&itemsPerPage=0&noRedirect=true",
				global: false,
				complete: function(data) {
					var countStr = jQuery(data.responseText).find("span.comment_count").html();
					jQuery("#commentcount").html(
							(countStr != null) ? countStr : "(0)");
				}
			});
		}
		else {
			jQuery("#commentcount").html("(-)");
		}
	},
	
	refreshOverlay: function(){
        var arrayPageSize = this.getPageSize();
        setTimeout(function() {
        	$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
        },1);
	},

    getPageSize: function() {
		var body = document.body,
	    html = document.documentElement;

		var pageHeight = Math.max( body.scrollHeight, body.offsetHeight, 
	                       html.clientHeight, html.scrollHeight, html.offsetHeight );

		var pageWidth = Math.max( body.scrollWidth, body.offsetWidth, 
                html.clientWidth, html.scrollWidth, html.offsetWidth );
		
		return [pageWidth,pageHeight];
	}
};

jQuery(document).ready(function(){
	if ( jQuery('#imageDataContainer') ){
		lightBoxExtension.createExtension();
		
		jQuery('#lightboxextension_tellafriend_link').mouseup(function(){
			lightBoxExtension.redirectToTellAFriend();	
		});

		jQuery('#lightboxextension_comments_link').mouseup(function(){
			lightBoxExtension.handleComments();	
		});
		
//		jQuery('#prevLink').mouseup(function(){
//			lightBoxExtension.clearComments();
//		});
//		
//		jQuery('#nextLink').mouseup(function(){
//			lightBoxExtension.clearComments();
//		});
		
		jQuery(window).resize( function(){
			lightBoxExtension.refreshOverlay();
		});
		
		jQuery(window).scroll( function(){
			lightBoxExtension.refreshOverlay();
		});
		
		jQuery("#comments-public-view").ajaxComplete(
				function(event, request, settings) {
					lightBoxExtension.updateCommentCount();
		});
		
		jQuery('#comments-form')
		.livequery(function(){ lightBoxExtension.refreshOverlay(); } ,
				function(){ lightBoxExtension.refreshOverlay(); } );
		
		lightBoxExtension.autoStartLightBox();
	}
});

