var imagePath = "";
var activeAXIS = "";
var scrollBars = "";

// ===== Remove default value text from input[type="text"] fields ===============================================
window.addEvent('domready',function(){
	var textfield = $$('input.text');
	if(textfield){
		textfield.addEvents({
			'focus':function(e){ if (this.value==this.defaultValue) this.value = "" },
			'blur':function(e){ if (this.value=="") this.value = this.defaultValue }
		});
	};
	
	$('globalSearchField').addEvent('keyup',function(e){
		if(e.key == 'enter'){
			document.location.href = "Search.aspx?Text=" + this.value;
		};
	});
	$('globalSearchBtn').addEvent('click',function(e){
		new Event(e).stop();
		document.location.href = "Search.aspx?Text=" + $('globalSearchField').value;
	});

});


// ===== Load media data then play first video ==================================================================
window.addEvent('domready',function(){
	if(!$('videoPlayer')) return;

	// ===== FLASH: Video Module ================================================
	var so = new SWFObject('flash/videoModule.swf', 'oeVideoModule', '100%', '100%', '8', '#000000');
	if(so.installedVer.major >= 7){
		so.useExpressInstall('flash/expressinstall.swf');
		so.addParam('allowScriptAccess','always');
		so.write("videoPlayer");
	} else {
		$('videoPlayer').set('html','<h2>Please <a href="http://www.adobe.com/products/flashplayer/" target="blank">upgrade your Flash Player</a><br /> to experience this site to its fullest.</h2>');	
	}
	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();
			}
		});
	}
	// ===== Load the PlayList ==================================================
	if($('singleVideoItem')){
		window.addEvent('load',function(){
			var media = {
				videostill: $('singleVideoItem').getElement('.video_still').get('text'),
				video: $('singleVideoItem').getElement('.video').get('text')
			};
			if($('oeVideoModule')){
				document.getElementById('oeVideoModule').loadMedia(media.videostill,media.video);
				//console.log(media.videostill +":"+media.video);
			}
		});
	} else {
		var listDisplay = ($(document.body).hasClass('index'))? $('videoItems') : $('scrollContent');
		var playList = ($(document.body).hasClass('index'))? 'Ajax.aspx?Mode=HomePageMedia&RefId=11&CacheInterval=0' : 'Ajax.aspx?Mode=HomePageMedia&RefId=17&CacheInterval=0';
		var oMedia = {}; // Media Container
		var activeVideo = "";

		var mediaRequest = new Request({
			url:playList, 
			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(),
							videostill: media[x].getElementsByTagName('asset')[1].firstChild.nodeValue.trim(),
							video: media[x].getElementsByTagName('asset')[2].firstChild.nodeValue.trim(),
							href: media[x].getElementsByTagName('asset')[3].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()
						},
						tags: {
							type: media[x].getElementsByTagName('tags')[0].getAttribute('type').trim(),
							genre: media[x].getElementsByTagName('tags')[0].getAttribute('genre').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', {'AxisType':oMedia[x].tags.type}).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')];
									var breadcrumb = '' //'What we do: <a href="#">Sports</a>, <a href="#">Commercials</a> &nbsp; &nbsp; How we do it: <a href="#">3-axis</a><br />';
									if($('videoDescription')){
										$('videoDescription').empty().set('html',
											'<h4>'+media.title+'</h4>', breadcrumb, media.description.short
										).adopt(
											new Element('img',{'src':'images/btn_ReadMore.gif','width':99,'height':23,'alt':''}).addEvent('click',function(){ window.location.href = media.asset.href; })
										);
									};
									if($('oeVideoModule')){
										document.getElementById('oeVideoModule').loadMedia(media.asset.videostill,media.asset.video);
									}
								}
							}
						}).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>'))
					));
				};
				listDisplay.empty().adopt(ul);
				if($('scrollContent')){
					$$('.selectedVideoType')[0].set('html', 'All Axis Shots: '+oMedia.total+' Video'+((oMedia.total==1)?'':'s'));
					scrollBars.update();
				}
				// Delay 'fireEvent' to allow flash module to instantiate;
				(function(){ listDisplay.getElements('li')[randomRange(0,4)].getElement('a').fireEvent('click') }).delay(125);
			},
			onFailure: function() {
				//$('result').set('text', 'The request failed.');
			}
		}).send();
	};
	
	// ===== TABS: 3-AXIS | 2-AXIS | 1-AXIS =====
	if($('videoTypes')){
		$$('#videoTypes li a').addEvent('click',function(e){
			filterTypeList(this);
			e.stop();
		});
	};
});

function filterTypeList(tab){
	var nTotal = 0;
	var axis = (activeAXIS == tab)? '' : tab.get('text');
	// ===== Only display selected axis =====
	$$('#scrollContent li').each(function(type){
		if(type.getProperty('AxisType') != axis && axis != ''){
			type.setStyle('display','none');
		} else {
			type.setStyle('display','');
			nTotal++;
		}
	});

	$$('.selectedVideoType')[0].set('html', tab.get('text')+': '+nTotal+' Video'+((nTotal==1)?'':'s'));
	// ===== Display Active Tab =====
	if(activeAXIS != '') activeAXIS.getParent().removeClass('active');
	if(axis != ''){
		tab.getParent().addClass('active');
	} else {
		tab.getParent().removeClass('active');
	}
	activeAXIS = (axis != '')? tab : '';
	
	scrollBars.update();
}
// ===== Create Slideshow for multiple images ===================================================================
window.addEvent('domready',function(){
	// ===== Add Slideshow to article pages =====
	if($('slideshow')){
		var imageSlideshow = new mooSimpleSlideshow($('slideshow'),{period:2500});
		imageSlideshow.displayImage();
	}
	// ===== Replace Default Checkboxes with Graphics =====
	var checkboxes = $$('.content input[type=checkbox]');
	if(checkboxes.length){
		new mooForms (document.getElement('form'));
	}
	addVideoPlayBtn();
});

// ===== Add Video Play Graphic Overlay for all video thumbnails ================================================
function addVideoPlayBtn(){
	var searchVideo = $$('.mainContent span.video');
	if(searchVideo.length){
		var img = searchVideo[0].getElement('img');
		var src = img.getProperty('src');
		//imagePath = src.substr(0,src.lastIndexOf('/')+1);
		imagePath = "images/";
		var clear = imagePath + "clear.gif"
		searchVideo.each(function(video){
			var size = video.getElement('img').offsetWidth;
			var playBtn = new Element('img', {
				'src' : imagePath + 'btn_play_x'+size+'.png',
				'width': size,
				'height': size,
				'class': 'play'
			});
			playBtn.injectBefore(video.getElement('img'));
			if(Browser.Engine.trident4) fixPNG();
		});
	}
};

// ===== Fix PNG issues for any IE < v7 =========================================================================
function fixPNG(){
	$$('img[src$=png]').each(function(el){
		var coord = el.getCoordinates();
		el.setStyles({
			width: coord.width,
			height: coord.height,
			filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + el.src + '", sizingMethod="crop")'
			//visibility: 'hidden'
		});
		el.src = imagePath + 'clear.gif';
		el.addEvent('load',function() {
			//el.setStyle('visibility','visible');
		});
	});
}

// ==============================================================================================================
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; 
}
