/* -------------------------------------------------------------- 
  
   application.js
   * Studio Hari by AREA 17
   
-------------------------------------------------------------- */

var isSafari = false;
var isSafari3 = false;
var isIE = false;
var isIE7 = false;
var isIE6 = false;
var isMozilla = false;
var isMac = false;
var isOpera = false;

var isProduction = false;
var hasVideo = false;
var playerId = "";
var playThumbPos = 0;	
var firstLoaded = false;

var hasFlash = false;
var ctrlbarHidden = true;

document.observe("dom:loaded", runOnDOMready);
Event.observe(window, 'load', function() { runOnLoaded(); });

function runOnDOMready() {
	setUpClasses();
	detectBrowser();
	featuresSlider();
	charactersIndexLayout();
	productionsIndexLayout();
	productionsClicks();
	if (isIE6) {
		ie6fixes();
	} 
	
}

function runOnLoaded() {		
	if (isIE) {
		setUpClasses();
	}
	productionsClicks();
}

function setUpClasses() {
	$$('input[type=submit]').invoke('addClassName', 'submit');
	$$('input[type=radio]').invoke('addClassName', 'radio');
	$$('input[type=checkbox]').invoke('addClassName', 'checkBox');
	$$('input[type=image]').invoke('addClassName', 'image');
	$$('input[type=file]').invoke('addClassName', 'file');	
	$$('input[type=hidden]').invoke('addClassName', 'hidden');
	$$('tr:nth-child(even)').invoke('addClassName', 'even');
	$$('li:nth-child(even)').invoke('addClassName', 'even');	
	$$('li:first-child').invoke('addClassName', 'first');
	$$('li:last-child').invoke('addClassName', 'last');
}

function detectBrowser() {
	// Based on Mike "1312" and Phil script for AREA 17.
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ some simple browser testing */
	if (navigator.appVersion.indexOf("Mac")!=-1) {
		isMac = true;
		$$('body').invoke('addClassName', 'isMac');
	}
	// Safari versioning
	isSafari = Prototype.Browser.WebKit;
	// are we on safari 3? add a class (it over anti aliases everything which causes padding issues)
	// http://www.hedgerwow.com/360/dhtml/detect-safari3-by-js-css.html
	if( window.devicePixelRatio && window.getMatchedCSSRules && !window.Opera){
		isSafari3 = !!window.getMatchedCSSRules(document.documentElement,'');
	}
	if (isSafari) {	
		$$('body').invoke('addClassName', 'isSafari');
		if (isSafari3) { $$('body').invoke('addClassName', 'isSafari3'); }
	}
	// (ok so theres an assumption that any Safari thats not Safari3 is Safari2 here)		
	// IE versioning
	isIE = Prototype.Browser.IE;
	if (isIE) {	
		$$('body').invoke('addClassName', 'isIE');
		if (typeof document.body.style.maxHeight != "undefined") { if (!isSafari) { isIE7 = true; } }
		if (isIE7) {
			$$('body').invoke('addClassName', 'isIE7');
		} else {
			isIE6 = true;
		}
	}
	/* http://gmatter.wordpress.com/2006/10/20/detecting-ie7-in-javascript/ */
	// ### ok so theres an assumption that any IE thats not IE7 is IE6 here	
	// alittle mozilla testing too
	isMozilla = Prototype.Browser.Gecko;
	if (isMozilla) {
		$$('body').invoke('addClassName', 'isMozilla');
		if(navigator.userAgent.search(/3.0/) != -1) {
			$$('body').invoke('addClassName', 'isFF3');
		} else {
			$$('body').invoke('addClassName', 'isFF2');
		}
	}	
	// and now also Opera
	isOpera = Prototype.Browser.Opera;
	if (isOpera) {
		$$('body').invoke('addClassName', 'isOpera');
	}
	
	if(FlashDetect.versionAtLeast(9)){
		hasFlash = true;
	}
	
}

function characterPopup(url) {
	var load = window.open(url,'','scrollbars=no,menubar=no,height=420,width=640,resizable=no,toolbar=no,location=no,status=no');
 	return false;
}

// DEPRECATED : use video.js instead
// function loadPlayer() {
// 
// 	var videoPos = 0;
// 		
// 	var featuresInner = $$('div#features ul.content')[0];
// 	var featuresItems = $$('div#features ul.content')[0].childElements();
// 		
// 	for (var i=0; i < featuresItems.length; i++) {
// 		if (featuresItems[i].hasClassName("video")) {
// 			videoPos = i;
// 			playerId = featuresItems[i].down().readAttribute('id');
// 		}
// 	}
// 	
// 	var paginatorInner = $$('div#features div.paginator ul')[0];
// 	var paginatorItems = paginatorInner.childElements();
// 		
// 	for (var i=0; i < paginatorItems.length; i++) {
// 		if (paginatorItems[i].hasClassName("video")) {
// 			playThumbPos = i;
// 		}
// 	}
// 	
// 	
// 	/* We only have one video per productions for the moment */
// 	if (playerId != "") {
// 		
// 		if (hasFlash) {
// 			
// 			showCtrlBar();
// 			
// 			if (!firstLoaded) { 
// 				$f(playerId, { src : "/assets/swf/flowplayer.commercial-3.1.1.swf", wmode : "transparent" }, {
// 					'key': '#$144f193bf4f6293eb52',
// 				
// 					// default settings for the play button
// 					play: {
// 						opacity: 0
// 					},
// 				
// 					// don't start automcatically
// 					clip: {
// 						autoPlay: true,
// 						autoBuffering: true
// 					},
// 
// 					// disable default controls
// 					plugins: {controls: null}
// 	
// 				}).controls("ctrlbar", { duration: 0}); 
// 				
// 				$$('div#ctrlbar')[0].down().next().insert('<div class="default"></div>');
// 			
// 				firstLoaded = true;
// 			} else {
// 			}
// 		
// 		} else {
// 			featuresItems[videoPos].insert('<div id="noflash"><p>Flash 9 or greater is required to enjoy the video. <a href="http://get.adobe.com/flashplayer/" target="_blank">Click here to install it.</a></p></div>');
// 		}
// 		
// 	}
// }

function unloadPlayer(){
  hideCtrlBar();
}

// function showCtrlBar() {
// 	if (ctrlbarHidden) {
// 		$$('div#ctrlbar')[0].setStyle({zIndex: '99', bottom: '40px'}); 
// 		$$('div.ctrlbar_bg')[0].setStyle({zIndex: '98', bottom: '110px'}); 
// 		ctrlbarHidden = false;
// 	}
// }

function showCtrlBar(_id) {
	var _wrap = "#ctrlbarwrap_" + _id;
	$$(_wrap)[0].setStyle({zIndex: '99'}); 
	$$('div.ctrlbar_bg')[0].setStyle({zIndex: '98'}); 
	$$('div.default')[0].setStyle({zIndex: '90'});
}

// function hideCtrlBar() {
// 	if (!ctrlbarHidden) {
// 		$$('div#ctrlbar')[0].setStyle({zIndex: '-1', bottom: '-100000'});
// 		$$('div.ctrlbar_bg')[0].setStyle({zIndex: '-1', bottom: '-100000'});
// 		ctrlbarHidden = true;
// 	}
// }

function hideCtrlBar() {
	$$(".ctrlbarwrap").each(function(el, i) {
		$(el).setStyle({zIndex: '-1'});
	});	
	$$('div.ctrlbar_bg')[0].setStyle({zIndex: '-1'});
	$$('div.default')[0].setStyle({zIndex: '-1'});
}

function ie6fixes(){
	if ( $$('div.news ul.news_module').length > 0 ) {
		var newsInner = $$('div.news ul.news_module')[0];
		var newsItems = newsInner.childElements();
		newsItems[0].setStyle({borderRight: '1px dotted #948F8A'});
		
	}
}

function productionsClicks() {	
	$$("ul.productions_index li").each(function(li) {	
		if($(li).select("a").length > 0) {
			var href = $(li).select("a")[0].readAttribute("href");
			$(li).observe("click", function(event) {
				var el = Event.element(event);
				window.location = href;
			});
		}
	});
}

function setFooter() {
	$('footer').setStyle({position: 'absolute', bottom: 0});
}

function productionsIndexLayout() {
	if ( $$('div.productions ul.productions_index').length > 0 ) {
		var productionsInner = $$('div.productions ul.productions_index')[0];
		var productionsItems = productionsInner.childElements();
		
		for (var i=0; i < productionsItems.length; i++) {
			if ((i % 3) == 0) {
				productionsItems[i].down().down().next().setStyle({border: 'none'});
			}
		}		
	}
}

// Dynamic style for Characters
function charactersIndexLayout() {
	if ( $$('div.characters ul').length > 0 ) {
		var charactersInner = $$('div.characters ul')[0];
		var charactersItems = charactersInner.childElements();
		var nbCharactersItems = 0;


		for (var i=0; i < charactersItems.length; i++) {
			// On Characters Index page, the ul list on characters index page ends with a <li> element related for ajax loading so we exclude it
			if (charactersItems[i].readAttribute('id') != 'loading' && charactersItems[i].readAttribute('id') != 'complete') {
				nbCharactersItems ++;
			}
		}

		for (var i=0; i < nbCharactersItems; i++) {
			// On Characters Index page, the ul list on characters index page ends with a <li> element related for ajax loading so we exclude it
			if (charactersItems[i].readAttribute('id') != 'loading' && charactersItems[i].readAttribute('id') != 'complete') {
				if ((i % 6) == 0) {
					charactersItems[i].down().next().insert('<div class="border_first"></div>');
					charactersItems[i].down().next().down().setStyle({border: 'none'});
					// if it's the characters module, we make sure to only apply the style to the 4th and last character.
					if ( $$('div.characters')[0].hasClassName("module") && charactersItems.length == 4) {
						charactersItems[charactersItems.length-1].down().next().insert('<div class="border_last"></div>');
						charactersItems[charactersItems.length-1].down().next().down().setStyle({borderTop: 'none'});
					} // if not, it means we're on the characters index page. 
					else {
						if (i > 0) {
							charactersItems[i-1].down().next().insert('<div class="border_last"></div>');
							charactersItems[i-1].down().next().down().setStyle({borderTop: 'none'});
						}
					}
				} 
				if (i == (nbCharactersItems - 1) && ((nbCharactersItems % 6) == 0)) {
					charactersItems[i].down().next().insert('<div class="border_last"></div>');
					charactersItems[i].down().next().down().setStyle({borderTop: 'none'});					
				}
			}
			
			
		}
		
		
	
		$$('div.characters ul li div.image a').each(function(el,s){
			el.observe('mouseover', function(event) {
				el.up().next().down().setStyle({ backgroundColor: '#FFFFB2' });
				Event.stop(event);				
			});
			el.observe('mouseout', function(event) {
				el.up().next().down().setStyle({ backgroundColor: '#FFFFFF' });
				Event.stop(event);				
			});
		});
		
		$$('div.characters ul li span a').each(function(el,s){
			el.observe('mouseover', function(event) {
				el.setStyle({ backgroundColor: '#FFFFB2' });
				Event.stop(event);				
			});
			el.observe('mouseout', function(event) {
				el.setStyle({ backgroundColor: '#FFFFFF' });
				Event.stop(event);				
			});
		});

	}
}

function featuresSlider() {
	if (($$('div#features ul.content').length > 0) && ($$('div#features ul.content')[0].childElements().length > 0 )) {
		
		var featuresInner = $$('div#features ul.content')[0];
		var featuresItems = $$('div#features ul.content')[0].childElements();
		var currentFeaturePos = 0;
		var flag = false;
		
		var sliderInner = $$('div#features div.paginator ul')[0];
		var currentSliderCount = 6; /* 1 */
		var currentSliderPos = 0;
		var initSliderPos = currentFeaturePos;
		var slideAmount = 900; /* 150 */
		
		var relativeCurrentSliderPos = 0;
		
		
		
		if ($$('div#features')[0].hasClassName("productions")) { 
			isProduction = true;
		}
		
		for (var i=0; i < featuresItems.length; i++) {
			if (featuresItems[i].hasClassName("video")) {
				hasVideo = true;
			}
		}
		
		for (var i = featuresItems.length; i > 1; i--) {
				featuresItems[i-1].hide();
		}			


		// calculates the next position of the slider/paginator
		function calculateNextPosition(direction) {
			
			if (direction == 'next') {
				
				currentSliderPos += slideAmount;
				currentSliderCount += 6;
				
				flag = true;
			} else if (direction == 'previous') {	
					
				currentSliderPos -= slideAmount;
				currentSliderCount -= 6;
				
				flag = true;
			} else {
				
				flag = false;
			}
		}
		
		function moveNavigationSlider(ok) {
			if (ok) {
				new Effect.Move (sliderInner,{ x: -currentSliderPos, y: 0, mode: 'absolute', duration: 0.65, transition: Effect.Transitions.sinoidal });
			}
		}
		
		// Features slider
		function moveFeaturesSlider(direction) {
			// console.log("direction: " + direction );
			if (isProduction && direction == 'previous' && currentSliderCount == 6) {
				// console.log("isProduction, no previous");
				return false;
			} else if (!isProduction && direction == 'previous' && currentFeaturePos == 0) {
				// console.log("!isProduction, no previous");
				return false;
			} else if (isProduction && direction == 'next' && ( currentSliderPos == slideAmount/6 * (featuresItems.length-1) || featuresItems.length-1 <= 6 )) {
				// console.log("isProduction, no next");
				return false;
			} else if (!isProduction && direction == 'next' && currentFeaturePos ==  featuresItems.length - 1 ) {
				// console.log("!isProduction, no next");
				return false;
			} else {

				if (isProduction) {
					calculateNextPosition(direction);
					moveNavigationSlider(flag);
				}	
					
				if (direction == 'next') {
					
					if (!isProduction) {
						featuresItems[currentFeaturePos].fade({ duration: 0.5 });
						currentFeaturePos = currentFeaturePos + 1;
						featuresItems[currentFeaturePos].appear({ duration: 0.5 });
					}

				} else if (direction == 'previous') {
					if (!isProduction) {
						featuresItems[currentFeaturePos].fade({ duration: 0.5 });
						currentFeaturePos = currentFeaturePos - 1;
						featuresItems[currentFeaturePos].appear({ duration: 0.5 });
					}
				} else  {
					featuresItems[currentFeaturePos].fade({ duration: 0.5 });
					currentFeaturePos = direction;
					featuresItems[currentFeaturePos].appear({ duration: 0.5 });
				}
				
				updateFeaturesPaginator();
				updateFeaturesNextPrev();
				
				
			}
		}
		

		
		// adds pagination links
		function addnextprev() {
			for (var i=1; i <= featuresItems.length; i++) {
				if (i==1) {					
					$$('div#features div.paginator ul')[0].insert('<li class="current"><a href="#">'+i+'</a></li>');
				} else {
					$$('div#features div.paginator ul')[0].insert('<li><a href="#">'+i+'</a></li>');
				}
				
			}
		}
		
		// update the current paginator * only for HP
		function updateFeaturesPaginator() {
			
			$$('div#features div.paginator ul li.current')[0].removeClassName("current");
			$$('div#features div.paginator ul li')[currentFeaturePos].addClassName("current");

			$$('div#features div.container ul li.current')[0].removeClassName("current");
			$$('div#features div.container ul li')[currentFeaturePos].addClassName("current");
		}
		
		// update nextprev links
		function updateFeaturesNextPrev() {
			setsPreviousBtnStyle(currentFeaturePos);
			setsNextBtnStyle(currentFeaturePos);
		}
		

		
		function setsPreviousBtnStyle(currentFeaturePos) {
			
			if ( !isProduction && currentFeaturePos == 0 ) {						
				$$('div#features div.nextprev ul li.prev a')[0].setStyle({ backgroundPosition: '0 -100px', cursor: 'default' });
			} else if ( isProduction && currentSliderCount == 6 ) {						
				$$('div#features div.nextprev ul li.prev a')[0].setStyle({ backgroundPosition: '0 -150px', cursor: 'default' });
			} else {
				$$('div#features div.nextprev ul li.prev a')[0].setStyle({ backgroundPosition: '0 0', cursor: 'pointer' });
			}
		}
		
	

		function setsNextBtnStyle(currentFeaturePos) {
			
			if (!isProduction &&  currentFeaturePos == featuresItems.length - 1) {
				$$('div#features div.nextprev ul li.next a')[0].setStyle({ backgroundPosition: '0 -100px', cursor: 'default' });
			} else if ( isProduction && (currentSliderPos == slideAmount/6 * (featuresItems.length-1) || featuresItems.length-1 <= 6) ) {						
				$$('div#features div.nextprev ul li.next a')[0].setStyle({ backgroundPosition: '0 -150px', cursor: 'default' });
			} else {
				$$('div#features div.nextprev ul li.next a')[0].setStyle({ backgroundPosition: '0 0', cursor: 'pointer' });

			}
		}
		
		function setPaginatorWidth(section) {
			if (section == 'productions') {
				var pWidth = (120 + 20 ) * featuresItems.length;
			} else if (section == 'hp') {
				var pWidth = (9 + 10 ) * featuresItems.length;
			}
			$$('div#features div.paginator ul')[0].setStyle({ width: pWidth + 'px'});
		}
		
		function initializeFeatures() {
			if ( isProduction ) {
				if (featuresItems[0].hasClassName("video")) {
					var _videoId = featuresItems[0].down().readAttribute('id');
					
					showCtrlBar(_videoId);
					
				}	
				$$('div#features div.paginator ul li')[0].addClassName("current");
				$$('div#features div.container ul li')[0].addClassName("current");
				updateFeaturesNextPrev();
			} else{
				
				if (featuresItems.length > 1) {
					setPaginatorWidth('hp');				
					addnextprev();
					$$('div#features div.paginator ul li')[0].addClassName("current");
					$$('div#features div.container ul li')[0].addClassName("current");

					updateFeaturesNextPrev();
				} else {
					$$('div#features div.nextprev')[0].hide();
				}
			} 

		}
		
		initializeFeatures();	
	
		// Click controls on next/prev of features slider
		$$('div#features div.nextprev ul li.prev a')[0].observe('click', function(event) {
	        moveFeaturesSlider('previous');
	        Event.stop(event);				
		});
		$$('div#features div.nextprev ul li.next a')[0].observe('click', function(event) {
	        moveFeaturesSlider('next');
	        Event.stop(event);				
		});
		
		// add hover effect to the PREV slider button
		$$('div#features div.nextprev ul li.prev a')[0].observe('mouseover', function(event) {
			var el = Event.element(event);
			if ( !isProduction && currentFeaturePos == 0 ) { 
				el.setStyle({ backgroundPosition: '0 -100px', cursor: 'default' });
			} else if ( isProduction && currentSliderCount == 6 ) {						
				el.setStyle({ backgroundPosition: '0 -150px', cursor: 'default' });
			} else {
				el.setStyle({ backgroundPosition: '0 -50px', cursor: 'pointer' });

			}		
		});
		
		// add mouseout effect to the PREV slider button
		$$('div#features div.nextprev ul li.prev a')[0].observe('mouseout', function(event) {
			var el = Event.element(event);
			if ( !isProduction && currentFeaturePos == 0 ) { 
				el.setStyle({ backgroundPosition: '0 -100px', cursor: 'default' });
			} else if ( isProduction && currentSliderCount == 6 ) {						
				el.setStyle({ backgroundPosition: '0 -150px', cursor: 'default' });
			} else {
				el.setStyle({ backgroundPosition: '0 0', cursor: 'pointer' });

			}
		});


		// add hover effect to the NEXT slider button
		$$('div#features div.nextprev ul li.next a')[0].observe('mouseover', function(event) {
			var el = Event.element(event);
			if (!isProduction &&  currentFeaturePos == featuresItems.length - 1) {
				el.setStyle({ backgroundPosition: '0 -100px', cursor: 'default' });
			} else if ( isProduction && (currentSliderPos == slideAmount/6 * (featuresItems.length-1) || featuresItems.length-1 <= 6) ) {						
				el.setStyle({ backgroundPosition: '0 -150px', cursor: 'default' });
			} else {
				el.setStyle({ backgroundPosition: '0 -50px', cursor: 'pointer' });

			}		
		});
		
		// add mouseout effect to the NEXT slider button
		$$('div#features div.nextprev ul li.next a')[0].observe('mouseout', function(event) {
			var el = Event.element(event);	
			if (!isProduction &&  currentFeaturePos == featuresItems.length - 1) {
				el.setStyle({ backgroundPosition: '0 -100px', cursor: 'default' });
			} else if ( isProduction && (currentSliderPos == slideAmount/6 * (featuresItems.length-1) || featuresItems.length-1 <= 6 )) {						
				el.setStyle({ backgroundPosition: '0 -150px', cursor: 'default' });
			} else {
				el.setStyle({ backgroundPosition: '0 0', cursor: 'pointer' });

			}
		});
		
		// handle player_thumbs
		$$('div.paginator ul li span.play_thumb').each(function(el,s){
			el.observe('mouseover', function(event) {
				// console.log("hover");
				el.previous().setStyle({backgroundColor: '#FFF', cursor: 'pointer'});
				Event.stop(event);				
			});
			el.observe('mouseout', function(event) {
				// console.log("mouseout");
				el.previous().setStyle({backgroundColor: '', cursor: 'default'});
				Event.stop(event);				
			});
			
			el.observe('click', function(event) {
				if (!el.up().hasClassName("current")) {
					//if (isProduction && hasVideo) {
						if (el.up().hasClassName("video")) {
					        unloadPlayer();
							var _videoId= (el.previous('a').readAttribute('id')).replace('paginator_', '');
							showCtrlBar(_videoId);
						} else {
					        unloadPlayer();
						}
					//}
					moveFeaturesSlider(playThumbPos);
					$$('div.paginator ul li.current')[0].removeClassName("current");
					el.up().addClassName("current");
				}
				Event.stop(event);				
			});
			
		});
		
		// handle pagination links
		$$('div.paginator ul li a').each(function(el,s){
			el.observe('click', function(event) {
				if (!el.up().hasClassName("current")) {
					//if (isProduction && hasVideo) {
						if (el.up().hasClassName("video")) {
							unloadPlayer();
							var _videoId = (el.readAttribute('id')).replace('paginator_', '');
							showCtrlBar(_videoId);
						} else {
					        unloadPlayer();
						}
					//}
					moveFeaturesSlider(s);
					$$('div.paginator ul li.current')[0].removeClassName("current");
					el.up().addClassName("current");
				}					
				Event.stop(event);				
			});
		});
		
	} 
}