
var ub_proxyURL = "/userphoto/userphoto_proxy.php";
var ub_renderURL = "/userphoto/userphoto_render.php";

var photo_types = null;

// -- Login Dialog -- 

function login_show() {
	ar_stop();
	qw_show("Login to your JET Photographic Account",
			"You must have a JET Photographic account before you can upload photographs, to keep track of uploaded photographs and " +
			"to ensure any photographs you upload cannot be viewed by anyone else.<br>"+
			"If you have an existing account, please enter your e-mail address and password below, and press the &quot;Login&quot; "+
			"button. If you need to register for an account, you can do so by following the &quot;register&quot; link below"+
			"<br><br><a href='/register.php'><b>Register for an account</b></a><br><br>"+
			"<form action='/login.php?origin=/userphoto/' name='login' method='POST'>"+
			"<input style='display:none' type='submit' id='submit-button' name='submit' value='proceed'><input type='hidden' name='usertype' value='existing'>"+
			"<table border=0><tr><td>E-mail Address:</td><td><input type='text' name='email'></td></tr>"+
			"<tr><td>Password</td><td><input type='password' name='password'></td></tr></table></form>",
			"Cancel","cancel",
			"Login", "login",
			function(resp) {
				if( resp == "login") {
					document.getElementById("submit-button").click();
				}else
				 document.location.href="/index.php";
			});
}


// -- Upload Stuff -- 
var upload_executor=null;
var upload_id=null;


function upload_addfield() {

	var field = Builder.node("input", {type:'file', name:'userpic[]'} );
	field.hide();
	
	$("upload_extrafields").appendChild( field );
	
	Effect.Appear(field, {duration:0.25});
}
function upload_start() {
	
	upload_id = Math.floor( Math.random() * 10000000 );
	
	overlay_show();
	
	qw_show("Upload File", 
			"Use the fields below to select photographs to upload to your account. For a list of "+
			"acceptible image formats, and a guide on uploading large numbers of files, click "+
			"<a href='/userphoto/uploadguide.html' target='_blank'>here</a>"+
			"<hr width=75% noshade><center>"+
			"<form action='upload.php' target='upload_target' name='upload_form' method='POST' enctype='multipart/form-data'>"+
			"<input type='hidden' name='UPLOAD_IDENTIFIER' value='"+upload_id+"'>"+
			"<input type='file' name='userpic[]'>"+
			"<div id='upload_extrafields'></div><br>(<a href='#' onClick='javascript:upload_addfield();'> add extra field </a>)<br></form>"+
			"</center><hr width=75% noshade>",
			"Cancel", "cancel",
			"Upload", "upload",
			function(resp) {
				if(resp=="upload") 
					upload_submit();
				overlay_hide();
			});

}

function upload_submit() {

	// retain the overlay for the next process
	overlay_show();
	//ar_stop();
	
	// add a target IFRAME
	if( $("upload_target") == null ) document.getElementsByTagName("body").item(0).appendChild(
		Builder.node("IFRAME", {name:"upload_target",style:"display:none", id:"upload_target"} ) );
	
	// submit the form - start the upload!
	document.upload_form.submit();

	// pre-set the form before its shown
	upload_setup();
	upload_updatePanel( "Uploading...", "", "5%" );
	
	// reset the AJAX status thingy-ma-jig
	upload_executor = window.setTimeout( upload_checkStatus, 1000 );

	//show the upload progress panel
	new Effect.Appear( upload_container, { duration: 0.25, from:0.0, to:1.0} );
}

function upload_checkStatus() {
		new Ajax.Request( "/userphoto/upload.php?status="+upload_id, {
						method:'get',
						on403:login_show,
						onSuccess:function(transport,json) {
							if( upload_executor == null ) return;
							
							if( transport.responseText.length > 0 ) 
								alert( transport.responseText ); 
							upload_statusData( json );
							upload_executor = setTimeout( upload_checkStatus, 1000 );
						},
						on403:function() {
							upload_hide();
						}
					});
	
}

function upload_statusData( status ) {
	// update details
	upload_updatePanel( status['message'], status['sub_message'], status['percent'] );
	
}
function upload_hide() {
	new Effect.Fade( upload_container, {duration: 0.5, from: 1.0, to: 0.0, afterFinish:function(){upload_container.remove();}});
	overlay_hide();
}
function upload_complete() {
	window.clearTimeout( upload_executor );
	upload_executor = null;
	
	// hide everything	
	upload_hide();
	
	// refresh the browser 
	//ar_start();
	ub_refreshBrowser();
}

// -- Upload UI -- 
var upload_container,
	upload_statusDest,
	upload_subStatusDest,
	upload_progressDest;

function upload_setup() {

	// build the status panel and attach to the body
	document.getElementsByTagName("body").item(0).appendChild(
					upload_container = Builder.node('div', {id:"upload_container",style:"display:none"},
						Builder.node('div', {id:"upload_panel"}, [
							upload_statusDest = Builder.node('div', {id:"upload_status", className:"upload_largetext"}),
							upload_subStatusDest = Builder.node('div', {id:"upload_substatus", className:"upload_smalltext"}),
							Builder.node('center', {},
								Builder.node("div", {id:"upload_progressbarouter"},
									upload_progressDest = Builder.node("div",{id:"upload_progressbar"})
								)
							)]
						))
			);
	
}

function upload_updatePanel( statusMessage, subStatusMessage, percent ) {
	upload_statusDest.innerHTML = statusMessage;
	upload_subStatusDest.innerHTML = subStatusMessage;
	upload_progressDest.style.width = percent;
	upload_progressDest.innerHTML = percent;
}


// -- Auto Refreshing -- 
// use reference counter to pause (so two pauses have to be un-paused)
var ar_pause_count=0;
var ar_refresher;
function ar_start() {
	if( ar_pause_count > 0 ) ar_pause_count--;
	if( ar_pause_count == 0 ) ar_refresher = new PeriodicalExecuter( function(pe) {ub_refreshBrowser();}, 5 );
}

function ar_stop() {
	ar_pause_count++;
	if( ar_pause_count == 1 && ar_refresher != null ) {
		ar_refresher.stop();
		delete(ar_refresher);
	}
}

// -- Overlay Window -- 
var overlay_retain = 0;

function overlay_setup() {
	document.getElementsByTagName('body').item(0).appendChild(
		Builder.node("div", {id:"overlay",className:"fixed",style:"display:none;"}));

}
function overlay_show() {
	if( $("overlay") == null ) overlay_setup();
	
	overlay_retain++;
	if( overlay_retain == 1 ) {
		new Effect.Appear( $('overlay'), {duration:0.2, from: 0.0, to:0.8} );
	}
}
function overlay_hide() {
	overlay_retain--;
	if( overlay_retain == 0 ) {
		new Effect.Fade( $('overlay'), {duration:0.2, from: 0.8, to:0.0} );	
		$('overlay').remove();
	}
}

// -- Question Window Stuff --
function qw_setup() {
	document.getElementsByTagName('body').item(0).appendChild(
		Builder.node("div", {id:"qw_container",className:"fixed"},
			Builder.node("div", {id:"qw_window"}, [
				Builder.node("div", {id:"qw_largeText"}),
				Builder.node("div", {id:"qw_smallText"}),
				Builder.node("div", {id:"qw_buttonBar"}, [
					leftButton = Builder.node("div", {id:"qw_leftButton"}),
					rightButton = Builder.node("div", {id:"qw_rightButton"})
				])
			])
		));

	$("qw_container").hide();
}
function qw_cleanup() {
	if( $("qw_container") == null ) return;
	$("qw_container").remove();
}
function qw_show( largeQuestion, smallQuestion, leftButton, leftResult, rightButton, rightResult, callback ) {

	// is question window up already?
	if( $("qw_container") != null ) return;

	// setup the window
	qw_setup();
	
	// set the fields
	$('qw_largeText').innerHTML = largeQuestion;
	$('qw_smallText').innerHTML = smallQuestion;
	$('qw_leftButton').innerHTML = leftButton;
	$('qw_rightButton').innerHTML = rightButton;

	// hook up the events 
	Event.observe($("qw_leftButton"), 'click', function() { qw_hide( callback, leftResult ); });
	Event.observe($("qw_rightButton"), 'click', function() { qw_hide( callback, rightResult ); })

	Event.observe($("qw_leftButton"), 'mousemove', function(){$("qw_leftButton").addClassName("qw_buttonBar_hover");} );
	Event.observe($("qw_leftButton"), 'mouseout', function(){if($("qw_leftButton")!=null)$("qw_leftButton").removeClassName("qw_buttonBar_hover");} );
	
	Event.observe($("qw_rightButton"), 'mousemove', function(){$("qw_rightButton").addClassName("qw_buttonBar_hover");} );
	Event.observe($("qw_rightButton"), 'mouseout', function(){if($("qw_rightButton")!=null) $("qw_rightButton").removeClassName("qw_buttonBar_hover");} );
	
	// "magic" the window up
	overlay_show();
	new Effect.Appear( $('qw_container'), {duration: 0.3, from: 0.0, to: 1.0} );
}

function qw_hide(callback, callbackResult) {
	
	// make sure a window is up
	if( $("qw_container") == null ) return;
	
	// fire the callback
	callback( callbackResult );
	
	// "magic" the window away
	new Effect.Fade( 'qw_container',  {duration: 0.2, from: 1.0, to: 0.0, afterFinish:function(){qw_cleanup();}} );	
	overlay_hide();
	
}



// -- Checkbox Stuff -- 
var multiple_issetup=false;
var multiple_count = 0;
function multiple_setup() {
	var m_add, m_delete, m_deselect;
	document.getElementsByTagName('body').item(0).appendChild(
			Builder.node( "div", {id:"multiple_container"},
				Builder.node( "div", {id:"multiple_window"}, [
						Builder.node("div", {id:"multiple_itemcounter"}, "Items Selected"),
						Builder.node("div", {id:"multiple_actionbar"}, [
							"( ",
							m_delete = Builder.node( "a", {href:"#"}, "Delete All"), " | ",
							m_deselect = Builder.node( "a", {href:"#"},"Deselect All"), " ) "
						])
					])
				)
		);
	
	Event.observe(m_delete, 'click', multiple_delete);
	Event.observe(m_deselect, 'click', multiple_deselect);
	
	$("multiple_container").hide();
	multiple_issetup = true;
}
function multiple_cleanup() {
	$("multiple_container").remove();
	multiple_issetup = false;
}
function multiple_updatecount() {
	var str;
	if( multiple_count == 1 ) str = " photo";
	else str = " photos";
	$("multiple_itemcounter").innerHTML = multiple_count + str + " selected";
}
function multiple_add_photo(photo) {
	if( photo.selected == undefined ) photo.selected = false;
	if( photo.selected == true ) return;
	
	if( multiple_issetup == false ) {
		multiple_setup();
		new Effect.Appear($("multiple_container"), {duration:0.15,afterFinish:function() {new Effect.Highlight($("multiple_window"));} });
		
	}

	photo.selected = true;
	photo.el_tick.checked = true;
		
	multiple_count++;
	multiple_updatecount();

}
function multiple_remove_photo(photo) {
	if( photo.selected == undefined ) photo.selected = false;
	if( photo.selected == false ) return;
	
	photo.el_tick.checked = false;
	photo.selected = false;
	
	multiple_count--;
	multiple_updatecount();
	// was that the last one selected ?
	if( multiple_count == 0 ) new Effect.Fade($("multiple_container"),{afterFinish:multiple_cleanup, duration:0.2});
}

function multiple_deselect() {
	ub_imageData.each( function(photo) {
		if( photo==null ) return;
		multiple_remove_photo( photo );
	});
}
function multiple_delete() {
	// ask
	overlay_show();
	qw_show( "Delete "+multiple_count+" photos?", "If deleted now, the photographs will need to be re-uploaded before an order can be placed for prints.",
		"Cancel", "cancel", "Delete", "delete", function(resp) { if( resp == "delete" ) multiple_delete_commit(); } );
}
function multiple_delete_commit() {

	// build the request data
	var photos = new Array();
	ub_imageData.each( function(photo) {
		if( photo == null ) return;
		if( photo.selected == true ) photos.push( photo.id );
	});
	
	// deselect them first!!
	multiple_deselect();
	
	// send multi-delete request
	new Ajax.Request( ub_proxyURL+"?op=PhotoMultiDelete&photos="+photos.toJSON(), { method:'get', onSuccess: function(transport) { if(transport.responseText.length > 0 ) alert(transport.responseText); ub_refreshBrowser(); overlay_hide() }} );

}

function action_check( photo ) {
	if( photo.selected==null ) photo.selected = false;
	if( photo.el_tick.checked == true && photo.selected == false) multiple_add_photo(photo);
	if( photo.el_tick.checked == false && photo.selected == true ) multiple_remove_photo(photo)
}
function action_toggle_selected( photo ) {
	if( photo.selected == false || photo.selected == undefined ) multiple_add_photo( photo );
	else if( photo.selected == true ) multiple_remove_photo( photo );
}

function action_rotateCW( photo ) {new Ajax.Request( ub_proxyURL+"?op=rotate_cw&photo_id="+photo.id, { method:'get', onSuccess: function(transport,json) { ub_reloadImage(photo.id); } });}
function action_rotateCCW( photo ) {new Ajax.Request( ub_proxyURL+"?op=rotate_ccw&photo_id="+photo.id, { method:'get', onSuccess: function(transport,json) { ub_reloadImage(photo.id); } });}
function action_fliph( photo ) {new Ajax.Request( ub_proxyURL+"?op=flip_horiz&photo_id="+photo.id, { method:'get', onSuccess: function(transport,json) { ub_reloadImage(photo.id); } });}
function action_flipv( photo ) {new Ajax.Request( ub_proxyURL+"?op=flip_vert&photo_id="+photo.id, { method:'get', onSuccess: function(transport,json) { ub_reloadImage(photo.id); } });}

function action_setCategory( photo ) {new Ajax.Request( ub_proxyURL+"?op=setcategory&photo_id="+photo.id+"&category_id="+photo.el_type.value, { method:'get', onSuccess: function(transport,json) {if(transport.responseText.length>0)alert(transport.responseText); ub_reloadImage(photo.id); } });}

function action_add( photo ) {
//	qw_show( "Add photo '"+photo.name+"' to your order?", "Once an order for a photograph has been placed, it will be removed from this view, and can no longer be edited or deleted.<br>The image will be placed in your site basket, accessible from the toolbar above.", "Cancel", "cancel", "Add to order", "add", function(response) {if(response=="add") action_commit_add(photo); } );

action_commit_add(photo);
}

function action_commit_add( photo ) {

	// fire the order AJAX method and forward to the 
	new Ajax.Request( ub_proxyURL+"?op=order&photo_id="+photo.id, {method:'get', onSuccess: function(transport,redirect) {if(transport.responseText.length>0) alert(transport.responseText);window.location.href=redirect; } } );

}

function action_edit( photo ) {
	editor_show( photo );
}

function action_delete( photo ) {

	// confirm user definately wants to delete photo
	qw_show( "Delete photo '"+photo.name+"'?", "This action will completely remove the photograph from the server - it must be re-uploaded if it is to be printed.", "Cancel", "cancel", "Delete", "delete", function(response) { if(response=="delete") action_performDelete(photo.id ); } );
}
function action_performDelete(photo_id) {	
	// perform the delete and refresh the browser
	new Ajax.Request( ub_proxyURL+"?op=delete&photo_id="+photo_id, {method:'get', on403:login_show, onSuccess: function(transport,json) { ub_refreshBrowser(); } } );
}

// reference to divs for photos
var ub_imageData;
var ub_emptyText=null;

function ub_setupBrowser() {

	
	// no photos text
	if( ub_emptyText == null ) {
		ub_emptyText = Builder.node("div", {className:"ub_empty_text"});
		ub_emptyText.innerHTML = "<div class=\"ub_empty_container\"><div class=\"ub_empty_large\"> -- No Photographs -- </div><br><div class=\"ub_empty_small\">Click the <b>&quot;Add Photographs&quot;</b> button above to add photos....</div></div>";
		$(ub_emptyText).hide();
		$("ub_browser").appendChild( ub_emptyText );
		ub_emptyText.is_hidden = true;
	}
	
	// visible images data store
	ub_imageData = new Array();
	
	// start the auto-refresher
	ar_start();
	
	// do the first refresh immediately
	ub_refreshBrowser();
}

function element_createCategoryChooser( photo ) {

	// use photo_types to build the category chooser
	var options = new Array();
	
	photo.option = new Array();

	options.push( photo.default_option = Builder.node("option", {value:-1}, " -- Select -- ") );
	photo.default_option.selected = true;
	
	photo_types.each( function(type) {
		options.push( photo.option[type['id']] = Builder.node("option", {value:type['id']}, type['name']));
	});
		
	return Builder.node("select", options);
}


function ub_refreshBrowser() {
	
	// Make AJAX call for Photo list
	new Ajax.Request( ub_proxyURL+"?op=PhotosForUser", {
				method:'get',
				on403:login_show,
				onSuccess: function(transport,json) { if( transport.responseText.length > 0 ) alert(transport.responseText); ub_displayPhotos(json); }
			});
}


function ub_reloadImage( photo_id ) {
	var img = ub_imageData[photo_id].element.getElementsByTagName( "img" ).item(0);
	img.src = ub_renderURL+"?photo_id="+photo_id+"&size=tn&random="+Math.floor(Math.random()*1000);
}

function ub_createPhotoElement( newPhoto ) {

	function makeAction( photo_id, caption, callback ) {
		var el = Builder.node("a",{href:"#"}, caption);
		if( callback!=null ) Event.observe( el, 'click', function() { callback( newPhoto ); } );
		return el;
	}
	
	// construct it!
	newPhoto.element = Builder.node("div", {className:"ub_photo_display"},
			Builder.node("div", {className:"ub_photo_display_inner"}, [
				Builder.node("div", {className:"ub_photo_display_image"},
					newPhoto.el_img = Builder.node("img",{src:ub_renderURL+"?photo_id="+newPhoto.id+"&size=tn"})),
					newPhoto.el_caption = Builder.node("div", {className:"ub_photo_display_caption"},
						[
							newPhoto.el_tick = Builder.node("input",{type:'checkbox'}),
							newPhoto.el_caption_text = Builder.node("b",newPhoto.name),
							Builder.node("br"),
							Builder.node("center", [ 
								newPhoto.el_type = element_createCategoryChooser(newPhoto),
								Builder.node("br"),
								"(",
								makeAction( newPhoto.id, "click to order", action_add), " | ",
								makeAction( newPhoto.id, "delete", action_delete),
								")"
							])
						])
					])
				);

			
	// check option
	Event.observe( newPhoto.el_type, 'change', function() {action_setCategory( newPhoto ); } );
	Event.observe( newPhoto.el_img,  'click', function() {action_toggle_selected( newPhoto ); } );
	Event.observe( newPhoto.el_tick, 'click', function() {action_check( newPhoto ); } );

}

function ub_addPhoto( photo, after ) {

	var newPhoto = new Object();
	
	// setup the new photo
	newPhoto.id = photo['id'];
	newPhoto.name = photo['name'];
	newPhoto.width = photo['width'];
	newPhoto.height = photo['height'];
	newPhoto.tn_bounds = photo['tn_bounds'];
	newPhoto.screen_bounds = photo['screen_bounds'];
	newPhoto.type = photo['type'];
	
	ub_createPhotoElement(newPhoto);

	if( newPhoto.option[newPhoto.type] == undefined ) newPhoto.default_option.selected = true;
	else newPhoto.option[newPhoto.type].selected = true;

	// insert it!
	if( after != null ) after = after.nextSibling;
	$("ub_browser").insertBefore( newPhoto.element, after );

	// add to the local cache
	ub_imageData[newPhoto.id] = newPhoto;
}
function ub_assertSettings( photo, data ) {
	
	// store everything
	photo.name = data['name'];
	photo.width = data['width'];
	photo.height = data['height'];
	photo.tn_bounds = data['tn_bounds'];
	photo.screen_bounds = data['screen_bounds'];
	photo.type = data['type'];
	
	// update the label
	photo.el_caption_text.innerHTML = photo.name;

	// update the selected type
	if( photo.option[photo.type].selected == false ) {
		photo.option[photo.type].selected = true;
		new Effect.Highlight(photo.el_type);
	}
}

function ub_removePhoto( photo ) {
	// called when a removed photo is detected!
	new Effect.DropOut( photo.element, {afterFinish: function() { photo.element.remove(); ub_imageData[photo.id] = null; delete(photo); }});
}

function ub_displayPhotos( data ) {

	// is the local storage empty ?
	if( ub_imageData == null ) ub_imageData = new Array();

	// Compare incoming photos to existing photos and find additions and removals
	var additions = new Array();
	var removals = new Array();
	var lastElement = null;
	
	var photos = data['photos'];

	// set photo types if this is the first go!
	if( photo_types == null ) {
		photo_types = data['photo_types'];		
	}
	
	// find added photos
	photos.each( function(photo) {
		// try to find photo in ub_imageData
		var photoID = photo['id'];
		if( ub_imageData[photoID] == null ) {
			// photo has been added
			ub_addPhoto( photo, lastElement );
		} else {
		
			// assert the settings
			ub_assertSettings( ub_imageData[photo['id']], photo );
		}
		
		
		lastElement = ub_imageData[photoID].element;
	});

	// find removed ones
	var imageCount = 0;
	ub_imageData.each( function(image) {
		if( image == null ) return;
	
		// find this photo in photos
		var found = false;
		photos.each( function(photo){ if( photo['id'] == image.id ) found=true; } );
		if( found == false ) {
			// photo was removed
			ub_removePhoto( image );
			return;
		}
		
		// counter to see actually how many are displayed
		imageCount++;
	});
	
	// are there any photos displayed ?
	if( imageCount == 0 && ub_emptyText.is_hidden == true ) {
		setTimeout( function(){ new Effect.Appear(ub_emptyText); }, 300 );
		ub_emptyText.is_hidden = false;
	} 
	if( imageCount > 0 && ub_emptyText.is_hidden == false ) {
		ub_emptyText.hide();
		ub_emptyText.is_hidden = true;
	}


	
}


// wait for DOM to load
Event.observe(window, 'load', ub_setupBrowser);
