
var search_type;
var hashCookie = new Hash.Cookie('nf');
var	user_group = hashCookie.get('ug');

Element.implement({
	// Open the preivew window
	preview: function(){
		window.open('/details/?' +search_type+ '=' 
		//	+ (search_type == 'video'? 
		//		  this.retrieve('json').VideoID
		//		: this.retrieve('json').ImageID
		// ),
			+ this.retrieve('json').itemguid,
			'',
			'toolbar=0,directories=0,width=1000,height=600,location=1,scrollbars=1'
		);
	},
	
	// Set the class based upon actual orientation
	orient: function() {
		var img = this;
		if (img.get("tag") != "img") return;
		img.addEvent('load', function(){
			img.removeClass('loading');
			set_orientation(img);
		});
		set_orientation(img);
	},
	
	// Set the src of the image based upon the JSON 'path'
	makeSrc: function(type){
		this.set(
			'src',
			path2src(type, this.retrieve('json').path )
		);
	}

});

// Logic to set class of an image based on actual orientation 
function set_orientation(img){
	if ( img.width >= img.height ){
		if (img.hasClass('result')){
			img.addClass('landscape');
			img.removeClass('portrait');
		} else {
			img.addClass('preview_landscape');
			img.removeClass('preview_portrait');
		}
	} else {
		if (img.hasClass('result')){
			img.addClass('portrait');
			img.removeClass('landscape');
		} else {
			img.addClass('preview_portrait');
			img.removeClass('preview_landscape');
		}
	}
};


var Photo = new Class({
	Implements: [Options, Events],
	
	options: {
		'target': '',
		'json': {},
		'showDelay': 1500,
		'hideDelay': 50,
		'lightbox': false,
		'size': 'thumbnail'
	},
    
	initialize: function( options ){
		this.setOptions(options);
		
		if (this.options.json.path.match(/\.m(ov|p4)$/) ){
			this.type = 'video'
		} else {
			this.type = 'image'
		}

		if (this.type == 'image' || $(document.body).hasClass('search') ){ // size=thumbnail
			this.img = new Element('img', {
				'class': 'loading',
				id: this.type=='video'? this.options.json.VideoID : this.options.json.ImageID,
				events: {
					'contextmenu': function(e){
						e.stop();
					}
				}
			});
		}
		
		// Flash video
		else {
			this.img = new Element('embed', {
				//'class': 'loading',
				flashvars: '',
				allowfullscreen: 'false',
				type: 'application/x-shockwave-flash',
				id: 'FLVScrubber2_' + this.options.json.VideoID
			});
		}
		this.img.store( 'json', this.options.json );
		this.img.makeSrc( this.options.size );
		var self = this;
		this.img.addEvent('load', function(){
			self.img.removeClass('loading');
			self.img.addClass('result');
			self.img.orient();
		});
	},
	
	formatDate: function(d){
		if (!d) return '';
		var regex = new RegExp("^(\\d{4})(\\d\\d)(\\d\\d)$");
		var results = regex.exec(d);
		if (results==null) return '';
		return results[1] +'-'+ results[2] +'-'+ results[3];
	},
	
	setSearchEvents: function(){
		var self = this;
		this.img.addEvents({
			click: function(e) { e.stop(); self.img.preview(); },
			mouseenter: function(e) {
				$clear(self.img.timer);
				if (self.img.hover) self.img.hover.dispose();
				self.img.timer = (function(e2) {
					var top = e.page.y - e.target.getStyle('height').toInt();
					if (top < 120) top = 120;
					self.img.hover = new Element('img',{
						src: path2src('preview', e.target.retrieve('json').path ),
						//e.target.src,
						styles: {
							display: 'none',
							position: 'absolute',
							top: top,
							left: e.page.x - e.target.getStyle('width').toInt()
						}
					});
					self.img.hover.delayTimer = self.img.hover.dispose.delay(5000, self.img.hover);
					self.img.hover.addEvents({
						load: function(){
							self.img.hover.orient();
							self.img.hover.setStyle('display', 'block');
						},
						mouseleave: function() {
							$clear(self.img.timer);
							self.img.hover.dispose();
						},
						click: function(e) { self.img.preview(); }
					});
					self.img.hover.inject($(document.body));
				}).delay(self.options.showDelay, this);
			},
			
			mouseleave: function() {
				$clear(self.img.timer);
			}
		});
	},
	
	add2page: function(){
		var json = this.img.retrieve('json');
		var page_class = $(document.body).getProperty('class'); 
		var div = new Element('div', {'class':'image_container'});
		var hashCookieVM;
		
		if (page_class=='search'){
			hashCookieVM = hashCookie.get('vm');
			if (hashCookieVM == '0d'){
				div.setStyle('width','auto');
			}
			if (hashCookieVM == '1d'){
				div.setStyle('width','auto');
			}
			else if (hashCookieVM == '1pr'){
				div.setStyle('width','100%');
			}
			else if (hashCookieVM == '2pr'){
				div.setStyle('width','47%');
			}
		}
		
		div.adopt( this.img );
		
		if (page_class=='search'){
			div.adopt( new Element('p', {
				'class':'id',
				text: json.ImageID? json.ImageID : json.VideoID
			}) );
		}
		
		div.adopt(  new Element('div', {id: 'image_download_links', 'class': 'image_download_links'}) );
		var list = new Element('div', {id: 'image_details', 'class': 'image_details'});
		
		if (page_class=='search'){
			if (hashCookieVM == '0d'){
				list.removeClass('minimal');
				list.setStyle('display','none');
			} 
			else if (hashCookieVM == '1d'){
				list.removeClass('minimal');
				list.setStyle('display','none');
			} 
			else if (hashCookieVM == '1pr'){
				list.removeClass('minimal');
				list.setStyle('display','block');
			}
			else if (hashCookieVM == '2pr'){
				list.removeClass('minimal');
				list.setStyle('display','block');
			}
		}
			
		var headline = json.headline? json.headline : json.title;
		if (headline && headline.length > 1)
			new Element('div', { 'class': 'iptc', html:
				'<h4>' + headline + '</h4>'
			}).inject( list );

		var caption = json.caption? json.caption : json.comment;
		if (caption){
			json.caption = caption.replace(/(,\s*, \s*)+/g, ", ");
			json.caption = caption.replace(/(,\S)/g, ", $1");
			new Element('p', { 'class': 'iptc', html: caption  }).inject( list );
		}
		
		new Element('hr', { 'class': 'iptc' }).inject( list );

		if (json.location || json.date)
			new Element('p', { 'class': 'iptc', html:
				(json.location? ' <b>'+json.location+'</b>' : '')
				+ 
				(json.date? ' <b>Date:</b>'+ this.formatDate( json.date ) +'</b>' : '')
			}).inject( list );

		var ID, type;
		if (json.ImageID){
			ID = json.ImageID;
			type = 'Image';
		} else {
			ID = json.VideoID;
			type = 'Video';
		}
		new Element('p', { 'class': 'iptc', html:''
			+'<b class="ImageID">' +type+ ' ID: ' +ID+ '</b> '
			+'<span class="hideable">'
			+(json.filesize && json.filesize>0? '<br/><b>Size</b>: ' +parseInt(json.filesize/1024)+' kb'  : '')
			+(json.width && json.height? ' - '+json.width+' x '+json.height : '')
			+'</span>'
		}).inject( list );
		
		if ( user_group == 'admin'){
			new Element('p', { 'class': 'iptc', html:''
				+'<p>Path:'+json.path+'</p>'
			}).inject( list );	
		}
		
		if (json.VideoID){
			new Element('p', { 'class': 'iptc', html:''
				+'<span class="hideable details">'
				+'Duration: ' +json.duration+'. '
				+'Format: ' +json.formatProfile+', '
				+json.format+'. '
				+'<br/>'
				+'<b>Video</b> bitrate: '+json.videobitrate+'. '
				+'Resolution: '+json.videoresolution+'. '
				+'<br/>'
				+'<b>Audio</b> bitrate: '+json.audiobitrate+'. '
				+'Resolution: '+json.audioresolution+'. '
				+'Channels: '+json.audiochannels+'. '
				+'Sample rate: '+json.audiosamplerate +'.'
				+'</span>'
			}).inject( list );
		}
		
		if (page_class=='search' ){
			var a = new Element('a', {text: 'Add to lightbox'} );
			a.inject( 
				new Element('p', {'class': 'search_add2lightbox'} ).inject( list )
			);
			a.addEvent('mousedown', function(){
				new Request.JSON({
					url: '/cgi-bin/lightbox.cgi/add',
					method: 'get',
					data: { itemguid: json.itemguid, path: json.path },
					onSuccess: function(){
						div.dispose();
					},
					onError: function(r){
						throw ('Error getting lightbox.cgi/add - ' + r.responseText);	
					}
				}).send();
			});
		}
		
		if (page_class=='lightbox'  
			|| (page_class=='details' && json.VideoID) 
			|| page_class=='search' 
		) {
			if (json.itemguid){
				render_download_links( 
					json.path,
					list, 
					json.itemguid, 
					json.ImageID? 'image' : 'video', 
					path2src('preview', json.path),
					path2src('full', json.path)
				);
			}
		}
		list.inject(div);
		div.inject( this.options.target );	
	}
});



var NorthFoto = new Class({
	Implements: [Options],

	options: {
		msg: '',
		suggestions: '',
		results: ''
	},

    initialize: function( options ){
		this.setOptions(options);
		this.search_attempts = 0;
		this.submitbutton = $('submitbutton');
		this.lightbox = $('cart');
		this.q = $("q");
		this.results_page = 1;
		this.re = /q=([^&]*)/g;
		this.q = $('q');
		this.options_div = $('options');
		this.hashCookie = hashCookie;// was member, now global
		this.searching_in = $('searching_in');
		
		// When a new search is made, make sure it gets page one
		if (document.forms['searchform'])
			var sf = $('searchform');
			if (typeof sf != 'undefined' ) sf.addEvent('submit', function(){
				sf.page.value = 1;
			});
		
		// For date search
		this.search_age = '';
		var df = '%Y%m%d';
		var now = new Date();
		this.nowf = now.format(df);
		this.ages = [
			{ label: 'Any age', value: ''},
			{ label: '24 hours',	value: now.decrement('day').format(df)   },
			{ label: '3 days',		value: now.decrement('day',3).format(df)   },
			{ label: '1 week',		value: now.decrement('week').format(df)   },
			{ label: '1 month',		value: now.decrement('month').format(df)   },
			{ label: '3 month',		value: now.decrement('month',3).format(df)   },
			{ label: '6 months',	value: now.decrement('month',6).format(df)   },
			{ label: '1 year',		value: now.decrement('year').format(df) }
		];
	},
	
	populate_age: function(el){
		for (var i=0; i < this.ages.length; i++){
			el.appendChild( 
				new Element(
					'option', 
					{'value' : this.ages[i].value }
				).appendText( this.ages[i].label )
			);
		}
	},
	

	set_searching_in: function(){
		var msg = '', groupname = "";
		var groups_seen = {};
		var groups_checked = {};
		var all_checked = [];
		var toggleAll = {};
		var boxes = $$('input[type=checkbox]');
		var name2title = {};
		
		boxes.each( function(i) {
			if (i.disabled){}
			// Is a toggleGroup check box?
			else if (i.id.indexOf('toggle')==0){
				groupname = i.id.substring(6).toLowerCase();
				toggleAll[groupname] = i.id;
				if (i.checked) all_checked.push( groupname );
				groups_seen[groupname] = [];
				groups_checked[groupname] = [];
			}
			else if ( i.hasClass(groupname) ){
				groups_seen[groupname] ++; 
				if (i.checked) {
					groups_checked[groupname].push( i.name );
					name2title[ i.name ] = i.title;
				}
			}
		});
		
		Object.keys(groups_seen).each( function(i){
			// Should toggleXXX be set?
			if ( groups_seen[i] == groups_checked[i].length ){
				$( toggleAll[i] ).checked = true;
				msg += ', all '+i;
			} else {
				$( toggleAll[i] ).checked = false;
				groups_checked[i].each( function(j){
					// msg += ', '+j;	
					msg += ', '+ name2title[j]; 
				});
			}
		});
		
		if (!msg) msg = '  available ' + search_type ;

		var providers = $('provider').getSelected();
		var done_any = false;
		if (providers) msg += '; libraries: ';
		providers.each( function(i){
			if (! i.value && !done_any) {
				done_any = true;
				msg += ' any, '; 
			}
			else if (i.value.length) msg += i.value + ', ';	
		});
		if (providers) msg = msg.substring(0, msg.length-2);

		if (msg){
			msg = msg.substring(1) + '.';
			this.searching_in.set('text', 'Searching in: '+msg);
			this.searching_in.setStyle('display','block');	
		} else {
			this.searching_in.setStyle('display','none');	
		}
		
		return msg;
	}, 
	
	set_form_from_qs: function(){
		var self = this;
    	var qs = $get();
    	
		var el = $$(document.forms['searchform'].search_what);
    	
    	for (var key in qs){
    		var el = $(key);
    		el = $(document.forms['searchform'][key]);
    		
    		if (el==null) { // Radio
    			var el = $$(document.forms['searchform'][key]);
				if (el.get('type')[0] == 'radio'){
					el.each( function(i){
						if (i.value == qs[key]) i.set('checked', true);
					});
				}
			}
    		
    		if (el) {
    			var t = el.get('type');
    			var val = unescape( qs[key] ).replace(/\++/g, ' ');
    			switch(t){
    				case 'checkbox': 
    					el.checked = true; 
    					break;
    				case 'select-one':
    					$(key).set('value', val );
    					break;
    				case 'select-multiple':
    					var v = (typeof qs[key] == 'object')?
							  qs[key]
							: [ qs[key] ];
						v.each( function(i){
							$(key).set('value', i );
						});
    					break;
    				case 'hidden':
    				case 'text': 
    					var v = (typeof qs[key] == 'object')?
    					  qs[key].join(' ')
    					: qs[key];
						el.value = unescape( v ).replace(/\++/g, ' '); 
    					break;
    			}
    		}
		}
		if (location.href.indexOf('search_what=video') > -1){
			// $('search_what').options[1].selected = true;
			$('search_what_video').set('checked', true);
			$('search_what_images').set('chekced', false);
			search_type = 'video';
		} else {
			// $('search_what').options[0].selected = true;
			$('search_what_video').set('checked', false);
			$('search_what_images').set('chekced', true);
			search_type = 'images';
		}
    },
	
	populate_lightbox: function(){
		var self = this;
		new Request.JSON({
			url: '/cgi-bin/lightbox.cgi/show',
			method: 'get',
			onSuccess: function(json, txt){
				for (var i=0; i < json.images.length; i ++){
					var img = new Element('img', {
						src: path2src('thumbnail', json.images[i].path),
						events: {
							click: function(e){ 
								e.stop();
								document.location = '/lightbox';	
							}
						}
					});
					img.inject( self.lightbox );
				}
			},
			onFailure: function(r){ throw( 'Error getting lightbox.cgi/show: '+r.responseText ); }
		}).send();

		if (self.hashCookie.get('lb')==1){
			self.options_div.setStyle('display', 'none');
			self.lightbox.setStyle('display', 'block');	
		} else {
			self.options_div.setStyle('display', 'block');
			self.lightbox.setStyle('display', 'none');	
		}
	},
	
	remove_spinner: function(){
		if ($('mainSpinner')) $('mainSpinner').dispose();
	},

	
	page2search_qs: function ( qs ){		
		var eng = '';
		var qs = '';
		var url = '';
		var q = '';

		if (qs) {
			url += qs;
		}
		// Searching for an ImageID means we ignore everything else
		else if (document.forms['searchform'].ImageID.value){
			var v = document.forms['searchform'].ImageID.value;
			v = v.replace(/^(tk3s|tn|prv)_/i, '');
			v = v.replace(/\.jpg$/i, '');
			v = trim(v);
			document.forms['searchform'].ImageID.value = v;
			url = url + 'query='
			+ (search_type == 'video'? 'Video':'Image')
			+ 'ID:' + v;
			eng = (search_type == 'video')? 'Video' : 'Image';
			eng += ' ID ' + v;
		}
		
		else {
			var doingEd = false;
			var doingCreative = false;
			$$('.editorial').each( function(i){
				if ( i.checked ) {
					doingEd = true;
					q += 'keywords:'+i.name+' OR ';
				}
			});
			$$('.creative').each( function(i){
				if ( i.checked ) {
					doingCreative = true;
					q += 'keywords:'+i.name+' OR ';
				}
			});
			if (q != '') q = '(' + q.substring(0, q.length - 4) + ')'
	
			if (document.forms['searchform'].age.value){
				if (q != '') q += ' AND ';
				q += 'date:[' + document.forms['searchform'].age.value +' TO '+this.nowf+']';
			}
			
			if (document.forms['searchform'].provider.value){
				if (q != '') q += ' AND ';
				q += 'directorypath:' + document.forms['searchform'].provider.value;
			}
			
			var edkws = $('edkws');
			var kws = $('kws');
			if (q == '' && this.q.value == ''){
				if (edkws.value != ''){
					edkws.value = trim( edkws.value );
					q += 'keywords:("'+edkws.value+'" AND NOT stockshot)';
					eng += 'editorial keywords "'+edkws.value+'"';
				}
				
				else {
					if (kws.value != ''){
						kws.value = trim( kws.value );
						q += 'keywords:("' + kws.value.split(/\s+/).join('" AND "') + '")';
						// alert(q);
						eng += 'keywords "' + kws.value.split(/\s+/).join('", "') ;
						eng += '"';
					}
				}
			}
			else {
				edkws.value = ''; // XXX
				kws.value = ''; // XXX
			}

			if (this.q.value){
				q = trim(q);
				this.q.value = trim( this.q.value );
				if (q != '') q += ' AND ';
				// else eng = '“' + this.q.value + '”';
				else eng = '' + this.q.value + '';
				// q += '(caption:' + this.q.value + ' OR headline:' + this.q.value + ' OR keywords:' + this.q.value + ')'
				var quote = (this.q.value.indexOf(' ')>-1)? '"' : '';
				var terms = '(' + this.q.value.split(/\s+/).join(' AND ') +')';
				q += '('
					+ (!doingCreative? ('headline:' + terms + ' OR ') : '')
					+ ' keywords:' + terms
					+ ' OR caption:' + terms
					+ ')'
			}
			if (! document.forms['searchform'].page.value)
				document.forms['searchform'].page.value = 1; // second page
			q += '&page=' + document.forms['searchform'].page.value;
		
			url = url + 'query=' + q;
		}
		
		// Convert for video search:
		if ( search_type == 'video' ){
			// q = q.replace(/caption:/, 'comment:');
			q = q.replace(/headline:/, 'title:');
			q = q.replace(/keywords:/, 'copyright:');
			// url = url.replace(/caption:/, 'comment:');
			url = url.replace(/headline:/, 'title:');
			url = url.replace(/keywords:/, 'copyright:');
		}

		if (!eng) eng = q.replace(/&?page=\d+&?/, '');
		return [url, eng, q];
	},
	
	
    search: function( qs ){ 
    	// qs arg may be 'search for more results'
		var self = this;
		var eng = "";
		var q = '';
		
		var url = search_type == 'video'?
			'/cgi-bin/searchproxy_video.cgi?'
		:	'/cgi-bin/searchproxy.cgi?';
		if (qs){
			url += qs;
		} else {
			var url_eng = this.page2search_qs( qs );
			url += url_eng[0];
			eng = url_eng[1];
			q = url_eng[2];
		}
		
		if (self.more) {
			self.more.disabled = true;
			self.more.set('text','Please wait...');
		}
		// No terms
		else if ((!q || q.match(/^&?page=\d+&?$/)) && !eng) {
			self.remove_spinner();
			q = '';
			// No terms and welcome page - no search
			if (location.search == '?__WELCOME__') return;
		}

		self.submitbutton.disabled = true;
		self.q.disabled = true;
		var sf = $('searched_for');
		new Request.JSON({
			method: 'get',
			url: url,
			onComplete: function(){
				self.remove_spinner();
				self.submitbutton.disabled = false;
				self.q.disabled = false;
				if (self.more) self.more.disabled = false;
			},
			onFailure: function(r){ 
				self.search_attempts ++;
				// Used when Tomcat was restarting
				// if (self.search_attempts < 3) {
				//	self.options.msg.innerHTML = "Sorry for the delay: please wait ("+self.search_attempts+")... <!--"+ self.search_attempts+") Error from server: "+r.responseText +' '+url+' -->';
				//	setTimeout( function(){ self.search() },1000);
				// } else {
					self.options.msg.innerHTML = "Error from server: "+r.responseText;
				// }
			},
			onSuccess: function(json, txt) {
				self.options.msg.innerHTML = '';
				document.forms['searchform'].ImageID.value = '';
				if (json.images && json.images.length > 0){
					
					for (var i=0; i < json.images.length; i++ ){
						var p = new Photo({
							json: json.images[i],
							target: self.options.results
						});
						// console.log ( p.img.src );
						p.setSearchEvents();
						p.add2page();
					}
					
					// Event delegation XXX
					var t = json.total_hits? json.total_hits : json.images.length;
					eng = eng? eng : '';
					if (eng) {
						eng = ' for ' + eng;
						eng = eng.replace('directorypath','provider');
					}
					if (eng) 
						eng = ' result'+(t==1?'':'s') + ' '+eng;
					else eng = ' images available for you to search';
					
					sf.set('text', addCommas(t) + eng );
					
					// Page links
					self.set_page_links( json );
					
					// More
					if (json.more){
						self.more = new Element('button', {
							type: 'button',
							id: 'more',
							text: 'Show the next page of results'
						}).inject( 'get_more' );
						
						self.more.addEvent('click', function(){
							$('get_more').empty();
							self.show_next_page( json.more );
						});
					}
				} 
				else {
					sf.set('text', "No results for your search" + (eng? ', '+eng : ', '+q));
					// Get a suggestion
					if (document.forms['searchform'].q.value)
					new Request.JSON({
						method: 'get',
						url: '/cgi-bin/suggest.cgi/' + escape(document.forms['searchform'].q.value),
						onComplete: function(){ self.remove_spinner() },
						onFailure: function(r){  throw( 'Error from suggest.cgi: '+r.responseText); },
						onSuccess: function(json, txt) {
							if (!json.ResultSet) return;
							var link = unescape($get("?")).replace(/\++/g, ' ');
							link = link.replace( document.forms['searchform'].q.value, json.ResultSet.Result );
							sf.innerHTML += "<p>Did you mean <a href='/search/?"+link+"'>"+json.ResultSet.Result+"</a>?</p>";
						}
					}).send();			
				}
			}
		}).send();

		return this;
    },
    
    
	show_next_page: function( uri ){
		if (! document.forms['searchform'].page.value){
			document.forms['searchform'].page.value = 1; // second page
		} else {
			document.forms['searchform'].page.value	++;
		}
		new Element('span', {
			html: '<br/>Page ' + (parseInt(document.forms['searchform'].page.value) ) + ':',
			'class': 'result inpage_page_number'
		}).inject( this.options.results );
		this.search(  uri );
	},
    
    set_page_links: function(json){
 		this.page_links = new Element('div', {
			id: 'page_links'
		}).inject( 'get_more' ); 
		
		var from = json.this_page - 5;
		if (from < 1) from = 1;
		
		var to   = from + 9;
		if (to > json.total_pages) to = json.total_pages;
		
		new Element('span',{text:'Jump to page', 'class':'light'}).inject( this.page_links );
		
		if (from > 1){
			 this.search_page_link(1).inject( this.page_links );
			 new Element('span',{text:'...'}).inject( this.page_links );
		}
		
		for (var i=from; i<=to; i++){
			var el = document.forms['searchform'].page.value != i?
					 this.search_page_link(i)
				 :	 new Element('span', { text: i, 'class':'active' } );
			el.inject( this.page_links );
		}

		if (to < json.total_pages){
			 new Element('span',{text:'...'}).inject( this.page_links );
			 this.search_page_link( json.total_pages ).inject( this.page_links );
		}
    },

    search_page_link: function(i){ 
    	return new Element('a', {
			href: '#',
			alt: i,
			text: i>999? addCommas(i) : i,
			events: {
				'click': function(e){
					document.forms['searchform'].page.value = 
						parseInt( e.target.getAttribute('alt')) ;
					document.forms['searchform'].removeEvent('submit'); // do not reset page number
					document.forms['searchform'].submit();
				}
			}
		});
	},
    
   	open_help: function(){
		window.open('/help#advanced_search',
			'',
			'toolbar=0,directories=0,width=1000,height=600,location=1'
		);
	},

	open_rss: function(){
		var delimit = '-/-/-/-';
		var qs, eng, q;
		var url ='';
		var url_eng = this.page2search_qs( qs );
		url += url_eng[0];
		eng = url_eng[1];
		q = url_eng[2];
		if (!eng) eng = q;
		var search_in = this.set_searching_in();
		if (search_in) eng += ' in ' + search_in;
		
		window.open('/rss?' + url + delimit + location.search + delimit + escape(eng) + delimit + '.rss',
			'',
			'toolbar=1,resizable=1,directories=0,location=1,width=600,height=250,scrollbars=1'
		);
	}
});






/*
Function: $get
	This function provides access to the "get" variable scope + the element anchor
Version: 1.4 - x10d by Lee for multiple values of a parameter
Arguments:
	key - string; optional; the parameter key to search for in the url's query string (can also be "#" for the element anchor)
	url - url; optional; the url to check for "key" in, location.href is default

*/

function $get(key,url){
	if(arguments.length < 2) url =location.href;
	if(arguments.length > 0 && key != ""){
		var regex;
		if(key == "#"){
			regex = new RegExp("[#]([^$]*)");
		} else if(key == "?"){
			regex = new RegExp("[?]([^#$]*)");
		} else {
			regex = new RegExp("[?&]"+key+"=([^&#]*)");
		}
		var results = regex.exec(url);
		return (results == null )? "" : results[1];
	} else {
		url = url.split("?");
		var results = {};
			if(url.length > 1){
				url = url[1].split("#");
				if(url.length > 1) results["hash"] = url[1];
				url[0].split("&").each(function(item,index){
					item = item.split("=");
					if (! results[item[0]]) results[item[0]] = item[1]
					else {
						if (typeof results[item[0]] == 'string'){
							results[item[0]] = [ results[item[0]], item[1] ];
						} else {
							results[item[0]].push( item[1] );
						}
					}
				});
			}
		return results;
	}
}


function string2searchterm( fieldname, input ){
	var rv = '', r;
	var bits = new Array();
	var re = new RegExp("(\"[^\"]+\")", 'g');
	while ( r = re.exec(input) ){
		bits.push( r[1] );
	}
	if (bits.length) rv += ' ('+fieldname +":"+ bits.join(' AND '+fieldname+':') +') ';
	
	input = input.replace( re, '' );
	input = input.replace( /[^\w'-]+/g, ' ' );
	input = input.replace( /^\s+/g, '' );
	input = input.replace( /\s+$/g, '' );
	
	if (input.length){
		if (bits.length) rv+= ' AND ';
		rv += '('+fieldname +":"+ input.split(/\s+/).join(' AND '+fieldname+':') +')';
	}
	return rv;
}


function print_preview( src ){
	var w = window.open( 
		src,
		'' // , 'toolbar=1,directories=0,width=1000,height=700,location=0,scrollbars=auto'
	)
    w.onload = function(){ 
    	setTimeout( function(){ w.print() },2000);
    };
    return false;
}

function download_img( src ){
	window.open( 
		'/cgi-bin/download_jpeg.cgi?'+src,
		'',
		'toolbar=1,directories=0,width=1000,height=600,location=0'
	);
}

function path2src(size, path){
	var src = path;
	src = src.replace(/\\+/g,'/');
	src = src.replace(/^D:\/+archive/i,'/archive1');
	src = src.replace(/^\/+nf-webserver2\/+www2-archive\/+archive/i,'/archive2');
	src = escape(src);

	if (!src.match(/\.m(ov|p4)$/) ){
		var r = '';
		if (size=='thumbnail'){
			r = 'tn_';
		}
		else if (size=='preview'){
			r = 'prv_';
			src += '.prv';
		}
		else if (size=='full'){
			r = 'tk3s_';
		}
		src = src.replace(/\/tk3s_/, '/'+r);
	}
	else {
		var lightbox =  $(document.body).hasClass('lightbox') ? true : false;
		var ext = '';
		if (size=='preview' || lightbox) {
			var prv = src;
			prv = prv.replace(/.{3}$/, 'jpg');
			if ( $(document.body).hasClass('details') ) prv = '';
			src = '/details/FLVScrubber2.swf?bufferTime=3&previewImage='+prv+'&startAt=0&autoStart='+(!lightbox)+'&credit=Northfoto&file=' + src;
			ext = 'flv';
		}
		else if (size=='thumbnail'){
			ext = 'jpg';
		}
		if (ext) src = src.replace(/.{3}$/, ext);
	}
	
	return src;
}

function path2catalogue( path ){
	var reCat = new RegExp( /[\\\/]+archive[\\\/]+([^\\/]+)/ );
	var reRes = reCat.exec( path );
	return reRes[1];
}

var download_links = 0;
var cats = {};
function render_download_links( path, into, ID, type, preview_src, full_src ){
	download_links ++;
	var hires_html;
	var html = 	'<h5>'+(type=='video'? 'Video' : 'Image')+' ID: '+ID+'</h5>';
	if ($(document.body).hasClass('lightbox')){
		html += '<p class="remove_from_lightbox"><a class="remove_from_lightbox" href="#" onClick="remove_from_lightbox(\''+ID+'\')">Remove from lightbox</a></p>'
	} 
	else if ($(document.body).hasClass('search')) {
	//	html += '<p class="add2lightbox"><a class="add2lightbox" href="#" onClick="nf.add2lightbox()">Add to lightbox</a></p>'
	}
	else {
		html += '<p class="add2lightbox"><a class="add2lightbox" href="#" onClick="add2lightbox()">Add to lightbox</a></p>'
	}
	
	if (preview_src.match(/flv$/) ){
		// hires_html = '<a href="'+full_src+'" class="hires_dl">Download</a> the hi-res video';
		hires_html = '<a href="/cgi-bin/download_video.cgi?'+full_src+'" class="hires_dl">Download</a> the hi-res video'
	}
	else {
		hires_html = '<a href="/cgi-bin/download_jpeg.cgi?'+full_src+'" class="hires_dl">Download</a> the hi-res image';

		if (! $(document.body).hasClass('search')) {
			html += '<p><a href="/cgi-bin/download_jpeg.cgi?'+preview_src+'" class="preview">Download</a> this preview image</p>';
			html += '<p><a class="print_preview" href="#" onClick="print_preview(\'' +preview_src+ '\')">Print</a> this preview</p>';
		}
	}
	
	var div = new Element('div', { 
		'class': 'dl_links',
		id: 'dl_links_'+download_links,
		html: html
	});
	
	var cat = path2catalogue( path );
	
	if (!cats[cat]){
		new Request.JSON({
			url: '/cgi-bin/userSeesCat.cgi?' + cat,
			method: 'get',
			onFailure: function(r){ throw( 'Can not get cat access for user '+r.responseText) },
			onSuccess: function(json, txt){
				cats[cat] = json.ok==1;
				new Element('p',{
					html: json.ok==1?
							  hires_html : 'Not available for hi-res download'
				}).inject( div );
			}
		}).send();
	}
	else {
		new Element('p',{
			html: cats[cat]?
					  hires_html : 'Not available for hi-res download'
		}).inject( div );
	}
	div.inject( into );
}						

function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function trim(v) {
	v = v.replace(/^\s+/, '');	
	v = v.replace(/\s+$/, '');	
	return v;
}



