/**
 * Actions
 *
 * @category   Module (images)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-12-07
 */



// HELPERS

	// Create XML request
	var createXMLHttpRequest = function() {
	    var ua;
	    if(window.XMLHttpRequest) {
	    	try { ua = new XMLHttpRequest(); } catch(e) { ua = false; }
	    } else if(window.ActiveXObject) {
	    	try { ua = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { ua = false; }
	    }
	    return ua;
	};
	
	// No cache for AJAX
	var noCache = function(uri) {
		return uri.concat(/\?/.test(uri) ? "&" : "?", "noCache=", (new Date).getTime(), ".", Math.random() * 1234567);
	};
	
	// Get resized dimensions
	var proportionalResize = function(width, height, maxWidth, maxHeight) {
		if(maxWidth > width) maxWidth = width;
		if(maxHeight > height) maxHeight = height;
		var ratio = Math.min(maxWidth / width, maxHeight / height);
		return [Math.round(ratio * width), Math.round(ratio * height)];
	};

	// Hide elements
	var toggleElements = function(mode, elements) {
		for(var i = 0; i < elements.length; i++) if(elements[i]) elements[i].style.display = mode;
	};

// ACTIONS

	// Popup
    var imagesPopup = function(imageSRC) {
    	var imageFilename = imageSRC.substr(imageSRC.lastIndexOf('/') + 1);
    
    	if(typeof pagemapImages[imageFilename] != 'undefined') {
    		var popupHREF = popupPath + '?image=' + imageSRC;
    		var popupID = Math.round(1 + 1000 * (Math.random()));
    		var imageWidth = pagemapImages[imageFilename]['width'];
    		var imageHeight = pagemapImages[imageFilename]['height'];
    		
    		if(showImageProperties == 0) {
    			var dimensions = proportionalResize(imageWidth, imageHeight, screen.availWidth, screen.availHeight);
    			popupWidth = dimensions[0];
    			popupHeight = dimensions[1];
    		}
    	
    		var popupLeft = (screen.availWidth - popupWidth) / 2;
    		var popupTop = (screen.availHeight - popupHeight) / 2;
    	
    		var popupWindow = window.open(popupHREF, popupID, 'left=' + popupLeft + ', top=' + popupTop + ', width=' + popupWidth + ', height=' + popupHeight + ', resizable=no, scrollbars=yes');
    	}
    };
    
    // Show image
    var pagemapImagesPageOpen = function(imageSRC) {
    	var imageFilename = imageSRC.substr(imageSRC.lastIndexOf('/') + 1);
    	
    	if(typeof pagemapImages[imageFilename] != 'undefined') {
    		// Get elements
    		var imagesIMG = document.getElementById('images-img-' + imagesID);
    		var imagesTitle = document.getElementById('images-title-' + imagesID);
    		var imagesDescription = document.getElementById('images-description-' + imagesID);

    		var imagesThumbnails = document.getElementById('images-thumbnails-' + imagesID);

    		var imagesControls = document.getElementById('images-controls-' + imagesID);
    		var imagesNumber = document.getElementById('images-number-' + imagesID);
    		var imagesStatus = document.getElementById('images-status-' + imagesID);
    		var imagesClose = document.getElementById('images-close-' + imagesID);
    		var imagesBackward = document.getElementById('images-backward-' + imagesID);
    		var imagesForward = document.getElementById('images-forward-' + imagesID);
    		
    		// Update slideshow
    		stopSlideshow();
    		
    		// Update URL
    		document.location.hash = imageFilename;

    		// Update Controls
    		if(imagesNumber)
    			imagesNumber.innerHTML = pagemapImages[imageFilename]['number'];
    		
    		if(imagesControls) imagesControls.style.display = showControls == 1 ? 'block' : 'none';
    		if(imagesStatus) imagesStatus.style.display = 'block';
    		
    		if(imagesBackward) {
    			imagesBackward.className = pagemapImages[imageFilename]['last image'] == '' ? 'backward disabled' : 'backward';
    			imagesBackward.onclick = function() { pagemapImagesPageOpen(imagesPath + pagemapImages[imageFilename]['last image'], imagesID); return false; };
    		}
    		
    		if(imagesForward) {
    			imagesForward.className = pagemapImages[imageFilename]['next image'] == '' ? 'forward disabled' : 'forward';
    			imagesForward.onclick = function() { pagemapImagesPageOpen(imagesPath + pagemapImages[imageFilename]['next image'], imagesID); return false; };
    		}

    		if(imagesClose) {
    			imagesClose.onclick = function() {
    				stopSlideshow();
    				toggleElements('none', [imagesIMG.getElementsByTagName('img')[0], imagesControls, imagesTitle, imagesDescription]);
    				if(imagesThumbnails) imagesThumbnails.style.display = 'block';
	    			if(typeof closeComments != 'undefined') closeComments();
   					if(typeof closeEXIF != 'undefined') closeEXIF();
    			};
    		}
    		
    		// Update image
    		var width = parseInt(pagemapImages[imageFilename]['width']);
    		var height = parseInt(pagemapImages[imageFilename]['height']);
   			var dimensions = proportionalResize(width, height, maxWidth, maxHeight);
			
			if(imagesIMG) {
				imagesIMG.innerHTML = '<img onload="hideStatus(\'' + imageFilename + '\')" style="-ms-interpolation-mode: bicubic" src="' + imageSRC + '" alt="' + imageFilename + '" width="' + dimensions[0] + '" height="' + dimensions[1] + '" />';
    		}
    		
    		// Update Thumbnails
    		if(showImages == 0 && imagesThumbnails) imagesThumbnails.style.display = 'none';
    		if(imagesThumbnails) var links = imagesThumbnails.getElementsByTagName('a');
    		
    		if(links) for(var i = 0; i < links.length; i++)
		    	links[i].className = links[i].href.substr(links[i].href.lastIndexOf('/') + 1) == imageFilename ? 'active' : '';
    		
    		// Update Image Properties
    		if(showImageProperties == 1) {
    			if(imagesTitle) {
    				imagesTitle.style.display = 'block';
		    		imagesTitle.innerHTML = '';
    			}
    			
    			if(imagesDescription) {
    				imagesDescription.style.display = 'block';
		    		imagesDescription.innerHTML = '';
    			}
    			
				var XMLcontent = createXMLHttpRequest();
				XMLcontent.open('get', noCache(imagesPath + 'storage/' + imageFilename + '.xml'), true);
				
				XMLcontent.onreadystatechange = function() {
					if(XMLcontent.readyState == 4 && XMLcontent.status == 200) {
						if(XMLcontent.responseXML) {
							var fileNode = XMLcontent.responseXML.getElementsByTagName('file')[0];
							if(fileNode) showProperties(fileNode);
						}
					}
				};
				
				XMLcontent.send(null);
				
				var showProperties = function(fileNode) {
					var titleNode = fileNode.getElementsByTagName('title')[0];
					var descriptionNode = fileNode.getElementsByTagName('description')[0];
					
					if(titleNode && descriptionNode) {
						if(imagesTitle && titleNode.childNodes[0]) imagesTitle.innerHTML = '<div class="title">' + titleNode.childNodes[0].nodeValue + '</div>';
						if(imagesDescription && descriptionNode.childNodes[0]) imagesDescription.innerHTML = '<div class="description">' + descriptionNode.childNodes[0].nodeValue + '</div>';
					}
				};
    		}
    		
    		// User function on image loading
    		if(typeof onImageLoading != 'undefined') onImageLoading();

    		// Update Comments
    		commentsXMLfile = imagesPath + 'storage/' + imageFilename + '.xml';
    		if(document.getElementById('load_comments')) document.getElementById('load_comments').click();
    		if(document.getElementById('current_url')) document.getElementById('current_url').value = top.location.href;
    		
    		// EXIF
    		imagePath = imagesPath + imageFilename;
    		if(typeof loadEXIF != 'undefined') loadEXIF(imagePath);
    	}
    };
    
    // Hide loading status
    var hideStatus = function(imageFilename) {
       	if(typeof onImageLoaded != 'undefined') onImageLoaded();
       	var imagesStatus = document.getElementById('images-status-' + imagesID);
       	if(imagesStatus) imagesStatus.style.display = 'none';
		
		if(slideshow == 1 && slideshow_pause_start == 0) {
	    	slideshowNextImage = imagesPath + (pagemapImages[imageFilename]['next image'] == '' && slideshow_loop == 1 ? firstImage : pagemapImages[imageFilename]['next image']);
			slideshowInstance = setTimeout("pagemapImagesPageOpen(slideshowNextImage)", slideshowSeconds * 1000);
		}
    };
    
	// Stop running slideshow
	var stopSlideshow = function() {
	    if(typeof slideshowInstance != 'undefined') clearTimeout(slideshowInstance);
	};
	
	// Start and stop slideshow
	var slideshowToggle = function() {
		var imagesSlideshow = document.getElementById('images-slideshow-' + imagesID);
		
		if(slideshow == 0) {
			slideshow = 1;
			slideshow_pause_start = 0;
			var imageByAnchor = document.location.hash.substr(1);
	       	if(typeof pagemapImages[imageByAnchor] != 'undefined') pagemapImagesPageOpen(imagesPath + pagemapImages[imageByAnchor]['next image']);
			if(imagesSlideshow) imagesSlideshow.className = 'slideshow';
		} else {
			slideshow = 0;
			stopSlideshow();
			if(imagesSlideshow) imagesSlideshow.className = 'slideshow active';
		}
	};
    
    // Start
   	if(openImage == 'page') {
   		// Add on click action to slideshow toggle link
		var imagesSlideshow = document.getElementById('images-slideshow-' + imagesID);
		if(imagesSlideshow) imagesSlideshow.onclick = slideshowToggle;
		
   		// Pause slideshow on start
   		if(slideshow_pause_start == 1) slideshowToggle();
   		
   		// Open first image or image given by anchor
       	var imageByAnchor = document.location.hash.substr(1);
       	if(typeof pagemapImages[imageByAnchor] != 'undefined') {
       		pagemapImagesPageOpen(imagesPath + imageByAnchor);
       	} else if(startWithFullImage == 1 || slideshow == 1) {
       		pagemapImagesPageOpen(imagesPath + firstImage);
       	}
	}
