function delegate(obj, method, args)
{
	return function () { method.apply(obj, args ? args.concat(arguments) : arguments); }
}

// ---------------------------------------------------------------------------------------------------------------------

// NOTE: Only one photoHost/thumbHost is supported, passing multiple on different instances will not work.

function Photo(photoData, thumbHost, photoHost)
{
	// fix this as it comes as a string 0/1 from PHP:
	photoData.isSeparator = parseInt(photoData.isSeparator);
	
	this.photoData = photoData;
	this.thumbHost = thumbHost;
	this.photoHost = photoHost;
	this.id = Photo.id++;
	Photo.all.push(this);
	
	var tEl = this.thumbEl = document.createElement('div');
	
	if (photoData.isSeparator) {
		tEl.className = 'thumbSeparator';	
	} else {
		tEl.className = 'thumb';
		tEl.onclick = delegate(this, this.pick);
	}
	
	$(tEl).css('opacity', 0.4);
	$(thumbHost).append(tEl).css('opacity', 0);
}

Photo.id = 1;

Photo.all = [];

Photo.prototype = {
	selected: false, 
	
	// tied to onmouseover
	rollOver: function () {
		
	},
	
	// tied to onmouseout
	rollOut: function () {
		
	},
	
	// tied to onclick fo the element, can be called manually
	pick: function() {
		var that = this;
		
		function onFade() {
			$(that.photoHost).html(
				'<div class="photoClient">' +
					'<div style="width: ' + (that.photoData.normalWidth - 2) + 'px; height: ' + (that.photoData.normalHeight - 2) + 'px"></div>' + 
					'<img onload="Photo.prototype.onPhotoLoad(this)" src="' + (isOffline ? '_media_properties_' : '/_media/properties/') + that.photoData.src+'">' + 
				'</div>'
			);
			
			$('.photoClient div').css('opacity', 0);
			$('.photoClient img').css('opacity', 0);
			
			setTimeout(function () {
				$('.photoClient div').animate({'opacity': 1}, 125);
			}, 600);
			
			$(that.photoHost).animate({opacity:1}, 125);	
		}
		
		$(this.thumbEl).animate({opacity: '1'}, 200);		
		$(this.photoHost).animate({opacity:0}, 125, onFade);
		
		this.selected = true;
		
		for (var i in Photo.all) {
			if (Photo.all.hasOwnProperty(i)) {
				if (this !== Photo.all[i]) {
					Photo.all[i].unpick();
				}
			}
		}
	},
	
	// called auto by pick for the rest of the photos
	unpick: function() {
		if (!this.photoData.isSeparator) {
			this.selected = false;
			$(this.thumbEl).animate({opacity: '0.4'}, 200);
		}
	},
	
	// UNTESTED
	onPhotoLoad: function(sender) {
		preloadPhotos(); // generated by the view inline
		
		var thHost = $(Photo.all[0].thumbHost);
		
		if (thHost.css('opacity') < 1)
                    thHost.animate({opacity:1}, 250);
		$(sender).animate({opacity:1}, 250);
	}
}

function Overlay2(overlayData, overlayHost)
{
	this.data = overlayData;
	this.hostEl = overlayHost;

	var doc = $(document);
	var win = $(window);
	var that = this;

	if (Overlay2.instance !== null) {
		Overlay2.instance.destruct();
	}

	Overlay2.instance = this;

	$(this.hostEl).append(
		$('<div id="overlayFade"></div>').css('opacity', 0)
	);

	$('#overlayFade').height(doc.height()).animate({'opacity': 0.75}, 300, part2);


	function part2()
	{
		var fade = $('#overlayFade');
		var startLeftMargin = Math.floor(win.width()/2) - 2/2;
		var startTopMargin = Math.floor(win.height()/2) - 500/2;
		var endLeftMargin = Math.floor(win.width()/2) - 740/2;

		$(that.hostEl).append('<div id="overlayPlate" style="margin-left:' + startLeftMargin + 'px; margin-top:' + startTopMargin + 'px"></div>');

		var plate = $('#overlayPlate');

		var animate = {
			'width': '704px',
			'marginLeft': endLeftMargin + 'px',
			'paddingLeft': '18px',
			'paddingRight': '18px'
		};

		if (!$.browser.msie) {
			plate.css('opacity', 0);
			animate.opacity = 1;
		} else {
			plate.css('background-color', '#070706');
			animate.backgroundColor = '#cccccc';
		}

		$('#overlayPlate').animate(animate, 400, part3);
	}

	function part3()
	{
		function photoFrame(prefix, index)
		{
			var html = '';
                        srcImage = (isOffline ? '_media_properties_publicationImages_' :'/_media/properties/publicationImages/');
                        urlLoader = (isOffline ?'_media_':'/_media/');
			html += '<div style="float:left; width:704px; height:444px; background:url('+urlLoader+'loader.gif) no-repeat center center; margin-right:20px;">';
			html += '<img src="' + srcImage + prefix + '_' + index + '_normal.jpg" id="overlayImg' + index + '">';
			html += '<script>$("#overlayImg' + index + '").css("opacity", 0).load(function () { $(this).animate({"opacity": 1}, 400);});<\/script>';
			html += '</div>';

			return html;
		}

		var html = '';
                var target = (that.data.pdf != "")?"target=\"_blank\"":"";
		html += '<div id="overlayClient">';
		html += '<div class="controlsLeft"><a href="">&lt; Back</a> &nbsp;|&nbsp; <a href="">Next &gt;</a></div>';
		html += '<div class="controlsRight"><a href="" '+ target +'>Get PDF (full size view)</a> &nbsp;|<a href="">&nbsp; Close</a></div>';
		html += '<div class="picHost"><div class="picClient"></div></div>';
		html += '</div>';
		html += '<div id="overlayClientReveal"></div>';

		$('#overlayPlate').append($(html));

		var controls = $('#overlayClient a');
		$(that.backLinkEl = controls.get(0)).click(function () { that.prevSlide(); return false; }).css();
		$(that.nextLinkEl = controls.get(1)).click(function () { that.nextSlide(); return false; });
                if (that.data.pdf != "") {
                    urlDocument = (isOffline ?'_media_properties_publicationImages_pdf_':'/_media/properties/publicationImages/pdf/');
                    controls.get(2).href = urlDocument + that.data.pdf;
                } else {
                    controls.get(2).href = 'javascript:alert("The publication does not PDF!")';
                }
		$(controls.get(3)).click(function () { that.destruct(); return false; });

		that.syncLinkState();

		$('#overlayClientReveal').css('opacity', 1).animate({opacity: 0}, 150, part4);

		var html = '';
		var images = that.data.images.split("*");
                if (that.data.count == 0) alert("The publication has no images!");
		for (var i = 0; i < that.data.count; i++) {
			html += photoFrame(that.data.prefix, images[i]);
		}

		$('#overlayClient .picClient').html(html);
	}

	function part4()
	{
		$('#overlayClientReveal').hide();
	}
}

Overlay2.instance = null;
Overlay2.linkOffColor = '#999';
Overlay2.linkOnColor = '#292929';

Overlay2.prototype = {
	data: null,
	hostEl: null,
	slide:0,
	backLinkEl:null,
	nextLinkEl:null,

	destruct: function ()
	{
		$('#overlayPlate').hide();
		$('#overlayFade').animate({opacity: 0}, 300, part1);

		var that = this;

		function part1()
		{
			$(that.hostEl).html('');
			Overlay2.instance = null;
		}
	},

	nextSlide: function()
	{
		if (this.slide < this.data.count - 1) this.moveSlide(1);
	},

	prevSlide: function()
	{
		if (this.slide > 0) this.moveSlide(-1);
	},

	moveSlide: function(delta)
	{
		this.slide += delta;

		$('#overlayClient .picClient').animate({'left': - (724 * this.slide) }, 600);

		this.syncLinkState();
	},

	syncLinkState: function()
	{
		$(this.backLinkEl).css('color', this.slide > 0 ? Overlay2.linkOnColor : Overlay2.linkOffColor);
		$(this.nextLinkEl).css('color', this.slide < this.data.count - 1 ? Overlay2.linkOnColor : Overlay2.linkOffColor);
	}
}
