// ===== MooTools =========================
var imagePath = "";
var activeAXIS = "";
var scrollBars = "";

// ===== Load media data then play first video ==================================================================
window.addEvent('domready',function(){
	if(!$('photoGallery')) return;
	
	if($('scrollContent')){
		scrollBars = new ScrollBar('scrollingArea', 'scrollContainer', 'scrollbar', 'track', 'thumb', 'arrowUp', 'arrowDown');
		new Drag('scrollContainer', {
			'modifiers': {y: 'height', x: 'width'},
			'limit': { x:[100], y:[50] },			
			onDrag: function(){
				scrollBars.update();
			}
		});
	};
	
	var state = 0, activeImage;
	var preloadPrev = new Image(), preloadNext = new Image();
	fx = {
		content: new Fx.Morph($$('.photoGallery')[0], {duration: 500, transition: Fx.Transitions.Sine.easeOut}),
		photo: new Fx.Morph('photoGallery', {duration: 500, transition: Fx.Transitions.Sine.easeOut})
	};
	
	// ===== Load the PlayList ==================================================
	var playList = $('scrollContent');
	var photo = $('photoGallery');
	var oMedia = {}; // Media Container
	var activeVideo = "";

		var fid = jQuery('#ctl00_uxMainContent_uxParam').attr('value');

	var mediaRequest = new Request({
		url:'/photovideoactionpage.aspx',
		data: "fid=" + fid, 
		//url:'xml/photoGallery.xml', 
		method: 'get',
		onSuccess: function(txt,xml) {
			var media = xml.getElementsByTagName('media');
			oMedia.total = media.length;
			var ul = new Element('ul');
			for(var x=0,xl=media.length;x<xl;x++){
				// ===== Convert XML To Object =====
				oMedia[x] = {
					id: media[x].getAttribute('id').trim(),
					asset: {
						thumbnail: media[x].getElementsByTagName('asset')[0].firstChild.nodeValue.trim(),
						photo: media[x].getElementsByTagName('asset')[1].firstChild.nodeValue.trim(),
						href: media[x].getElementsByTagName('asset')[2].firstChild.nodeValue.trim()
					},
					title: media[x].getElementsByTagName('description')[0].getAttribute('title').trim(),
					description: {
						short: media[x].getElementsByTagName('short-description')[0].firstChild.nodeValue.trim(),
						long: media[x].getElementsByTagName('long-description')[0].firstChild.nodeValue.trim()
					}
				};
				// ===== Create PlayList =====
				// <li><a href="#"><img src="images/photo_videoItem1.jpg" width="54" height="36" alt="" /><span><b>Teaser 1 (2:56)</b><br />In rutrum ac</a></span></li>
				ul.adopt(new Element('li').adopt(
					new Element('a',{
						'nVideo': x,
						'events': {
							'click': function(){
								// ===== Set Active Video Button =====
								if(activeVideo != "") activeVideo.removeClass('active');
								activeVideo = this.getParent();
								activeVideo.addClass('active');
								// ===== Activate Selected Video =====
								var media = oMedia[this.getAttribute('nVideo')];
								if($('photoDescription')){
									$('photoDescription').empty().set('html','<h2>'+media.title+'</h2>', media.description.long);
								};

								changeImage(this.getAttribute('nVideo'));
							}
						}
					}).adopt(new Element('img',{'src':oMedia[x].asset.thumbnail,'width':54,'height':36,'alt':''})
					).adopt(new Element('span').set('html','<b>'+oMedia[x].title+'</b>'))
				));
			};
			playList.empty().adopt(ul);
			if($('scrollContent')){
				scrollBars.update();
			}
			// Delay 'fireEvent' to allow flash module to instantiate;
			(function(){ playList.getElements('li')[randomRange(0,4)].getElement('a').fireEvent('click') }).delay(125);
			state = 1;
		},
		onFailure: function() {
			//$('result').set('text', 'The request failed.');
		}
	}).send();
	
	function changeImage(imageIndex){
		//if(typeof imageIndex == 'object') imageIndex = Number(this.get('rel'));
		if ((state == 1) && (imageIndex >= 0)) {
			state = 2;
			activeImage = parseFloat(imageIndex);
			prevImage = ((activeImage) ? activeImage : oMedia.total) - 1;
			nextImage = activeImage + 1;
			if (nextImage == oMedia.total) nextImage = 0;
			
			photo.style.display = "";
			photo.addClass("loading");
	
			preload = new Image();
			preload.onload = nextEffect;
			preload.src = oMedia[imageIndex].asset.photo;
		};
		return false;
	};
	
	// ===== Transitions =====
	function nextEffect(){
		photo.setStyles({background: "#000 url(" + oMedia[activeImage].asset.photo + ") no-repeat center center"});
		photo.removeClass('loading');
	
		if (prevImage >= 0) preloadPrev.src = oMedia[prevImage].asset.photo;
		if (nextImage >= 0) preloadNext.src = oMedia[nextImage].asset.photo;
		
		fx.content.start({'width': Math.min(preload.width+2,446)});
		fx.photo.start({'width': Math.min(preload.width,444), 'height':preload.height}).addEvent('complete',function(){ state = 1; });

		state = 1;
	};
});
// ============================================
String.extend({
	trim: function(){
		return this.replace(/^\s*|\s*$/g, "");
	}
});
function randomRange(lower, upper) {
	var range = upper-lower+1; 
	var l = ("" + range).length; 
	var randomNumber = (Math.floor(Math.random() * Math.pow(10,l)) % range) + parseInt(lower); 
	return randomNumber; 
}
