var PhotoViewer = Class.create();
PhotoViewer.Config = {
	display_image: null,
	width: null,
	height: null,
	matte: null
};
PhotoViewer.prototype = {
	initialize: function( el ){
		try{
			if (PhotoViewer.Config.display_image)
				this.displayImg = PhotoViewer.Config.display_image;
			else
				this.displayImg = el.select( ".MainDisplay")[0];
			this.photoContainer = el.select( ".Photos" )[0];
			var photos = this.photoContainer.getElementsByTagName( 'img' );
		}catch(e){
			//Does Not Have The Proper Components
		}
		for( asdf=0; asdf<photos.length; asdf++ ){
			Event.observe( photos[asdf], 'click', this.__changeImg.bind(this, photos[asdf] ) );
			Event.observe( photos[asdf], 'mouseover', this.__changeImg.bind(this, photos[asdf] ) );
		}
			
		Event.observe(this.displayImg, 'click', this.photoOnClick.bindAsEventListener(this));
		this.displayImg.style.cursor = 'pointer';
	},
	__changeImg: function( img ){
		this.displayImg.src = PhotoViewer.parseImgURL(img.src, {width: PhotoViewer.Config.width, 
																height: PhotoViewer.Config.width, 
																matte:PhotoViewer.Config.matte});
		try{
			this.photoContainer.select( '.selected' )[0].removeClassName( 'selected' );
		}catch(e){
			//Can't Find Previous Selection
		}
		img.addClassName( 'selected' );
	},
	photoOnClick: function(event){
		window.open(Event.element(event).src, 'imgviewer');
	}
}

PhotoViewer.parseImgURL = function(url, replaceSettings){
	console.debug(url);
	if(replaceSettings.width != null){
		if (url.match(/width\/\d+/) != null) {
			url = url.replace(/width\/\d+/, 'width/' + replaceSettings.width);
		} else {url += '/width/' + replaceSettings.width;}
	} else {url = url.replace(/\/width\/\d+\//, '');}
	if(replaceSettings.height != null){
		if (url.match(/height\/\d+/) != null) {
			url = url.replace(/height\/\d+/, 'height/'+ replaceSettings.height);
		} else {url += '/height/' + replaceSettings.height;}
	} else {url = url.replace(/\/height\/\d+\//, '');}
	if(replaceSettings.matte != null){
		//This only supports Hex Based Mattes. RGB support late if at all.
		if (url.match(/matte\/\![a-fA-F0-9]+/) != null) {
			url = url.replace(/matte\/\![a-fA-F0-9]+/, 'matte/'+ replaceSettings.matte);
		} else {url += '/matte/' + replaceSettings.matte;}
	} else {url = url.replace(/matte\/\![a-fA-F0-9]+/, '');}
	console.debug(url);
	return url;
}
PhotoViewer.InitPage = function(){
	var viewers = $$('.PropertyPictureViewer');
	PhotoViewer.viewers = new Array();
	for( pvc=0; pvc<viewers.length; pvc++ ) {
		PhotoViewer.viewers.push(new PhotoViewer( viewers[pvc] ))
	}
	
	 viewers = $$('.PictureViewer');
	 for( pvc=0; pvc<viewers.length; pvc++ ) {
		PhotoViewer.viewers.push(new PhotoViewer( viewers[pvc] ))
	}
}
Event.observe( window, 'load', PhotoViewer.InitPage );
