var customSelects = [];
var searchD = null;
var menuLogin = null;
var debugging = 1;
var searchTimer = 0;

var log = function(t){
	if (!debugging) return;

	var elmLog = $('log');
	if (!elmLog) elmLog = new Element('pre',{'id':'log',events:{click:function(){this.set('text','');}},styles:{background:'transparent url(../gfx/main_bg_m2.png) repeat scroll 0 0',textAlign:'left',position:'absolute',fontFamily:'Tahoma,Arial,sans-serif',top:280,left:10,float:'left',height:120,width:300,whiteSpace:'pre',fontSize:'9px',color:'#eeaa33',zIndex:50000,overflow:'auto'}}).inject(document.body);
	elmLog.appendText('\n\r'+t);
}

// http://frogsbrain.wordpress.com/2007/04/28/javascript-stringformat-method/
var prf = function(text) {
    if ( arguments.length <= 1 ) {
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ ) {
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ] );
    }

    return text;
};

Element.implement({

	getOffsetParent: function() {
		var body = this.getDocument().body;
		if (this == body) return null;
		if (!Browser.Engine.trident) return $(this.offsetParent);
		var el = this;
		while ((el = el.parentNode)){
			if (el == body || Element.getComputedStyle(el, 'position') != 'static') return $(el);
		}
		return null;
	}

});

var Asset = new Hash({

	image: function(source, properties){
		properties = $merge({
			'onload': $empty,
			'onabort': $empty,
			'onerror': $empty
		}, properties);
		var image = new Image();
		var element = $(image) || new Element('img');
		['load', 'abort', 'error'].each(function(name){
			var type = 'on' + name;
			var event = properties[type];
			delete properties[type];
			image[type] = function(){
				if (!image) return;
				if (!element.parentNode){
					element.width = image.width;
					element.height = image.height;
				}
				image = image.onload = image.onabort = image.onerror = null;
				event.delay(1, element, element);
				element.fireEvent(name, element, 1);
			};
		});
		image.src = element.src = source;
		if (image && image.complete) image.onload.delay(1);
		return element.setProperties(properties);
	}
})

var OverlayFix = new Class({

	initialize: function(el) {
		this.element = $(el);
		this.shown = false;
		this.relative = this.element.getOffsetParent();
		if (Browser.Engine.trident) {
			this.fix = new Element('div', {
				'class':'overlayFix',
				'styles': {
					'position': 'absolute',
					'display': 'none',
					'background-color': '#000'
				},
				'opacity':0.01
			}).set('html','<iframe style="display:block;position:absolute;left:0;top:0;border:none;" width="100%" height="100%" frameborder="0" scrolling="no" src=""></iframe>').getFirst().set('opacity',0.01).getParent().inject(this.element, 'after');
		}
		else {
			this.fix = new Element('div', {
				'class':'overlayFix',
				'styles': {
					'position': 'absolute',
					'border': 'none',
					'display': 'none',
					'background-color' : '#000'
				},
				'opacity':0.01
			}).inject(this.element, 'after');
		}
	},

	show: function() {
		if (this.fix && !this.shown) {
			this.shown = true;
			var coords = this.element.getCoordinates(this.relative);
			delete coords.right;
			delete coords.left;
			coords.top = this.element.getStyle('top');
			delete coords.bottom;
			this.fix.setStyles($extend(coords, {
				'display': '',
				'margin-top': this.element.getStyle('margin-top')
			}));
		}
		return this;
	},

	hide: function() {
		if (this.fix && this.shown) {
			this.fix.setStyle('display', 'none');
			this.shown = false;
		}
		return this;
	},

	destroy: function() {
		this.fix = this.fix.destroy();
	}

});

/*
--------------------------------------
    CustomSelect for 1.2 MooTools
--------------------------------------
*/
var CustomSelect = new Class({

	Implements: Events,

	initialize: function(selectArea,optionContainerClass,setOptionTitle){
		if(!selectArea) { return (false); }
		this.selectArea = selectArea;
		this.id = selectArea.get('id');
		this.selectList = false;
		this.selected = false;
		this.setOptionTitle = setOptionTitle || false;
		this.selectOpen = false;
		this.buildContents();
		if (optionContainerClass) this.optionContainer.addClass(optionContainerClass);
		this.selectElement = $(selectArea).getElement('select');
		this.selectElement.setStyle('display', 'none');
		this.elements = this.selectElement.getChildren().each(function(child) {
			if(child.get('tag') == 'optgroup') {
				this.addOptionGroup(child);
			} else {
				this.addOption(child);
			}
		}.bind(this));
		this.bindEvents();
		this.optionContainer.adopt(new Element('div',{'class':'optContainerBottom'}));
		this.fix = new OverlayFix(this.optionContainer);
  },
	buildContents: function() {
		this.selectField = new Element('div', {
			'class': 'selectField'
		});
		this.dropArea = new Element('div', {
			'class': 'status'
		});
		this.selectedOption = new Element('div', {
			'class': 'selected'
		});
		this.optionContainer = new Element('div', {
			'class': 'optContainer',
			'html': ''
		});
		this.selectedOption.inject(this.dropArea);
		this.dropArea.inject(this.selectField);
		this.optionContainer.inject(this.selectArea).adopt(new Element('div',{'class':'optContainerTop'}));
		this.selectField.inject(this.selectArea, 'top');
	},
	bindEvents: function() {
		this.dropArea.addEvents({
			'click': function(e){
				if(this.selectOpen == true) {
					this.hideList();
				} else {
					new Event(e).stop();
					this.showList();
				}
			}.bind(this),
			'mouseover': function(e) {
				if(this.selectOpen == false) {
					this.hideList();
				}
			}.bind(this)
		});
		$(document).addEvent('click', function() {
			this.hideList();
		}.bind(this));
	},
	
	addOptionGroup: function(optionGroup) {
		var group = new Element('div').addClass('optGroup');
		var label = new Element('div').addClass('optLabel'); 
		var optList  = new Element('div').addClass('optList');
		optList.inject(group);
		label.set('text',optionGroup.getProperty('label'));
		label.inject(group, 'top');
		optionGroup.getElements('option').each(function(option) {
			newOption = this.returnOption(option);
			newOption.inject(optList);
		}.bind(this));
		group.inject(this.optionContainer);

	},

	addOption: function(option) {
		newOption = this.returnOption(option);
		newOption.inject(this.optionContainer);
	},

	returnOption: function(option) {
		var newOption = new Element('div', {
			'html': option.text
		});
		if (this.setOptionTitle) newOption.set('title',option.text);
		if($defined(option.getProperty('class')) && $chk(option.getProperty('class'))) {
			newOption.set('class',option.getProperty('class'));
		}
		newOption.addClass('opt');
		if(option.disabled) {
			newOption.addClass('disabled') 
		} else {
			newOption.addEvents({
				'click': this.onOptionClick.bindWithEvent(this),
				'mouseout': this.onOptionMouseout.bindWithEvent(this),
				'mouseover': this.onOptionMouseover.bindWithEvent(this)
			})
		}
		if(option.selected) {
			if(this.selected) { this.selected.removeClass('selected'); }
			this.selected = newOption;
			newOption.addClass('selected');
			this.selectedOption.set('text',option.text);
		}
		newOption.value = option.value;
		return newOption;
	},

	onOptionClick: function(e) {
		var event = new Event(e);
		if(this.selected != event.target) {
			this.selected.removeClass('selected');
			event.target.addClass('selected');
			this.selected = event.target;
			this.selectedOption.set('text',this.selected.get('text'));
			this.selectElement.value = event.target.value;
		 	this.fireEvent('change');
		}
		this.hideList();
	},
	onOptionMouseover: function(e) {
		var event = new Event(e);
		event.target.addClass('over');
	},
	onOptionMouseout: function(e) {
		var event = new Event(e);
		event.target.removeClass('over');
	},
	showList: function() {
		if(this.selectOpen == false) {
			customSelects.each(function(c){c.hideList()});
			this.selectOpen = true;
			pos = this.selectField.getSize();
			this.optionContainer.setStyles({'display':'block',left:0,top:pos.y,'z-index':20});
			if (this.optionContainer.getSize().y > 400) this.optionContainer.setStyles({'height':400,'overflow-y':'auto'});
			if (this.fix) this.fix.show();
		 	this.fireEvent('showlist');
		}
	},
	hideList: function() {
		if(this.selectOpen == true) {
			this.selectOpen = false;
			this.optionContainer.setStyles({'display':'none','z-index':-1});
		}
		if (this.fix) this.fix.hide();
		 	this.fireEvent('hidelist');
	}
});

var privateReady = function(){


	$('thebody').getElements('select').each(function(sel,ind){
		customSelects[ind] = new CustomSelect(sel.getParent('span'),sel.getParent('span').get('class').replace('customSelect').clean(),false);
	});

	var hideinfolink = $('hideinfolink');
	if (hideinfolink) {
		hideinfolink.addEvent('click',function(e){toggleInfo(this);}).getParent().getChildren().addEvents({
			'mouseover':function(){
				this.addClass('hovered');
			},
			'mouseout':function(){
				this.removeClass('hovered');
			}
		});
		[$('prevLine'),$('nextLine')].each(function(el){el.addEvent('click',function(){doPhotoLine(this);});});
	}

	bindEventsTo('thebody');

	privateAfterReady.delay(10);

	photolinelinks = $('photolinelinks');

}

var loadingLine = false;
//var urlLine = 0;
var urlLineOld = 0;
var photolinelinks = null;

var thisLineRequest = null;

var doPhotoLine = function(x){
	if (loadingLine) return;
	loadingLine = true;
	if ($(x).get('id') == 'prevLine')
		var thisLineNumber = urlLine-1;
	else
		var thisLineNumber = urlLine+1;

	if (thisLineNumber > urlLine && $('nextLine').hasClass('hide')) {
		loadingLine = false;
		return;
	}
	if (thisLineNumber < urlLine && $('prevLine').hasClass('hide')) {
		loadingLine = false;
		return;
	}

	if (thisLineRequest) thisLineRequest.cancel();
	thisLineRequest = new Request({
			'url':'photoline.jx'+window.location.href.substr(window.location.href.indexOf('?'))+';pg='+thisLineNumber,
			'method':'get',
		onRequest:function(){
			photolinelinks.getNext().setStyle('left',0).adopt(photolinelinks.getChildren()).getParent().addClass('ajax-loading-line').addClass('zIndexLine').getLast().set('opacity',0.65);
			photolinelinks.empty();
		},
		onSuccess:function(txt,xml){
			if (txt.length > 10) {
				photolinelinks.set('html',txt);
				urlLineOld = urlLine;
				urlLine = thisLineNumber;
				bindEventsTo(photolinelinks);

				if (photolinelinks.getFirst().get('rel') == 'start')
					$('prevLine').addClass('hide');
				else
					$('prevLine').removeClass('hide');
				if (photolinelinks.getLast().get('rel') == 'end')
					$('nextLine').addClass('hide');
				else
					$('nextLine').removeClass('hide');

				var leftA = [850,-850];
				if (urlLineOld < urlLine)
					leftA = leftA.reverse();

				photolinelinks.getNext().set('tween',{'duration':1000}).tween('left',[0,leftA[0]]);
				photolinelinks.set('tween',{'duration':1000}).tween('left',[leftA[1],0]);
				photolinelinks.getParent().removeClass('ajax-loading-line');
				setTimeout(function(){
					photolinelinks.set('opacity',1).getNext().getElements('a').removeEvents('click').dispose();
					if (urlLineOld > urlLine)
						loadPhoto(photolinelinks.getLast(),photolinelinks.getLast());
					else
						loadPhoto(photolinelinks.getFirst(),photolinelinks.getFirst());
					photolinelinks.getParent().removeClass('zIndexLine');
					loadingLine = false;
				},1200);
			}
			else {
				loadingLine = false;
				photolinelinks.adopt(photolinelinks.getNext().getChildren()).getParent().removeClass('ajax-loading-line').removeClass('zIndexLine');
				photolinelinks.getNext().empty();
			}
		},
		onFailure:function(){
			log('photolines failure');
			loadingLine = false;
			photolinelinks.adopt(photolinelinks.getNext().getChildren()).getParent().removeClass('ajax-loading-line').removeClass('zIndexLine');
			photolinelinks.getNext().empty();
		},
		onCancel:function(){
			log('photolines cancel');
			loadingLine = false;
			photolinelinks.adopt(photolinelinks.getNext().getChildren()).getParent().removeClass('ajax-loading-line').removeClass('zIndexLine');
			photolinelinks.getNext().empty();
		}
	}).send({'line':thisLineNumber,'_t':$time()});
}

var loadingPhoto = false;
var loadingPhotoRequest = null;

var loadPhoto = function(uri,elm) {
//	log('loadphoto');
	if (loadingPhoto) return;
	rmcrop();
	var pos = elm.href.indexOf('?');
	if (pos) var ui = elm.href.substr(pos);
	else var ui = elm.href;
	// log(ui);

	loadingPhoto = true;

	elm.getParent().getChildren().removeClass('active');
	elm.addClass('active');

	if (loadingPhotoRequest) loadingPhotoRequest.cancel();

	loadingPhotoRequest = new Request.JSON({
		'url':'photo.jx'+ui,
		'method':'get',
		onRequest:function(){
			$('photoinfo').setStyle('visibility','hidden');
			$('photoimage').addClass('ajax-loading-photo');
			$('actualphotoimg').setStyle('visibility','hidden');
			$('actualphotoheading').setStyle('visibility','hidden');
		},
		onSuccess:function(im){
			new Asset.image(im.actualphotoimg,{onload:function(im){
						$('actualphotoimg').set('src',im.get('src')).setStyle('visibility','visible');
						$('photoinfo').setStyle('visibility','visible');
						$('photoimage').removeClass('ajax-loading');
			}});
			$('evn').set('href',im.event_href);
			$('evn').set('text',im.event_text);
			if ($('xalbum')) {
				$('xalbum').set('value',im.album);
				$('xphoto').set('value',im.photo);
			}
			$('actualphotolink').set('href',im.actualphotolink);
			$('actualphotoheading').set('text',im.actualphotoheading).setStyle('visibility','visible');
//cart-out			$('addtocart').set('href',im.addtocart);
			$('download').set('href',im.download);
			if ($('adm_img')) $('adm_img').set('href', im.addtocart);
			if (im.imagenext != "0") $('nextPhoto').removeClass('hide').set('href',im.imagenext+'#next');
			else $('nextPhoto').addClass('hide');
			if (im.imageprev != "0") $('previousPhoto').removeClass('hide').set('href',im.imageprev+'#prev');
			else $('previousPhoto').addClass('hide');

                        var propList = "";
                        // remove (old) keywords
                        $('keys').innerHTML = '';

                        for(var pr in im) {
//                            if(typeof(obj[propName]) != "undefined") {
                            if (pr.substr(0,2) == 'ex') {
                                if (pr == 'exKeys') {
                                    for (i=0; i<im[pr].length; i++) {
                                        var el = document.createElement('p');
                                        el.innerHTML = im[pr][i];
                                        $('keys').appendChild(el);
                                    }
                                } else {
                                    $(pr).set('text', im[pr]);
                                }
                            }
                        }
			// // $("exfile_desc").set('text',im.exfile_desc);
			// // $("exfile_desc").set('text',im.exfile_desc);
			// // $("exfile_name").set('text',im.exfile_name),
			// $("exFileSize").set('text',im.exFileSize),
			// $("exres").set('text',im.exres),
			// // $("exexpo_time").set('text',im.exexpo_time),
			// // $("excamera").set('text',im.excamera),
			// $("extime").set('text',im.extime),
			// // $("exorient").set('text',im.exorient),
			// $("excredit").set('text',im.excredit),
			// $("exsource").set('text',im.exsource),
			// $("exeditor").set('text',im.exeditor),
			// $("exstate").set('text',im.exstate),
			// $("excity").set('text',im.excity),
			// $("exlocation").set('text',im.exlocation),
			// $("exby_line").set('text',im.exby_line),
			// $("extitle").set('text',im.extitle),
			// $("exkeywords").set('text',im.exkeywords);
			loadingPhoto = false;
		},
		onFailure:function(){
			log('photo failure');
			$('actualphotoimg').setStyle('visibility','visible');
			$('photoinfo').setStyle('visibility','visible');
			$('photoimage').removeClass('ajax-loading');
			$('actualphotoheading').setStyle('visibility','visible');
			loadingPhoto = false;
		}
	}).send({'photo':uri});
}

var bindEventsTo = function(t){
	$$($(t).getElements('a')).each(function(el){
			// log ('href: ' + el.get('href'));
                // log('w: ' + window.location.href.contains);
                // log('file: ' + el.get('href').split("/").getLast());
		el.addEvents({
			'click':function(e){
				e = new Event(e);
				if (customSelects.length>0) customSelects.each(function(cus){cus.hideList()});

				var hrefa = this.get('href')? this.get('href').split("/").getLast() : '';
				var param = '';

				var pos = hrefa.indexOf('?');
				var file = hrefa.substring(0,pos);
				if (pos >= 0) hrefa = hrefa.substr(pos);

				var contPhoto = hrefa.contains('photo=');
				var contPage  = hrefa.contains('page=');
				var contAlbum = hrefa.contains('album=');
				var contFull = hrefa.contains('full');
				var contNextPhoto = hrefa.contains('#next');
				var contPrevPhoto = hrefa.contains('#prev');
				var contD = hrefa.contains('#add-to-cart');

				var crop = hrefa.contains('#');
				if (contFull) {
					return;
				}

				// if ($("actualphotoimg").style['display'] == 'none') {
				// 	e.stop();
				// 	alert("Nooooone" + $("actualphotoimg").style);
				// 	return false;
				// }

				if (contD) {

				} else if (window.location.href.contains('/photo')) {
					if (contNextPhoto) {
						var nextA = photolinelinks.getElement('.active').getNext() || false;
						if (nextA) loadPhoto(nextA.get('href'),nextA);
						else doPhotoLine('nextLine');
					}
					else if (contPrevPhoto) {
						var prevA = photolinelinks.getElement('.active').getPrevious() || false;
						if (prevA) loadPhoto(prevA.get('href'),prevA);
						else doPhotoLine('prevLine');
					} else if (contAlbum && contPhoto) {
						loadPhoto(this.get('href'),this);
					} else return;
				} else if (file.contains('album')) {
					return;
				} else if (window.location.href.contains('album') && contPhoto) {
					return;
				} else {
					if (contPage && !contPhoto && !contAlbum) { // index.* ? page=4
						return;
					} else if (contAlbum && !contPhoto) { // album=14&page=4 || album=7
						return;
					} else return;
				}
				e.stop();
				return false;
			}
		});
	});
}

var toggleInfo = function(t,b){
	$(t).getFirst().toggleClass('doHideinfo');
	$('photoinfo').toggleClass('vis');
}

var Res = function(sz, r) {
	this.ratio = r;
	var x = sz.x / r[0];
	var y = sz.y / r[1];
	
	if (x<y) {
		this.x = sz.x;
		this.y = Math.round(this.x * r[1] / r[0]);
	} else {
		this.y = sz.y;
		this.x = Math.round(this.y * r[0] / r[1]);
	}

	this.px = Math.round((sz.x-this.x) / 2);
	this.py = Math.round((sz.y-this.y) / 2);

//	log(prf('size {0}x{1} - {2}x{3}+{4}', sz.x, sz.y, this.x, this.y, this.px));

}			

var rmcrop = function() {
	var it = $('cropfrm');
	if (!it) return;
	it.setStyle('display', 'none');
	$('icrop').setStyle('display', 'none');
	while (it = $("actualphotolink").getElements('div')[0]) {
		$("actualphotolink").removeChild(it);
	}
	crop_th = undefined;
	crop_la = undefined;
	$("actualphotoimg").removeAttribute("style");
}

var updateCoords = function(pos) {
	$("crop_x").set('value', pos.x);
	$("crop_y").set('value', pos.y);
	$("crop_w").set('value', pos.w);
	$("crop_h").set('value', pos.h);
}

var docrop = function(tp, par) {
	par.et.stop();
	rmcrop();
	$('cropfrm').setStyle('display', 'block');
	$("crop_btn").setStyle('border-color', par.color);
	$("crop_type").set('value', tp);
	$("actualphotolink").removeAttribute("href");
	var res = new Res($('actualphotoimg').getSize(), par.ratio);

	return new Lasso.Crop('actualphotoimg',{
		  ratio : res.ratio,
				preset : [res.px,res.py,res.x+res.px,res.y+res.py],
				handleSize : 9,
				opacity : .7,
				color : par.color,
				border : '/gfx/crop.gif',
				onResize : updateCoords
	});
}

var crop_th = undefined;
var crop_la = undefined;

var privateAfterReady = function(){

	searchD = $('search');
	menuLogin = $('menuLogin');

	menuLogin.addEvent('mouseenter',function(){this.addClass('hover');});
	if (menuLogin.hasClass('signin')) {
		menuLogin.getElements('input').addEvents({
			'click':function(){
				menuLogin.addClass('showing');
				if (this.get('value') == this.get('rel')) this.set('value','');
			},
			'focus':function(){
				menuLogin.addClass('showing');
				if (this.get('value') == this.get('rel')) this.set('value','');
			},
			'blur':function(){
				menuLogin.removeClass('showing');
				if (this.get('value') == "") this.set('value',this.get('rel'));
			}
		});
		menuLogin.addEvent('mouseleave',function(){
			this.removeClass('hover');
		});
	}
	else {
		menuLogin.addEvent('mouseleave',function(){
			this.removeClass('hover');
		});
	}

	searchD.addEvents({'mouseenter':function(){searchD.addClass('hover');},'click':function(e){this.set('class','hover');e=new Event(e);e.stop();}});
	searchD.getElement("input.button").addEvent('click',function(ev){
		ev = new Event(ev);
		ev.target.getParent('form').submit();
	});
	searchD.getElements('.advanced input').addEvents({
		'focus':function(e){
			searchD.set('class','showing hover');
			if (this.get('value') == this.get('rel')) this.set('value','');
			this.addClass('focused');
			e = new Event(e);
			e.stop();
			$(document.html).removeEvents().addEvent('click',function(){searchD.set('class','');$(document.html).removeEvents('click');});
		},
		'blur':function(){
			this.removeClass('focused');
			if (this.get('value') == "") this.set('value',this.get('rel'));
		}
	});
	searchD.getElements('.advanced .wheresearch input').addEvents({
		'mousedown':function(e){
			this.set('checked','true');
		}
	});
	searchD.addEvent('mouseleave',function(){
		if (searchD.getElement('.focused')) {
			searchD.set('class','showing');
		}
		else {
			searchD.removeClass('hover');
		}
	});

	var posun = customSelects.length;
	searchD.getElements('select').each(function(sel,ind){
		customSelects[posun+ind] = new CustomSelect(sel.getParent('span'),sel.getParent('span').get('class').replace('customSelect').clean(),sel.hasClass('location')).addEvents({
			'onShowlist':function(e){
				searchD.set('class','showing hover');
			},
			'onHidelist':function(e){
				searchD.removeClass('showing');
			}
		});
	});
	if (customSelects.length == 4){
		customSelects[0].addEvent('onChange',function(e){
				// log(this.selectArea.getParent('form').toQueryString());
				window.location.href = "index.html?"+this.selectArea.getParent('form').toQueryString();
		});
	}

//	[$('m_crop_la'),$('m_crop_th')].each(function(el){el.addEvent('click',function(){alert("ye");});});
	if ($('m_crop_th')) {
		$('m_crop_th').addEvent(
			'click', function(e) {
				crop_th = docrop('th', {et: e, ratio: [4,3], color: 'hsl(210, 66%, 33%)'});
			});

		$('m_crop_la').addEvent(
			'click', function(e) {
				crop_th = docrop('la', {et: e, ratio: [240,268], color: 'hsl(60, 66%, 33%)'});
			});
	}
}

window.addEvent("domready",privateReady);