// Email obfuscator script 2.1 by Tim Williams, University of Arizona
// Random encryption key feature by Andrew Moulden, Site Engineering Ltd
// This code is freeware provided these four comment lines remain intact
// A wizard to generate this code is at http://www.jottings.com/obfuscator/
function decode() {
	coded = "MRPYFU@AnMUlOn87jM.xU3"
	key = "ZhGcbKHIy29aCgeL8Uk5dpuO1xDqmXWitn4QjNsv7JYTPSEVzf36rFRlwoABM0"
	coded = "2HcOQO7@hQBd0YQ3I8B.CdS"
	key = "6KshtPoO2pHCD0LJwkaW1S8UGBYbAdgX4yVRxf53IQjuq9rlvicTnzEN7ZFMme"
	shift=coded.length
	link=""
	for (i=0; i<coded.length; i++) {
		if (key.indexOf(coded.charAt(i))==-1) {
			ltr = coded.charAt(i)
			link += (ltr)
		}
		else {     
			ltr = (key.indexOf(coded.charAt(i))-shift+key.length) % key.length
			link += (key.charAt(ltr))
		}
	}
	return link;
}


function x( e )
{
	alert( 'x' );
}

function contactJason() {
	var mailto_link = 'mailto:'+decode()+'?subject=Hello Jason';
	win = window.open(mailto_link,'emailWindow');
	if (win && win.open &&!win.closed) win.close();
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.startsWith = function(str) {
	return (this.match("^"+str)==str) }

function viewLightbox_click() {
	id = document.getElementById('selectlightboxid').value;
	frm = document.getElementById('viewlightbox');
	frm.action = '/lightbox/' + id;
	frm.submit();
}

function writeCookie(key, value) {
	var expdate = new Date (); // pre-set to the current time and date
	expdate.setTime( expdate.getTime() + 1000 * 60 * 60 * 24 * 30 ); // add one month to it 
	document.cookie = key + '=' + value + '; expires=' + expdate.toGMTString() + '; path=/';
} 
  
function readCookie(key) {
  var ca = document.cookie.split(';');
  var nameEQ = key + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}

function lightBoxId() {
	return document.getElementById('selectlightboxid').value;
}

function test() {
	popup = $('#testdiv');
	if (!popup[ 0 ].initialised) {
		popup[ 0 ].initialised = true;
		popup.dialog();
		popup.append( '<img src="/static/photos/2009/0119/3.zip/cache/dsc_4668_popup.jpg" />' );
	};
	popup.dialog( 'open' );
}

var siteUrl = "http://" + location.host;

function body_unload() {
	if (typeof GUnload != 'undefined') { GUnload(); }
}

function print_click( e ) {
	e.preventDefault();
	control = getControlByChild( e );
	window.open( '/photo/' + control.data.id + '/print', 'print', 'width=650,height=700, scrollbars=true,titlebar=true,menubar=true,toolbar=false,location=false,status=false,resizable=true,left=200,top=200' );
}

function email_click( e ) {
	e.preventDefault();
	var target = e.target ? e.target : e.srcElement;
	if ( target.id.indexOf( 'lightbox' ) != -1 )
	{
		subject = 'Have a look at these photos I found.';
		url = siteUrl + '/lightbox/' + target.id.substr( 17 );
		body = '%0A%0AYou can view the photos here: ' + url + '%0A%0Aor the website (Jason Hawkes Photography) here: ' + siteUrl;
	}
	else
	{
		control = getControlByChild( e );
		subject = 'Have a look at this photo I found.';
		url = siteUrl + '/photo/' + control.data.id;
		body = '%0A%0AYou can view the image here: ' + url + '%0A%0Aor the website (Jason Hawkes Photography) here: ' + siteUrl;
	}
	var mailto_link = 'mailto:?subject=' + subject + '&body=' + body;
	win = window.open(mailto_link,'emailWindow');
	if (win && win.open &&!win.closed) win.close();
}

var googleMapsKeyFlintTechnology ='ABQIAAAAcwZUQgm5koFYZsMYQyZfahT4cx0G2r4zxAKS_JmI7hGcN593GBRVtxXpqBtxpdwG85zIQjzvG0BgYw';
var googleMapsKey1270018000 = "ABQIAAAAcwZUQgm5koFYZsMYQyZfahTpH3CbXHjuCVmaTc5MkkU4wO1RRhTi7EDQ7boy2zrHJ_gT1GnM5IZtjg";

var map = null;

function getLoadingHMTL() {
	return '<div style="text-align:center; padding-top: 100px;"><img src="/static/img/loading.gif" style="width:60px; height:60px;" /></div>';
}

function applyGoogleMap( lat, lon, control ) {
	if ( map == null && (GBrowserIsCompatible() ) )
	{
		map = new GMap2( document.getElementById("map"),
			{ size:		new GSize( 600, 480 )
			} );
		map.setCenter( new GLatLng( 0, 51.5333), 13 );
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
	}
 	if ( map != null )
	{
		if ( ( lat == null ) | ( lon == null ) )
		{
			$('#nomap').show();
			$('#map').hide();
		}
		else
		{
			map.clearOverlays();
			map.setCenter( new GLatLng( lat, lon ), 13 );
			var point = new GLatLng( lat, lon );
			marker = new GMarker( point,
			{	title: '[ ' + control.data.id + ' ]' + control.data.caption,
				clickable:	false,
				draggable:	false
			} );
			map.addOverlay( marker );
			$('#nomap').hide();
			$('#map').show();
		}
	}

}

function requestquote_click( e ) {
	usage = [];
	notes = '';
	q_id = [];
	a_id = [];
	$('.pricing-select').each( function(i)
		{
			q_id[i]		= this.id.substr( 1 ),
			a_id[i]		= this.value
		} );
	notes = $('#quoteNotes')[0].value;
	tids = [];
	$( '#quoteTerritories' ).children().each( function(i)
		{
			tids[i] = this.value;
		} );
	if ( tids.length == 0 )
	{
		alert( 'Please specify in which territories the image will be used.' );
		return;
	}
	ctl = $('#quoteIndustry')[0];
	industry = ctl.value;
	industry_text = ctl.options[ ctl.options.selectedIndex ].text;
	if ( industry == "0" ) {
		alert( 'Please specify which industry is being promoted.' );
		return;
	}
	start = $( '#quoteStartDate' )[0].value;
	if ( start.length == 0 )
	{
		alert( 'Please specify from when the image will be used.' );
		return;
	}
	ctl = $('#quoteDuration')[0];
	duration = ctl.value;
	duration_text = ctl.options[ ctl.options.selectedIndex ].text;
	if ( duration == "0" ) {
		alert( 'Please specify how long the image will be used.' );
		return;
	}
	control = getControlById( $( '#dialogue-photo-id' ).text() );
	$.post( '/pricing/quote',
		{	'q_id':			q_id,
			'a_id':			a_id,
			'tids':			tids,
			industry:		industry,
			industry_text:	industry_text,
			start:			start,
			duration:		duration,
			duration_text:	duration_text,
			notes:			notes,
			pid:			control.data.id
			},
		function( result, status )
		{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
			if ( control.data.id == $('#dialogue-photo-id').text() )
			{
				$('#pricing').parent().html( result.message );
			}
			control.data.pricing = result.message;
		},
		'json' );
}

function addTerritory() {
	var selectOptions = $('#quoteTerritorryChoices')[0].getElementsByTagName('option');
	var target = $('#quoteTerritories')[0];
	for (var i = 0; i < selectOptions.length; i++) {
		var opt = selectOptions[i];
		if ( opt.selected ) {
			index = -1;
			var targetOptions = target.getElementsByTagName('option');
			for (j = 0; j < targetOptions.length; j++ )
			{
				if ( targetOptions[ j ].value == opt.value )
				{
					index = j;
					break;
				}
			}
			if ( index == -1 )
			{
				newopt = new Option( opt.text, opt.value, true, true );	// [text[, value[, defaultSelected[, selected]]]])
				newopt.innerHTML = opt.text;
				target.appendChild( newopt );
				newopt.select = true;
				newopt.select = false;
			}
		}
	}
}

function removeTerritory() {
	var selectOptions = $('#quoteTerritories')[0].getElementsByTagName('option');
	for (var i = 0; i < selectOptions.length; i++) {
		var opt = selectOptions[i];
		if ( opt.selected ) {
			opt.parentNode.removeChild( opt );
			i--;
		}
	}
}

function pricing_changed( e ) {
	e.preventDefault();
	var target = e.target ? e.target : e.srcElement;
	control = getControlById( $( '#dialogue-photo-id' ).text() );
	ctl = $( '#' + target.id ).parent();
	ctl.nextAll().remove();		// Also performs unbinding
	control.data.pricing = $('#pricing').html();
	if ( target.value != 0 )
	{
		ctl.after( getLoadingHMTL() );
		$.post( '/pricing/answer',
			{	aid: target.value,
				qid: target.id.substr( 1, target.id.length - 1 ) },
			function( result, status )
			{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
				if ( status == 'success' )
				{
					if ( control.data.id == $('#dialogue-photo-id').text() )
					{
						ctl.nextAll().remove();
						jqPricing = $('#pricing');
						jqPricing.append( result.data.pricing );
						control.data.pricing = jqPricing.html();
						jqPricing_select = $('.pricing-select');
						jqPricing_select.unbind( 'change', pricing_changed );
						jqPricing_select.change( pricing_changed );
						$('#requestQuote').click( requestquote_click );
						$('#quoteStartDate').datepicker( {	mandatory: true,
															gotoCurrent: true,
															dateFormat: 'd M yy'
															} );
						$('#quoteTerritorryChoices').dblclick( addTerritory );
						$('#quoteTerritories').dblclick( removeTerritory );
						$('#addTerritory').click( addTerritory );
						$('#removeTerritory').click( removeTerritory );
					}
				}
			},
		'json' );
	}
}

function setPricing( control ) {
	$('.pricing-select').unbind( 'change', pricing_changed );
	$('#pricing').html( control.data.pricing );
	$('.pricing-select').change( pricing_changed );
	$('#requestQuote').click( requestquote_click );
}

function initPricing( html ) {
	$('.pricing-select').unbind( 'change', pricing_changed );
	$('#pricing').html( html );
	$('.pricing-select').change( pricing_changed );
	$('#requestQuote').click( requestquote_click );
}

function setKeywords( control ) {
	$('#ns_new').html( control.data.keywords );
}

function tab_photo_select( control ) {
	if ( control.data.orientation == 'L' )
	{
		$('#photo-landscape')[0].src = control.data.url;
		$('#photo-portrait').hide();
		$('#photo-landscape').show();
	}
	else
	{
		$('#photo-portrait')[0].src = control.data.url;
		$('#photo-landscape').hide();
		$('#photo-portrait').show();
	}
	$('#dialogue-photo-id').text( control.data.id );
	$('#dialogue-photo-size').text( control.data.filesize );
	$('#dialogue-photo-dimensions').text( control.data.dimensions );
}

function tab_google_select( control ) {
	applyGoogleMap( control.data.lat, control.data.lon, control );
}

function tab_search_select( control ) {
	if ( control.data.keywords )
	{
		setKeywords( control );
	}
	else
	{
		$('#ns_new').html( getLoadingHMTL() );
		$('#pricing').html( getLoadingHMTL() );
		$.post( '/popup/init',
			{	pid: control.data.id },
				function( result, status )
				{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
					if ( status == 'success' )
					{
						control.data.keywords = result.data.keywords;
						if ( control.data.id == $('#dialogue-photo-id').text() )
						{
							setKeywords( control );
							initPricing( result.data.pricing );
						}
					}
				},
			'json' );
	}
}

function tab_pricing_select( control ) {
	if ( $('#pricing')[0].childNodes.length == 0 )
	{
		$('#pricing').html( getLoadingHMTL() );
		$.post( '/popup/init',
			{	pid: control.data.id },
				function( result, status )
				{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
					if ( status == 'success' )
					{
						if ( !control.data.keywords )
						{
							control.data.keywords = result.data.keywords;
							if ( control.data.id == $('#dialogue-photo-id').text() )
							{
								setKeywords( control );
							}
						}
						if ( control.data.id == $('#dialogue-photo-id').text() )
						{
							initPricing( result.data.pricing );
						}
					}
				},
			'json' );
	}
}

function tab_select(event, ui) {
	return;
	control = popupControl;
	switch ( ui.index )
	{
		case 0:
			tab_photo_select( control );
			break;
		case 1:
			tab_google_select( control );
			break;
		case 2:
			tab_search_select( control );
			break;
		case 3:
			tab_pricing_select( control );
			break;
	}
}

function map_data( control ) {
	dlgJQ.data( 'title.dialog', '[ ' + control.data.id + ' ] ' + control.data.caption );
	//$('#dialogue-photo-id').text( control.data.id );
	//return;
	if ( control.data.orientation == 'L' )
	{
		$('#photo-landscape')[0].src = control.data.url;
		$('#photo-portrait').hide();
		$('#photo-landscape').show();
	}
	else
	{
		$('#photo-portrait')[0].src = control.data.url;
		$('#photo-landscape').hide();
		$('#photo-portrait').show();
	}
	$('#dialogue-photo-id').text( control.data.id );
	$('#dialogue-photo-size').text( control.data.filesize );
	$('#dialogue-photo-dimensions').text( control.data.dimensions );
	applyGoogleMap( control.data.lat, control.data.lon, control );
	if ( false )		//( control.data.keywords )
	{
		setKeywords( control );
		setPricing( control );
	}
	else
	{
		$('#ns_new').html( getLoadingHMTL() );
		$('#pricing').html( getLoadingHMTL() );
		$.post( '/popup/init',
			{	pid: control.data.id },
			function( result, status )
			{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
				if ( status == 'success' )
				{
					control.data.keywords = result.data.keywords;
					control.data.pricing = result.data.pricing;
					if ( control.data.id == $('#dialogue-photo-id').text() )
					{
						setKeywords( control );
						setPricing( control );
					}
				}
			},
		'json' );
	}
}

function lightbox_save( e ) {
	e.preventDefault();
	control = getControlByChild( e );
	form = document.getElementById( 'lightbox-form' );
	form.submit();
}

var popupControl = null;

function popup_click( e ) {
	e.preventDefault();
	control = getControlByChild( e );
	changed = ( popupControl != control );
	popupControl = control;
	map_data( control );
	var target = e.target ? e.target : e.srcElement;
	dlgJQ.tabs().tabs( 'select', -1 );
	switch ( target.className )
	{
		case 'thumb ui-draggable ui-droppable':
			dlgJQ.tabs().tabs( 'select', '#tab-1' );
			break;
		case 'thumb':
			dlgJQ.tabs().tabs( 'select', '#tab-1' );
			break;
		case 'icon map':
			dlgJQ.tabs().tabs( 'select', '#tab-2' );
			break;
		case 'icon search':
			dlgJQ.tabs().tabs( 'select', '#tab-3' );
			break;
		case 'icon pricing':
			if ( changed ) $( '#pricing' ).html( '' );
			dlgJQ.tabs().tabs( 'select', '#tab-4' );
			break;
	}
	dlgJQ.dialog( 'open' );
}

function select_change( e ) {
	ctl = e.target;
	ctl.enabled = false;
	ctl.disabled = true;
	lbid = e.target.value;
	pids = [];
	i = 0;
	$( '.photocontrol' ).each( function(e) {
					pids[i] = this.data.id;
					i++;
				} );
	$.post( '/lightbox/select', { lbid: lbid, photos: pids },
		function( result, status )
		{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
			if (status == 'success')
			{
				if ( result.success )
				{
					ctl.title = result.message;
					data = result.data;
					for (i = 0; i < data.length; i ++ )
					{
						iconAdd = document.getElementById( 'iconadd' + data[i].id );
						control = getControlById( data[i].id );
						control.data.added = data[i].added;
						if ( control.data.added )
						{
							iconAdd.src = "/static/img/icon-added.png";
							iconAdd.title = 'in lightbox';
						}
						else
						{
							iconAdd.src = "/static/img/icon-add.png";
							iconAdd.title = 'add to lightbox';
						}
					}
				}
			}
			else
			{
				ctl.title = 'Failed: ' + result.message;
			}
			ctl.enabled = true;
			ctl.disabled = false;
		},
		"json" );
}

function add_click(e){
	caller = this;
	if ( caller.busy ) return;
	control = getControlByChild( e );
	if ( control.data.added ) return;
	caller.busy = true;
	icon = $('#iconadd' + control.data.id )[ 0 ];
	icon.src = "/static/img/loading.gif";
	lbid = lightBoxId();
	$.post( '/lightbox/add', { pid: control.data.id, lbid : lbid },
		function( result, status ){	//   "timeout", "error", "notmodified",  "success", "parsererror" 
			if (status == 'success') {
				if ( result.success ) {
					icon.title = result.message;
					icon.src = "/static/img/icon-added.png";
					control.data.added = true;
				} else {
					icon.title = 'Add failed: ' + result.message;
					icon.src = "/static/img/icon-add.png";
				}
			}
			else {
				alert( 'ADD ERROR : ' + status + '\n\n' + result );
			}
			caller.busy = false;
		}, "json" );
}

function noadd_click(e){
	window.location = siteUrl + "/signon?next=" + window.location;
}

function newSearch_click( e ) {
	qs = '';
	$('.ns_fieldset input').each( function( check )
	{
		if ( this.checked )
		{
			qs += $('#' + this.id + '-label').text() + ',';
		}
	} );
	this.href = siteUrl + '/search?k=' + qs;
}

function getControlByChild( e ) {
	return $( '#' + e.target.id ).parents(".photocontrol")[ 0 ];
}

function getControlByChildId( e ) {
	return $( '#' + e.id ).parents(".photocontrol")[ 0 ];
}

function getControlById( id ) {
	return document.getElementById( 'control' + id );
}

function initIcons() {
	photos = $('.photo');
	photos.click( popup_click );
	icons = $( '.icon' );
	icons.filter( '.noadd' ).hover(
		function () {
			this.src = siteUrl + '/static/img/icon-add-hover.png';
		}, 
		function () {
			this.src = siteUrl + '/static/img/icon-add.png';
		}
	).click( noadd_click );
	icons.filter( '.add' ).hover(
		function () {
			control = getControlByChildId( this );
			if ( control.data.added ) {
				this.src = siteUrl + '/static/img/icon-added-hover.png';
			} else {
				this.src = siteUrl + '/static/img/icon-add-hover.png';
			}
		}, 
		function () {
			control = getControlByChildId( this );
			if ( control.data.added ) {
				this.src = siteUrl + '/static/img/icon-added.png';
			} else {
				this.src = siteUrl + '/static/img/icon-add.png';
			}
		}
	).click( add_click );
	icons.filter( '.email' ).hover(
		function () {
			this.src = siteUrl + '/static/img/icon-email-hover.png';
		}, 
		function () {
			this.src = siteUrl + '/static/img/icon-email.png';
		}
	).click( email_click );
	icons.filter( '.print' ).hover(
		function () {
			this.src = siteUrl + '/static/img/icon-print-hover.png';
		}, 
		function () {
			this.src = siteUrl + '/static/img/icon-print.png';
		}
	).click( print_click );

	icons.filter( '.map' ).hover(
		function () {
			this.src = siteUrl + '/static/img/icon-map-hover.png';
		}, 
		function () {
			this.src = siteUrl + '/static/img/icon-map.png';
		}
	).click( popup_click );
	icons.filter( '.search' ).hover(
		function () {
			this.src = siteUrl + '/static/img/icon-search-hover.png';
		}, 
		function () {
			this.src = siteUrl + '/static/img/icon-search.png';
		}
	).click( popup_click );
	icons.filter( '.pricing' ).hover(
		function () {
			this.src = siteUrl + '/static/img/icon-pricing-hover.png';
		}, 
		function () {
			this.src = siteUrl + '/static/img/icon-pricing.png';
		}
	).click( popup_click );
}

function initPhotoData() {
	photos = window.photos || [];	// Ensure variable defined, at least to empty list
	for ( i = 0; i < photos.length; i ++ )
	{
		getControlById( photos[i].id ).data = photos[i];
	}
}

function initLightboxes() {
	$( '.lbox' ).click( function( e )
		{
			var target = e.target ? e.target : e.srcElement;
			if ( target.id.length != 0 ) {
				location.href = target.id;
			}
		} );
}

function initHomepageLinks() {
	$( '#indicatelightboxes' ).click( function (e)
		{
			e.preventDefault();
			var target = e.target ? e.target : e.srcElement;
			$( '.lbox' ).fadeOut( 'fast' ).fadeIn( 'fast' );
		} );
	$( '#indicatesearchform' ).click( function (e)
		{
			e.preventDefault();
			var target = e.target ? e.target : e.srcElement;
			$( '.searchform' ).fadeOut( 'fast' ).fadeIn( 'fast', function()
					{ document.getElementById( 'searchinput' ).focus(); } );
		} );
}

function initSearchBar() {
	$( '#searchbar-title' ).hover(
		function (e) {
			var target = e.target ? e.target : e.srcElement;
			target.style.background = 'transparent url( /static/img/icon-drop-hover.png ) no-repeat scroll 985px 3px';
			target.style.backgroundColor = '#6B9AAD';
			target.style.color = '#FFFFFF';
		},
		function ( e ) {
			var target = e.target ? e.target : e.srcElement;
			target.style.background = 'transparent url( /static/img/icon-drop.png ) no-repeat scroll 985px 3px';
			target.style.backgroundColor = '#DEE7EF'; 
			target.style.color = '#555555';
		} ).click( function(e) {
			$( '#searchbar-contents' ).toggle( 'fast' );
	} );
}

function initLightboxForm() {
	$( '#lightbox-save' ).click( lightbox_save );
	$( '.lightbox-icon-intro' ).hover( function(e) {
			var target = e.target ? e.target : e.srcElement;
			if ( target.busy ) return;
			control = getControlByChildId( target );
			if (control.data.star == 1) {
				target.src = '/static/img/icon-star-active-hover.png';
			} else {
				target.src = '/static/img/icon-star-hover.png';
			}
		},
		function(e) {
			var target = e.target ? e.target : e.srcElement;
			if ( target.busy ) return;
			control = getControlByChildId( target );
			if (control.data.star == 1) {
				target.src = '/static/img/icon-star-active.png';
			} else {
				target.src = '/static/img/icon-star.png';
			}
		} ).click ( function(e) {
			var target = e.target ? e.target : e.srcElement;
			if ( target.busy ) return;
			target.busy = true;
			target.src = '/static/img/loading.gif';
			control = getControlByChildId( target );
			negstar = ( control.data.star == 1 ) ? 0 : 1;
			$.post( '/lightbox/setstar',
					{		iid : control.data.iid,
							star : negstar },
					function( result, status )
						{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
							if ( status == 'success' )
							{
								control.data.star = result.data.star;
								if ( result.data.star == 1 )
								{
									$( '#star' + control.data.iid ).attr( 'src', '/static/img/icon-star-active.png' );
								}
								else
								{
									$( '#star' + control.data.iid ).attr( 'src', '/static/img/icon-star.png' );
								}
								target.busy = false;
							}
						},
					'json' );
			} );
	$( '.lightbox-icon-delete' ).hover( function(e) {
			var target = e.target ? e.target : e.srcElement;
			if ( target.busy ) return;
			target.src = '/static/img/icon-delete-hover.png';
		},
		function(e) {
			var target = e.target ? e.target : e.srcElement;
			if ( target.busy ) return;
			target.src = '/static/img/icon-delete.png';
		} ).click( function(e) {
			var target = e.target ? e.target : e.srcElement;
			if ( target.busy ) return;
			target.busy = true;
			if ( $( '#remove-warn' )[ 0 ].checked )
			{
				ok = confirm( 'Are you sure you want to remove this photo?' );
				if ( !ok )
				{
					target.busy = false;
					return;
				}
			}
			control = getControlByChildId( target );
			target.src = '/static/img/loading.gif';
			$.post( '/lightbox/remove',
					{		lid : lightbox,
							iid : control.data.iid },
					function( result, status )
						{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
							if ( status == 'success' )
							{
								$( '#' + control.id ).remove();
							}
						},
					'json' );
			} );
	$( '#lightbox-delete' ).click( function(e) {
		e.preventDefault();
		ok = confirm( 'Are you sure you want to delete this lightbox?' );
		if ( !ok ) { return; }
		document.forms[ 'delete' ].submit();
	} );
	$( '.photo' ).children( 'img' ).draggable( { helper: 'clone'} ).droppable(
			{	accept: '.photo img',
				activeClass: 'droppable-active',
				hoverClass: 'droppable-hover',
				revert: 'invalid',
				revertDuration: 500,
				scroll: true,
				drop: function(ev, ui) {
					target = getControlByChildId( ui.element[0] );
					source = getControlByChildId( ui.draggable[0] );
					if ( source == undefined ) return;
					beforetarget = $( '#' + target.id ).prev();
					max = parseFloat( target.data.order );
					if ( beforetarget.length > 0 && beforetarget[0].className == 'photocontrol' ) {
						min = parseFloat( beforetarget[0].data.order );
					} else {
						min = minorder;
					}
					neworder = ( max + min ) / 2;
					$.post( '/lightbox/setorder',
							{		iid : source.data.iid,
									order : neworder },
							function( result, status )
								{	//   "timeout", "error", "notmodified",  "success", "parsererror" 
									if ( status == 'success' )
									{
										$( target ).before( source );
										source.data.order = result.data.neworder;
									}
								},
						'json' );
				}
			} );
}

function perpage_change( e ) {
	var target = e.target ? e.target : e.srcElement;
	url = window.location;
	qs = '';
	params = url.search.substring(1).split("&");
	page = 1;
	page_size = 12;
	for ( i=0; i<params.length; i++)
	{
		if ( params[i].startsWith( 'ps=' ) )
		{
			page_size = params[i].split( '=' )[1];
		}
		else if ( params[i].startsWith( 'p=' ) )
		{
			page = params[i].split( '=' )[1];
		}
		else
		{
			qs += params[i] + '&'; 
		}
	}
	new_page_size = target.value;
	start = ( ( page - 1 ) * page_size ) + 1;
	new_page = Math.floor( start / new_page_size ) + 1;
	newqs = 'p=' + new_page + '&ps=' + new_page_size;
	newurl = url.href.replace( url.search, '' ) + '?' + qs + newqs;
	window.location.assign( newurl );
}

var dlgCtl = null;
var dlgJQ = null;

$(document).ready(function(){
	timer.log( 'document ready' );
	initPhotoData();
	timer.log( 'initPhotoData' );
	$("#search").click(function(e){
		$("#searchform").submit();
	});
	$('#selectlightboxid').change( select_change );
	$( '#perpage' ).change( perpage_change );
	dlgJQ = $('#dialogue');
	dlgJQ.dialog( {
		bgiframe: true,
		draggable: true,
		position: [ 'center', 'center' ],
		resizable: false,
		width: 650,
		height: 700,
		stack: true,
		title: 'template popup',
		dialogClass: '',
		show: '',
		hide: '',
		buttons: { },
		autoOpen: false,
		modal: false
		} );
	$('#dialogue > ul').tabs();
	//dlgJQ.bind('tabsselect', tab_select );
	$('#photo-landscape').click( function(e) { dlgJQ.dialog( 'close' ); } );
	$('#photo-portrait').click( function(e) { dlgJQ.dialog( 'close' ); } );
	dlgCtl = dlgJQ[ 0 ];
	timer.log( 'dialogue and search form' );
	initIcons();
	timer.log( 'initIcons' );
	initLightboxes();
	timer.log( 'initLightboxes' );
	$('.ns_initiate a').click( newSearch_click );
	timer.log( 'ns_initiate' );
	initHomepageLinks();
	timer.log( 'initHomepageLinks' );
	initSearchBar();
	timer.log( 'initSearchBar' );
	if ( $( '#lightbox-ref' ).size() == 1 ) initLightboxForm();
	timer.log( 'initLightboxForm' );
	document.body.onunload = body_unload;
	$("#searchinput").autocomplete( '/findtags', 
			{
				autoFill		: true,
				//minChars		: 1,
				delay			: 100,	//400
				cacheLength		: 50,
				matchSubset		: 1,
				//matchCase		: 0,
				matchContains	: 0,	//	options.matchContains || 0
				maxItemsToShow	: 30,
				mustMatch		: 0,
				//extraParams		: {},
				width			: 160,	//0
				selectFirst		: true,		// false
				selectOnly		: true		// false
				//formatItem		: function
				//onSelectItem		: function
				//onFindValue		: function
			});
	$('.commission-thumb img').mouseover( function() {
		$('#commission-img')[0].src = this.src;
	} );
	//timer.showlog();
	/*
	$('.menus ul li').ahover({moveSpeed: 100, hoverEffect: function() {
        $(this)
            .animate({opacity: 0.5}, 750)
            .animate({opacity: 1.0}, 750)
            .dequeue();
        $(this).queue(arguments.callee);
    }});*/
});