/*
    Script: photolib.js
    Copyright: Fishnet NewMedia (c) 2003
    Create: 07/15/03
    Version: 1
    Compatibility: JavaScript 1.2
    Scripts: none
    Changes: none
    Description: 

    This script initializes and executes three different
    document event handlers.  The purpose of this script
    is to allow a user to grab, drag, and drop images in
    order to sequence the images.  The image sequence is
    stored in a hidden input field and passed to the CGI 
    script for processing.

*/

// Parse the navigator object for browser type and platform for compatibility
// Supported browsers include MSIE version 5+ and Netscape with Gecko version 1+

var useragent = navigator.userAgent;   // user agent string for the current browser.
var browser = navigator.appName;       // official name of the current browser
var platform = navigator.platform;     // platform on which the current browser is running
var product = navigator.product;       // product name of the current browser - for Netscape
var productsub = navigator.productSub; // build number of the current browser - for Netscape

var N = 0;	// Netscape
var M = 0	// MSIE

if (product == "Gecko" && Number(productsub) > 20020605){
	// Netscape with Gecko >= 1.0
	// supported browser
	N = 1;
}
else if (browser == "Microsoft Internet Explorer" && document.getElementById) {
	// MSIE version 5+
	// check platform
	if (platform.substring(0,3) == "MacPPC"){
	    // Macintosh
	    // check version
	    if(/MSIE ([0-9\.]+)/.test(useragent) && Number(RegExp.$1) >= 5.1){
	        // Mac MSIE version >= 5.1
	        // supported browser
	        M = 1;
	    }
	    else{
	        // Mac MSIE version < 5.1
	        // unsupported browser
	        M = 0;
	    }
	}
	else{
	    // Win MSIE version 5+
	    // supported browser
	    M = 1;
	}
}
else {
	// Not MSIE 5+ or Netscape with Gecko 1+
	// unsupported browser
	M = 0;
	N = 0;
}

var photos = 0;
var columns = 4;
var currentObject, oldObject;
var offsetX, offsetY;
var origX, origY;
var origPixelLeft, origPixelTop;
var currentObjectIndex;
var currentPhotoid;
var origClientX, origClientY;
var origPhotoids = new Array();
var currentPhotoids = new Array();


function setInput () {
	// passes sort order array to form input
	var sort_order = currentPhotoids.join(",");
	document.photolib.sort_order.value = sort_order;
	return true;
}

function grab(evnt) {
	// the argument "evnt" is the event object for the event
	// the event object contains properties that describe a 
	// javascript event, and is passed as an argument to an 
	// event handler when the event occurs
	if (M) {
		// create reference to the event actuator object
		var photo = window.event.srcElement;
		// ignore all events from non-sortindex elements
		if (photo.className && photo.className.indexOf("sortindex") != -1){
			// create a reference to the current photo's parent
			currentObject = photo.src == null ? null : photo.parentNode;
			if (currentObject && currentObject.style) {
				// store current photo's properties
				currentPhotoid = parseInt(photo.name.substring(5, photo.name.length));
				for (i = 0; i < photos; i++) {
					if (currentPhotoids[i] == currentPhotoid) currentObjectIndex = i; 
				}
				currentObject.style.zIndex = 10;
				offsetX = window.event.offsetX;
				offsetY = window.event.offsetY;
				origX = currentObject.style.posLeft;
				origY = currentObject.style.posTop;
				origClientX = window.event.clientX;
				origClientY = window.event.clientY;
				origPixelLeft = currentObject.style.pixelLeft;
				origPixelTop = currentObject.style.pixelTop;
				return false;
			}
		}
		
	}
	else if (N) {
		// create reference to the event actuator object
		photo = evnt.target;
		// ignore all events from non-sortindex elements
		if (photo.className && photo.className.indexOf("sortindex") != -1){
			// create a reference to the current photo's parent
			currentObject = photo.src == null ? null : photo.parentNode;
			if (currentObject && currentObject.style) {
				// store current photo's properties
				currentPhotoid = parseInt(photo.name.substring(5, photo.name.length));
				for (i = 0; i < photos; i++) {
					if (currentPhotoids[i] == currentPhotoid) currentObjectIndex = i; 
				}
				currentObject.style.zIndex = 10;
				offsetX = evnt.layerX;
				offsetY = evnt.layerY;
				origX = currentObject.style.left.replace(/px/i,"");
				origY = currentObject.style.top.replace(/px/i,"");
				origClientX = evnt.clientX;
				origClientY = evnt.clientY;
				origPixelLeft = currentObject.style.left.replace(/px/i,"");
				origPixelTop = currentObject.style.top.replace(/px/i,"");
				return false;
			}
		}
		
	}
	currentObject = null;
	return false;
}

function drag(evnt) {
	// the argument "evnt" is the event object for the event
	// the event object contains properties that describe a 
	// javascript event, and is passed as an argument to an 
	// event handler when the event occurs
	if (currentObject && currentObject.style){
		if (M) {
			// move the photo
			currentObject.style.pixelLeft = parseInt(origPixelLeft) + parseInt(window.event.clientX) - parseInt(origClientX);
			currentObject.style.pixelTop = parseInt(origPixelTop) + parseInt(window.event.clientY) - parseInt(origClientY);
		}
		else if (N) {
			// move the photo
			currentObject.style.left = parseInt(origPixelLeft) + parseInt(evnt.clientX) - parseInt(origClientX);
			currentObject.style.top = parseInt(origPixelTop) + parseInt(evnt.clientY) - parseInt(origClientY);
		}
	}
	return false;
}

function drop(evnt) {
	// the argument "evnt" is the event object for the event
	// the event object contains properties that describe a 
	// javascript event, and is passed as an argument to an 
	// event handler when the event occurs
	var newObjectNum, newObjectSeq;
	if (currentObject && currentObject.style) {
		if (M) {
			currentObject.style.zIndex = 0;
			for (var i = 0; i < photos; i++) {
				var newObject = document.getElementById("photo" + currentPhotoids[i]);
				if ((Math.abs(parseInt(newObject.style.posLeft) - parseInt(currentObject.style.posLeft)) < 30) && (Math.abs(parseInt(newObject.style.posTop) - parseInt(currentObject.style.posTop)) < 30)) {
					if (currentObject.style != newObject.style) {
						newObjectIndex = i;
						var destPixelLeft = origPixelLeft;
						var destPixelTop = origPixelTop;
						if (newObjectIndex > currentObjectIndex) {
							for (var j = currentObjectIndex + 1; j <= newObjectIndex; j++) {
								var nextDiv = document.getElementById("photo" + currentPhotoids[j]);
								tempPixelLeft = nextDiv.style.pixelLeft;
								tempPixelTop = nextDiv.style.pixelTop;
								nextDiv.style.pixelLeft = destPixelLeft;
								nextDiv.style.pixelTop = destPixelTop; 
								destPixelLeft = tempPixelLeft;
								destPixelTop = tempPixelTop;
								currentPhotoids[j-1] = currentPhotoids[j];
							} 
						} 
						else {
							for (var j = currentObjectIndex - 1; j >= newObjectIndex; j--) {
								var nextDiv = document.getElementById("photo" + currentPhotoids[j]); 
								tempPixelLeft = nextDiv.style.pixelLeft;
								tempPixelTop = nextDiv.style.pixelTop;
								nextDiv.style.pixelLeft = destPixelLeft;
								nextDiv.style.pixelTop = destPixelTop; 
								destPixelLeft = tempPixelLeft;
								destPixelTop = tempPixelTop;
								currentPhotoids[j+1] = currentPhotoids[j];
							} 
						}
						currentObject.style.pixelLeft = destPixelLeft 
						currentObject.style.pixelTop = destPixelTop;
						currentPhotoids[newObjectIndex] = currentPhotoid;
						currentObject = null;
						return false;
					}
				} 
			}
			currentObject.style.posLeft = origX;
			currentObject.style.posTop = origY;
			currentObject = null;
		}
		else if (N) {
			// place the photos
			currentObject.style.zIndex = 0;
			for (var i = 0; i < photos; i++) {
				var newObject = document.getElementById("photo" + currentPhotoids[i]);
				if ((Math.abs(parseInt(newObject.style.left.replace(/px/i,"")) - parseInt(currentObject.style.left.replace(/px/i,""))) < 30) && (Math.abs(parseInt(newObject.style.top.replace(/px/i,"")) - parseInt(currentObject.style.top.replace(/px/i,""))) < 30)) {
					if (currentObject.style != newObject.style) {
						newObjectIndex = i;
						var destPixelLeft = origPixelLeft;
						var destPixelTop = origPixelTop;
						if (newObjectIndex > currentObjectIndex) {
							for (var j = currentObjectIndex + 1; j <= newObjectIndex; j++) {
								var nextDiv = document.getElementById("photo" + currentPhotoids[j]);
								tempPixelLeft = nextDiv.style.left.replace(/px/i,"");
								tempPixelTop = nextDiv.style.top.replace(/px/i,"");
								nextDiv.style.left = destPixelLeft;
								nextDiv.style.top = destPixelTop; 
								destPixelLeft = tempPixelLeft;
								destPixelTop = tempPixelTop;
								currentPhotoids[j-1] = currentPhotoids[j];
							} 
						} 
						else {
							for (var j = currentObjectIndex - 1; j >= newObjectIndex; j--) {
								var nextDiv = document.getElementById("photo" + currentPhotoids[j]); 
								tempPixelLeft = nextDiv.style.left.replace(/px/i,"");
								tempPixelTop = nextDiv.style.top.replace(/px/i,"");
								nextDiv.style.left = destPixelLeft;
								nextDiv.style.top = destPixelTop; 
								destPixelLeft = tempPixelLeft;
								destPixelTop = tempPixelTop;
								currentPhotoids[j+1] = currentPhotoids[j];
							} 
						}
						currentObject.style.left = destPixelLeft 
						currentObject.style.top = destPixelTop;
						currentPhotoids[newObjectIndex] = currentPhotoid;
						currentObject = null;
						return false;
					}
				} 
			}
			currentObject.style.left = origX;
			currentObject.style.top = origY;
			currentObject = null;
		}
	}
	return false;
}


function init() {
	if (photos){
		if (N){ // capture all of the following events
			if (document.captureEvents) document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
		}
		
		// initialize event handlers
		document.onmousedown = grab;	// grap photo on mouse down
		document.onmousemove = drag;	// drag photo on mouse move
		document.onmouseup = drop;	// drop photo on mouse up
	}
}

var mirror = 0;
var rotation = 0;
function fix(action){
	
	// create reference to photo
	var photo = document.getElementById('photo');
	
	// set the filter attributes
	if (action == "revert"){
		mirror = 0;
		rotation = 0;
	}
	else if (action == "flip"){
		mirror = mirror ? 0 : 1;
	}
	else if (action == "right"){
		if (mirror){
			if (rotation == 0) rotation = 3;
			else rotation--;
		}
		else{
			if (rotation == 3) rotation = 0;
			else rotation++;
		}
	}
	else if (action == "left"){
		if (mirror){
			if (rotation == 3) rotation = 0;
			else rotation++;
		}
		else{
			if (rotation == 0) rotation = 3;
			else rotation--;
		}
	}
	
	// filter photo
	photo.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(mirror:' + mirror + ', rotation=' + rotation + ')';
}

function setFixes () {
	// pass filter values
	if (mirror == 1) document.photolib.flip.value = "Y";
	if (rotation == 1) document.photolib.rotate.value = "90";
	else if (rotation == 2) document.photolib.rotate.value = "180";
	else if (rotation == 3) document.photolib.rotate.value = "270";
	return true;
}

function checkFileExt(elm){
	// supported file extensions
	var extensions = new Array ('.jpg','.jpe','.jpeg'); 
	// get the image's file name
	var filename = elm.value;
	// supported image file (boolean)
	var supported = 0;
	
	if (filename){
		// a file has been selected
		var regexp = / $/;
		// remove all trailing spaces
		// from the image's file name
		while (regexp.test(filename)){
			filename = filename.substr(0,filename.length - 1);
		}
		// check the image's file extension against
		// the list of supported file extensions
		for (ext in extensions){
			var regexp = new RegExp(extensions[ext],"i");
			if (regexp.test(filename)){
				supported = 1;	// supported
				break;			// exit loop
			}
		}

		// alert user if the image's extension does
		// not match one of the supported file extensions
		if (!supported){
			var msg = "";
			msg += "You have selected an unsupported file format.\n";
			msg += "Only image files with the following extensions\n";
			msg += "can be uploaded: jpg, jpeg, jpe";
			alert(msg);
		}
	}
	
	// return supported boolean
	return supported;
}

function togglePreview(elm){
	// supported file extensions
	var extensions = new Array ('.jpg','.jpe','.jpeg');
	// get the image's file name
	var filename = elm.value;
	// supported image file (boolean)
	var supported = 0;
	
	if (filename){
		// a file has been selected
		var regexp = / $/;
		// remove all trailing spaces
		// from the image's file name
		while (regexp.test(filename)){
			filename = filename.substr(0,filename.length - 1);
		}
		// check the image's file extension against
		// the list of supported file extensions
		for (ext in extensions){
			var regexp = new RegExp(extensions[ext],"i");
			if (regexp.test(filename)){
				supported = 1;	// supported
				break;			// exit loop
			}
		}
	}
	
	// enable or disable image
	document.getElementById("preview_image").style.display = supported ? "block" : "none";
}

function previewUpload(elm){
	if (checkFileExt(elm)){
		var file = elm.value;

		// encode file name
		file = file.replace(/%/g,"%25");
		file = file.replace(/&/g,"%26");
		file = file.replace(/#/g,"%23");
		
		// add file protocol identifier
		file = "file:///" + file;
		
		// view the image
		viewImage(file);
	}
}

function previewImport(path, file){
	if (file) viewImage(path + file);
}

function viewImage(file){
    // open image in popup window
    var win = window.open("photolib_preview.cgi?file=" + file,"Preview","width=400,height=250,resizable,scrollbars");
    // set focus on the new window
    if (win) win.focus();
}

var attempt = 0;
function retryUrl(img){
	// an error occured while attempting to load img
	var imgsrc = img.src;
	
	// increment attempt
	attempt++;
	
	if (attempt == 1){
		// attempt 2
		// MSIE (mac)
		imgsrc = "file:/" + imgsrc.substring(7);
		img.src = imgsrc;
	}
	else if (attempt == 2){
		// attempt 3
		imgsrc = "file://Volumes/" + imgsrc.substring(6);
		img.src = imgsrc;
	}
	else img.onerror = null;
}

function importPhotos(script_name){
	var album_id = document.photolib.album_id.options[document.photolib.album_id.selectedIndex].value;
    // open image in popup window
    var win = window.open(script_name + "?Action=Import&album_id=" + album_id,"import","width=235,height=100");
    // set focus on the new window
    if (win) win.focus();
}

function confirmImport(script_name,photo_ct,album_id){
	if (opener){
		// opener window found
		opener.location = script_name + "?Action=Confirm&photo_ct=" + photo_ct + "&album_id=" + album_id;
		// close this window
		self.close();
	}
}
