ABCapital.Footer = new Class();
ABCapital.Progress = (
	function(){

		// ADD DETECT FOR IE8 & CORRECT FOR MOOTOOLS
		if(navigator.userAgent.toLowerCase().indexOf('ipad') > 0){
			window.ipad = true;
		}
		if(navigator.userAgent.indexOf('MSIE 9') > 0){
			window.ie9 = true;
			window.ie7 = false;
		}
		if(navigator.userAgent.indexOf('MSIE 8') > 0){
			window.ie8 = true;
			window.ie7 = window.ie6 = false;
		}
		if (navigator.userAgent.indexOf("compatible; MSIE 7") > 0 || document.documentMode == 7) {
			window.ie7 = true;
			window.ie8 = window.ie6 = false;
		}

		// DYNAMICALLY CREATE HTML ELEMENTS OUTSIDE OF gs_main
		var createElements = function(){
			// CREATE EXPAND BAR
			var elink = document.createElement('a');
				elink.setAttribute('href', 'javascript:/\/');
				elink.setAttribute('id', 'expand-hd');
				elink.innerHTML = 'ABCapital Menu &nbsp;&nbsp;▼';
			var expandbar = document.createElement('div');
				expandbar.setAttribute('id','expandbar');
				expandbar.appendChild(elink);
				
			$("gs_doc").insertBefore(expandbar,$("gs_doc").firstChild);
		
		}
		
		// FIXES FOR IE
		var ie7FixBg = function(){
			$$('.background img').setStyles({
				'width' : '100%',
				'height': 'auto'
			});
			$$('#background img').setStyles({
				'width' : '100%',
				'height': 'auto'
			});
		}
		var ieFixes = function(){
			if(window.ie9){
			}			
			if(window.ie8){
				if($('flashShareThis')){ $('flashShareThis').setStyle('visibility','hidden'); }
			}
			if(window.ie7){
				$('subnav-list').setStyle('width', $('viewsubnav').getStyle('width'));
				$$('.rightnav #subnav-list li').setStyle('margin-bottom', '-3px');
				ie7FixBg();
			}
			if(window.ie6){ // ADD SUBNAV ROLLOVERS CURRENTLY CONTROLLED BY CSS
				$('viewsubnav').setStyle('width', $('subnav-list').getStyle('width')); 
				$('viewsubnav').addEvents({
					mouseover: function(){
						$('subnav-list').setStyle('display', 'block');
						$('viewstories').addClass('on');
					},
					mouseout: function(){
						$('subnav-list').setStyle('display', 'none');
						$('viewstories').removeClass('on');
					}
				});

				$$('.subnav-wrap a').each(function(el){
					el.addEvents({
						mouseover: function(){
							el.addClass('on');
						},
						mouseout: function(){
							el.removeClass('on');
						}
					});
				});
			}
		}
		
		var iPadFixes = function(){
			if(!window.ipad){return;}
			
			$$('.maincontent').setStyle('min-height', 400);
			
			// REMOVE HOVERS - TOP NAV
			$$('.rightnav #subnav-list li a:hover').setStyle('background','none');
			$$('.rightnav .subnav-wrap .subnav').setStyle('background','none');
			
			
			// REMOVE HOVERS - PODS
			for(i=0;i<$$('.content-nav li a').length;i++){
				var elm = $$('.content-nav li a')[i];
				var cls = elm.getAttribute('class').split(' ')[1];
				var bg = elm.getStyle('background-image');
				elm.setStyle('background', bg + ' no-repeat');
			}
			
			// VIDEO PAGE
			if($('flash_container')){
				$('flash_container').setStyles({
					'position' : 'fixed',
					'top' : '0px'
				});
				$('overview').setStyle('top', '45%');
				$$('#overview .page a.resumeFilm').setStyle('bottom', '25px');
			}
			
			
			
			// STORY PAGE
			var video_button = $$('#story .button')[0];
			if(video_button){
				// REMOVE HOVERS - "WATCH THE SHORT FILM"
				var video_bg = video_button.getStyle('background-image');
				video_button.setStyle('background', video_bg + ' no-repeat');
				
				// SWITCH VIDEO LINK
				/* DISABLED - FUNCTIONALITY REPLACED WITH HTML5 PLAYER
				video_button.setAttribute('href', video_button.getAttribute('ipad'));
				*/
				
				// ADDING OVERVIEW CONTENT
				/* DISABLED - FUNCTIONALITY REPLACED WITH HTML5 PLAYER 
				Overview.Page.InitPagination();
				$('ipad_learnmore').addEvent('click', function() { Overview.Show('learn'); });
				$('ipad_learnmore').setStyle('visibility', 'visible');
				$$('.resumeFilm').setStyle('visibility', 'hidden');
				*/
				
			}
			
			// VIEWSTORIES DROPDOWN FUNCTIONALITY
			$('viewstories').setAttribute('href', 'javascript:/\/void(0)'); // DISABLE LINK
			$('viewstories').addEvent('click', function(event){
				if(this.getStyle('background') == 'none'){
					this.setStyle('background', 'url(/a/pg/progress/v2/img/bg_fade.png) repeat 0 0')
				} else {
					this.setStyle('background','none');
				}		
				$('subnav-list').toggleClass('ipad');
			});			
			
		}
		var iPadBgFix = function(){
			if(!window.ipad){return;}
			$$('.background img').setStyle('min-width', 1100);
			$$('#background img').setStyle('min-width', 1100);			
		}
		
		var getDocHeight = function() {
		    return Math.max(
		        Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
		        Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
		        Math.max(document.body.clientHeight, document.documentElement.clientHeight)
		    );
		}

		// SET PAGE BACKGROUND
		var backgroundDiv;
		var setBackground = function(img,height){
			backgroundDiv = document.createElement('div');
			backgroundDiv.setAttribute('id','background');
			document.body.appendChild(backgroundDiv);
			if(height){$('background').setStyle('height', getDocHeight() - 20 + 'px');}

			var backgroundImage = document.createElement('img');
				backgroundImage.setAttribute('src',img);
				backgroundImage.setAttribute('class','bgimg');
				backgroundDiv.appendChild(backgroundImage);
				backgroundImage.setAttribute('width','100%');
				
			iPadBgFix();
			return $(backgroundDiv);
		}

		// ROTATING BACKGROUNDS
		var boxAnimation, boxCurrent, boxNext, boxTotal, h2Next, h2Current, h2Animation;
		var transitionDuration = 1500;
		var transitionInterval = 6000;
		// 6 seconds, text animates out, new text in, then image changes
		var boxTransitionOffset = 1000;
		var boxTransitionDuration = 1500;
		var slideMultiplier = 1.25;
		var repeatRotary = true;
		var boxDistance = 250;
		var initRotary = function(rotaryItems){
			boxTotal = h2Total = $$('.box').length;  // number of items
			createBackgrounds(rotaryItems);
			
			boxCurrent = 1;
			h2Current = 1;
			if(window.ie8){
				$$('.box').setStyles({
					'visibility' : 'visible'
				});
			}
			$$('.background').setOpacity(0);
			$('box' + h2Current).setStyle('top',0);
			$('background' + boxCurrent).setOpacity(1);
			h2Animation = setInterval(slideBox, transitionInterval);
			iPadBgFix();
		}
		var rotateImage = function(){
			boxNext = boxCurrent + 1;
			if(boxNext > boxTotal){ 
				if(repeatRotary){
					boxNext = 1;
				} else {
					clearInterval(boxAnimation); 
					return; 
				}
			}
			$('background'+boxCurrent).effect('opacity', {duration:transitionDuration, transition:Fx.Transitions.Cubic.easeInOut}).start(1,0);
			$('background'+boxNext).effect('opacity', {duration:transitionDuration, transition:Fx.Transitions.Cubic.easeInOut}).start(0,1);
			boxCurrent = boxNext;
		}
		var slideBox = function(){
			h2Next = h2Current + 1;
			if(h2Next > h2Total){ 
				if(repeatRotary){
					h2Next = 1;
				} else {
					clearTimeout(h2Animation); 
					return; 
				}
			}
			boxAnimation = setTimeout(rotateImage, transitionDuration);
			$('box'+h2Next).setStyle('top', boxDistance);
			$('box'+h2Current).effect('top', {duration:boxTransitionDuration, transition:Fx.Transitions.Cubic.easeInOut}).start(0,-(boxDistance));
			$('box'+h2Next).effect('top', {duration:boxTransitionDuration, transition:Fx.Transitions.Cubic.easeInOut}).start(boxDistance,0);
			$('box'+h2Current).effect('opacity', {duration:boxTransitionDuration/slideMultiplier, transition:Fx.Transitions.Cubic.easeInOut}).start(1,0);
			$('box'+h2Next).effect('opacity', {duration:boxTransitionDuration*slideMultiplier, transition:Fx.Transitions.Cubic.easeInOut}).start(0,1);
			h2Current = h2Next;
		}

		var createBackgrounds = function(backgroundArray){
			for(i=0;i<backgroundArray.length;i++){
				var backgroundDiv = document.createElement('div');
					backgroundDiv.setAttribute('id','background'+(i+1));
					$(backgroundDiv).setProperty('class','background');
					$(backgroundDiv).setStyle('width', '100%');

					var backgroundImage = document.createElement('img');
						backgroundImage.setAttribute('src',backgroundArray[i]);
						backgroundImage.setAttribute('class','bgimg');

					document.body.appendChild(backgroundDiv);
					backgroundImage.setAttribute('width','100%');

					backgroundDiv.appendChild(backgroundImage);
					backgroundImage.setAttribute('width','100%');
					$(backgroundImage).setStyle('height','auto'); 
			}
		}
	
		// SET UP TRANSITION/ANIMATION SETTINGS
		var FX_ExpandNav, FX_ExpandBtn;
		var setTransitions = function(){
			FX_ExpandNav = new Fx.Style('gs_head', 'margin-top', {duration:1000, transition:Fx.Transitions.Cubic.easeInOut});
			FX_ExpandBtn = new Fx.Style('expand-hd', 'opacity', {duration:800, transition:Fx.Transitions.Cubic.easeOut});		
		}

		// HOME PAGE EXPAND-BAR SET UP
		var isExpanded, headerTimeout, stopHomePageClick;
		var initHome = function(imgs){
			initRotary(imgs);
			if(isFirstVisit()){
				
				$('expand-hd').setStyles({
					'visibility': 'hidden',
					'opacity'	: '0'
				});
				
				stopHomePageClick = true;
				$('gs_head').setStyle('margin-top','-20px');
				isExpanded = true;
				headerTimeout = setTimeout(function(){
					stopHomePageClick = false; 
					toggleHeader('close');
				}, 3000);
				header2nd = setTimeout(function(){
					$('expand-hd').setStyle('visibility','visible');
					FX_ExpandBtn.start(0,1);

				}, 3800);
			}
		}
		
		// COOKIE THE HOME PAGE
		var cookieInterval = 1; // Interval in days for the cookie
		var cookieName = 'progressAnimation';
		var isFirstVisit = function(){
			if( Cookie.get(cookieName) == 'seen'){
				// If user has seen animation then disable
				return false;
			} else {
				//Cookie.set(cookieName,'seen');
				Cookie.set(cookieName, 'seen', {path:'/', duration: cookieInterval});
				return true;
			}
		}
		
		// TOGGLE EXPAND-BAR HEADER ON/OFF
		var toggleHeader = function(command){
			if(headerTimeout){clearTimeout(headerTimeout); clearTimeout(header2nd);}
			if(command == 'close'){
				if(!isExpanded){return;}
				heighttogo = -150;
				isExpanded = false;
				setTimeout(function(){FX_ExpandBtn.start(0,1);}, 1000);
			} else {
				isExpanded = true;
				$("gs_head").setStyle('display', 'block');
				heighttogo = -20;
				setTimeout(function(){FX_ExpandBtn.start(1,0);}, 1000);
			}
			FX_ExpandNav.start(heighttogo);	
		}
		
		var handleDocumentClick = function(e){
			if(!isExpanded || stopHomePageClick){ return;}
			target = e.target || event.srcElement;
			elm = target;
			while($(elm).getTag() != 'html'){
				elm = $(elm).getParent();
				if($(elm).id == 'expandbar' || $(elm).id == 'gs_head'){ return;}
			}
			toggleHeader('close');
		}

		var assignClickHandlers = function(){
		    // EXPAND HEADER
			$("expand-hd").addEvent('click', function(){
				toggleHeader('open');
		    });

			// CLOSE HEADER (IF OPEN)
			$(document).addEvent('click', handleDocumentClick);
			if(window.ipad){
				$('gs_main').addEvent('mousedown', handleDocumentClick);
				$('gs_main').setStyle('-webkit-tap-highlight-color', 'rgba(0,0,0,0)');
				$('gs_main').getChildren().each(function(el){
					el.setStyle('-webkit-tap-highlight-color', 'rgba(10%,10%,10%,.5)');  //adjust to proper color
				})
				
			}

			// ABOUT PAGE
			$$('#about_blurbs li a').each(function(el,idx){
				el.getChildren('a img').addEvents({
					mouseover: function(){
						if(About.blurbInMotion){clearInterval(About.blurbInMotion);}
						About.blurbShow(idx);
					},
					mouseout: function(){
					/*	console.log(About.blurbCurrent);
						if(idx===About.blurbCurrent) return;
						this.src = this.src.replace('_on', '_off');
					*/
					}
				});
			});	

			
			// TOPNAV
			if(!window.ipad){
				$('viewsubnav').addEvents({
					mouseover: function(){
						$('subnav-list').setStyle('display', 'block');
						$('viewstories').addClass('on');
					},
					mouseout: function(){
						$('subnav-list').setStyle('display', 'none');
						$('viewstories').removeClass('on');
					}
				});
			}
			
			// OVERVIEW
			if($('closeOverview')){
				Overview.Page.InitPagination();
				$('closeOverview').addEvent('click', function(){
					Overview.Hide();
				});
			}
			
			// STORY PAGE MODS
			if($('read_more') != null){
				$('read_more').addEvent('click', function(){
					Overview.Show('story');
				});
				$$('.resumeFilm').addEvent('click', function(){
					Overview.Hide();
				});
				$$('.resumeFilm').each(function(el){
//					el.setStyle('background', $('watchfilm').getStyle('background-image'));
					el.addClass('watchfilmstory');
//					el.removeClass('resumeFilm')
					el.addEvent('click',function(e){
						location.href = $('watchfilm').getAttribute('href');
						e.preventDefault();
						e.stop();
						
					});
				}); 
				$('overview').setStyle('position', 'fixed');
			
			}	

		}

		// INITIALIZE VIDEO PAGE	
		var initVideoPage = function(){
			// PAGE-SPECIFIC CSS MODIFIERS
			$('expand-hd').setStyle('position','absolute');
			$('expand-hd').setStyle('right','10px');
		
			// ASSIGN OVERLAY CLICK HANDLERS
			$$('.resumeFilm').addEvent('click', function(){
				Overview.Hide();
			});
			$("replayButton").addEvent('click', function(){
				EndFrame.Hide();
			});
			
//			Overview.Page.InitPagination();
			
			// SHARE THIS
			addthis.addEventListener('addthis.menu.open', Share.EventHandler);
			addthis.addEventListener('addthis.menu.close', Share.EventHandler);
			addthis.addEventListener('addthis.menu.share', Share.EventHandler);
			
			
			// ANALYTICS CALLS
			addthis.addEventListener('addthis.menu.open', function(){ try { gsAnalytics.handleInitiateShare(true); } catch (e){} });

			$$("#end_frame a.more").each(function(a){
				$(a).addEvent('click', function(){
					try {
						gsAnalytics.handleProgressLearnMore(this, $(this).getText());
					} catch (e){}
				});
			});

		}
	
		// FLASH FUNCTIONALITY
		var Flash = Object();
			Flash.Active = false;
			Flash.Container = 'flash_container';
			Flash.InnerLayer = 'flashMovie';
		
			Flash.Embed = function(datafile){
				var so = new SWFObject("video.swf", Flash.InnerLayer, "100%", "100%", "10.0.0", "#000000");
				so.addParam("wmode", "transparent");
				so.addVariable("configUrl", "config.xml");
				so.addVariable("xmlUrl", datafile);
				
				if(Analytics.account){
					so.addVariable('account', Analytics.account);
					so.addVariable('pagename', Analytics.pagename);
					so.addVariable('pageurl', Analytics.pageurl);
					so.addVariable('movieid', Analytics.movieid);
				}
				
				if (so.write(Flash.Container)) {
					window.addEvent('resize', Flash.ReSize);
					Flash.Active = true;
				} 				
				Flash.ReSize();

				/* ADDED FOR OVERVIEW */
				if(window.innerWidth < 930){
					$('overview').setStyles({
						'left' : '10px',
						'top'  : '20px',
						'margin' : '0'
					});
				} else {
					$('overview').setStyles({
						'left' : '50%',
						'top'  : '50%',
						'margin' : '-250px 0 0 -480px'
					});				
				}
				
				window.addEvent('resize', Flash.ReSize);
				return Flash.Active;
			}
			Flash.ReSize = function(){
				var el = document.getElementById(Flash.Container);
				h = document.getElementsByTagName("body")[0].clientHeight + 30;
				w = document.getElementsByTagName("body")[0].clientWidth;
				var footer = document.getElementById("gs_footer");
				var topper = document.getElementById('expandbar');
				el.style.width = "100%";
				el.style.height = footer.offsetTop - (footer.clientHeight-2) + "px";
			}
			Flash.GetMovie = function(movieName){
				var isIE = navigator.appName.indexOf("Microsoft") != -1;
				return (isIE) ? window[movieName] : document[movieName];			
			}
			Flash.SendCommand = function(command){
				if(HTML5.Active || window.ipad){return;}
				Flash.GetMovie(Flash.InnerLayer).sendToActionScript(command);
			}

		var Share = Object();
			Share.Open = function(){
				if(window.ie8){
					$('flashShareButton').click();
				} else {
					$('flashShareButton').fireEvent('click');
				}
			}
			Share.Close = function(){
				if(EndFrame.On) return;
				if(Flash.Active) {
					Flash.SendCommand('brighten');
				} else if(HTML5.Active || window.ipad){
					HTML5.playVideo();							
				}			
			}
			Share.EventHandler = function(evt) {
//				console.log(evt)
			    switch (evt.type) {
			        case "addthis.menu.open":
//		            console.log('menu opened; surface=' + evt.data.pane);
						if(EndFrame.On) return;
						if(!window.ie8 && Flash.Active){ Flash.SendCommand('dim'); } // because IE8 doesn't hear flash, has to self-trigger the dim 
						if(window.ipad){
						//	HTML5.pauseVideo(true);						
						}
			            break;
			        case "addthis.menu.close":
//			            console.log('menu closed; surface=' + evt.data.pane);
						Share.Close();
			            break;
			        case "addthis.menu.share":
//			            console.log('user shared to ' + evt.data.service);
			            break;
			        default:
//			            console.log('received an unexpected event', evt);
			    }

			    if (evt.type == 'addthis.menu.share') { 
			//        alert(typeof(evt.data)); // evt.data is an object hash containing all event data
			//       alert(evt.data.service); // evt.data.service is specific to the "addthis.menu.share" event
			    }
			}
			
			
		// VIDEO OVERVIEW LAYER
		var Overview = Object();
			Overview.On = false;
			Overview.Show = function(clicked){
				Overview.On = true;
				if(clicked == 'learn'){
					// ANALYTICS CALL
					try { gsAnalytics.handleProgressLearnMore(this, ABCapital.Progress.Analytics.movieid); } catch (e){}
				} else if (clicked == 'pause'){
					// ANALYTICS CALL
					try { gsAnalytics.handleProgressPause(this, ABCapital.Progress.Analytics.movieid); } catch (e){}									
				} else if (clicked == 'story'){
					try { gsAnalytics.handleProgressLearnMore(this, ABCapital.Progress.Analytics.movieid); } catch (e){}
				}
				if(window.ipad){
				//	$('video').pause();
				}
				$('overview').setStyle('display', 'block');
				$('fade-layer').setStyle('display','block');
				Overview.Page.Go(1);
			}
			Overview.Hide = function(){
				Overview.On = false;
				$('overview').setStyle('display', 'none');
				$('fade-layer').setStyle('display','none');
				if($('story') != null){ // If Story page
					return;
				}
				if(Flash.Active){
					Flash.SendCommand('brighten');
				} else {
					HTML5.playVideo();
				}
			}
	
			// OVERVIEW PAGINATION
			Overview.Page = Object();
				Overview.Page.Current = 1;
				Overview.Page.TotalCount = 1;
				Overview.Page.InitPagination = function(){
					Overview.Page.TotalCount = $$('.pagination ul li').length;
				         $$('.pagination ul li a').each(function(el){
				                  el.removeEvents('click');
				                  if(el.innerHTML == "Next"){
				                        el.addEvent('click', function(){
				                              Overview.Page.Next();
			         	               });
			         	         } else if(el.innerHTML == "Prev"){
			         	               el.addEvent('click', function(){
			         	                     Overview.Page.Prev();
			         	               });
			         	         } else {
			         	               el.addEvent('click', function(){
			         	                     Overview.Page.Go( this.innerHTML );
			                  	      });
			         	         }
			     	});
				
				}
				Overview.Page.Go = function(x){
					x = parseInt(x);
					$$('.page').setStyle('display','none');
					$$('.pagination ul li').removeClass('on');
					$("page"+x).setStyle('display','block');
					Overview.Page.Current = x;
					$$('.pagination ul li')[Overview.Page.Current].addClass('on');
					if(x==1) {
						Overview.Page.UpdatePagination('previous','hidden');
					} else {
						Overview.Page.UpdatePagination('previous','visible');
					}	
					if(x==(Overview.Page.TotalCount-2)){
						Overview.Page.UpdatePagination('next','hidden');
					} else {
						Overview.Page.UpdatePagination('next','visible');
					}
					
					// ANALYTICS CALL
					try { gsAnalytics.handleProgressPaginate(this, ABCapital.Progress.Analytics.movieid + " p." + x); } catch (e){}
						
				}
				Overview.Page.Next = function(){
					if(Overview.Page.Current < (Overview.Page.TotalCount-2)){
						Overview.Page.Go(Overview.Page.Current+1);
					}
				}
				Overview.Page.Prev = function(){
					if(Overview.Page.Current > 1){
						Overview.Page.Go(Overview.Page.Current-1);
					}
				}
				Overview.Page.UpdatePagination = function(elm,what){
					$$('.pagination ul li.' + elm).setStyle('visibility', what);
				}


		// VIDEO END FRAME
		var EndFrame = Object();
			EndFrame.On = false;
			EndFrame.Show = function(){
				if(!window.ipad){
					// BACKGROUND SHOW FUNCTION
					if(!HTML5.backgroundCreated){
						setBackground(Video.EndFrameBackground);
						$('background').setStyle('z-index',1);
					} else {
						$('background').setStyle('visibility','visible');
					}
					HTML5.backgroundCreated = true;
				}
				
				$('end_frame').setStyle('display','block');
				Flash.ReSize();
				EndFrame.On = true;
				$('fade-layer').setStyle('display','block');
			}
			EndFrame.Hide = function(){
				EndFrame.On = false;
				if(!window.ipad) $('background').setStyle('visibility','hidden');
				$('end_frame').setStyle('display','none');
				$('fade-layer').setStyle('display','none');				
				if(Flash.Active){
					Flash.ReSize();
					Flash.SendCommand('brighten');		
					Flash.SendCommand('play');
				} else {
					HTML5.loadStart(0);
				}
			}

		// ABOUT PAGE ROLLOVERS
		var About = Object();
			About.blurbCurrent = false;
			About.blurbInterval = 3000;
			About.blurbInMotion = false; // setInterval
			About.blurbShow = function(idx){
				$$('#about_blurbs li a').removeClass('on');
				$$('#about_blurbs li a')[idx].addClass('on');
				$$('#about_blurbs #blurbs p').setStyle('visibility', 'hidden');
				$$('#about_blurbs #blurbs p')[idx].setStyle('visibility', 'visible');
				$$('#about_blurbs li a img').each(function(el,imgidx){
					if(imgidx==idx){
						el.src = el.src.replace('_off', '_on');
					} else {
						el.src = el.src.replace('_on', '_off');
					}
				});
				About.blurbCurrent = idx;
			}
			About.blurbAutoplay = function(){
				if(About.blurbCurrent == About.blurbTotal || !About.blurbCurrent) About.blurbCurrent = 0;
				About.blurbShow(About.blurbCurrent);
				About.blurbCurrent++;
			}
			About.blurbInit = function(){
				About.blurbTotal = $$('#about_blurbs li a').length;
				About.blurbShow(0);
				About.blurbInMotion = setInterval(About.blurbAutoplay, About.blurbInterval);
			}

		
		// ONLOAD
		window.addEvent('domready', function(){
			createElements();
			setTransitions();
			assignClickHandlers();
			setTimeout(function(){ieFixes();}, 100);
			iPadFixes();
			if($('flash_container') != null){
				initVideoPage();
			}
			
		});


		var Video = Object();
			Video.init = function(xmlfile, html5_video, html5_cc_video, html5bg){
				if(!DebugOn && Flash.Embed(xmlfile)){
					// Flash was embedded, do nothing further
				} else if(window.ipad || DebugOn){
					HTML5.videoFile = html5_video;
					HTML5.videoFileCC = html5_cc_video;
					HTML5.init();
				} else {
					$('get_flash').setStyle('display', 'block');
				}
				$('end_frame').setStyle('z-index', 5000);
				Video.EndFrameBackground = html5bg;
			}



/***************************************************************************************************/
/***  HTML5 Video   ********************************************************************************/
/***************************************************************************************************/


		var HTML5 = Object();
			HTML5.video;
			HTML5.videoFile;
			HTML5.videoFileCC;
			HTML5.onCC;
			HTML5.sources;
			HTML5.Active = false;
			HTML5.loadStartFirstRun = false;
			HTML5.controls;
			HTML5.playControl;
			HTML5.progressControl;
			HTML5.progressHolder;
			HTML5.playProgressBar;
			HTML5.playProgressInterval;
			HTML5.currentTimeDisplay;
			HTML5.syncTime;
			HTML5.durationDisplay;
			HTML5.volumeControl;
			HTML5.volumeDisplay;
//			HTML5.fullScreenControl;
			HTML5.callout;
			HTML5.calloutIsVisible;
			HTML5.calloutDuration;
//			HTML5.endFrame;
//			HTML5.overview;

			HTML5.videoWasPlaying;
			HTML5.videoIsFullScreen;
			HTML5.videoOrigWidth;
			HTML5.videoOrigHeight;
//			HTML5.videoViewMode = 'quad';

			HTML5.showController = function() {
			    HTML5.controls.style.display = "block";
			}

			HTML5.positionController = function() {
			//    HTML5.controls.style.top = (HTML5.video.offsetHeight - 20/* - HTML5.controls.offsetHeight*/) + "px";
			//    HTML5.controls.style.left = "0px";
			    HTML5.controls.style.width = '100%'//$('video').offsetWidth + "px";
			    HTML5.sizeProgressBar();
			}

			HTML5.sizeProgressBar = function() {
			    HTML5.progressControl.style.width = (HTML5.controls.offsetWidth - 279) + "px";
			    HTML5.progressHolder.style.width = (HTML5.progressControl.offsetWidth) + "px";
			}

			HTML5.playVideo = function() {
				Analytics.TrackPlay();
				Debug('playVideo()')
			    $('video').play();
			    HTML5.playControl.className = "pause control";
			    HTML5.trackPlayProgress();
				// ANALYTICS
				try { gsAnalytics.handleProgressPlay(this, ABCapital.Progress.Analytics.movieid); } catch (e){}
			}

			HTML5.pauseVideo = function(which) {
				Analytics.TrackStop();
			    $('video').pause();
			    HTML5.playControl.className = "play control";
			    HTML5.stopTrackingPlayProgress();
			}

			HTML5.trackPlayProgress = function() {
			    HTML5.playProgressInterval = setInterval(HTML5.updatePlayProgress, 500);
			}

			HTML5.stopTrackingPlayProgress = function() {
			    clearInterval(HTML5.playProgressInterval);
			}

			HTML5.updatePlayProgress = function() {
			    HTML5.playProgressBar.style.width = (($('video').currentTime / $('video').duration) * (HTML5.progressHolder.offsetWidth - 2)) + "px";
			    HTML5.updateTimeDisplay();

			}
			HTML5.updateTimeDisplay = function() {
//			    HTML5.syncTime = $('video').currentTime;
			    HTML5.currentTimeDisplay.innerHTML = HTML5.formatTime($('video').currentTime);
			    if ($('video').duration) HTML5.durationDisplay.innerHTML = HTML5.formatTime($('video').duration);
				Analytics.mediaOffset = parseInt($('video').currentTime);
			}

			HTML5.formatTime = function(seconds) {
			    seconds = Math.round(seconds);
			    minutes = Math.floor(seconds / 60);
			    minutes = (minutes >= 10) ? minutes : "0" + minutes;
			    seconds = Math.floor(seconds % 60);
			    seconds = (seconds >= 10) ? seconds : "0" + seconds;
			    return minutes + ":" + seconds;
			}
			HTML5.setPlayProgress = function(clickX) {
			    var newPercent = Math.max(0, Math.min(1, (clickX - HTML5.findPosX(HTML5.progressHolder)) / HTML5.progressHolder.offsetWidth));
			    $('video').currentTime = newPercent * $('video').duration;
			    HTML5.playProgressBar.style.width = newPercent * (HTML5.progressHolder.offsetWidth - 2) + "px";
			    HTML5.updateTimeDisplay();
			}
			HTML5.blockTextSelection = function() {
			    document.body.focus();
			    document.onselectstart = function() { return false; };
			}

			HTML5.unblockTextSelection = function() {
			    document.onselectstart = function () { return true; };
			}

			HTML5.findPosX = function(obj) {
			    var curleft = obj.offsetLeft;
			    while (obj = obj.offsetParent) {
			        curleft += obj.offsetLeft;
			    }
			    return curleft;
			}

			HTML5.fullScreenOn = function() {
			    HTML5.videoIsFullScreen = true;
			    HTML5.videoOrigWidth = $('video').offsetWidth;
			    HTML5.videoOrigHeight = $('video').offsetHeight;

//			    $('video').style.width = window.innerWidth/* -16 */ +"px";
			    $('video').setStyles({
					'height'	: window.innerHeight - 33,
					'width'		:1048,
					'top'		: 0,
					'left'		: -20
//					'width'		: 'auto'
				});//(window.innerHeight/*controls.offsetHeight*/) + "px";
			//	Debug(HTML5.controls.offsetHeight)
			//    $('video').style.position = "fixed";
			//setTimeout('alert("width:" + $('video').style.width + ", height:"+$('video').style.height)',3000);
			//    $('video').style.left = -100;
			//    $('video_box').setStyle('top', '-40px');
			//$('flash_container').setStyle('top','-20px')
			//    controls.style.position = "fixed";
			//$('HTML5.video_box').setStyle('left',-100);
			//$('HTML5.video_box').setStyle('top',-60);
			    HTML5.positionController();

			    //	fullScreenControl.className = "fs-active control";
			}
			HTML5.setVolume = function() {
				if($('video').volume > 0 && $('video').volume < 1){
					$('video').volume = 1
				}
				if($('video').volume == 1){
					newVol = 0;
					$('volume').removeClass("on");
				} else {
					$('volume').addClass("on");
					newVol = 1;
				}
				$('video').volume = newVol;

			}
			
			HTML5.playClicked = function(){
				Debug('play clicked')
			        if ($('video').paused) {
						if(!HTML5.loadStartFirstRun){
							HTML5.loadStart();
						} else {
			            	HTML5.playVideo();
		    			}
			    	} else {
			            HTML5.pauseVideo('pause');
						Overview.Show('pause');						
			        }
			}
			HTML5.init = function() {
				Debug('HTML5.init')
				$('video_box').setStyle('display','block');
//			    HTML5.video = document.getElementById("video");
			    HTML5.sources = $('video').getElementsByTagName('source');
			    HTML5.controls = document.getElementById("controls");
			    HTML5.playControl = document.getElementById("play");
			    HTML5.progressControl = document.getElementById("progress");
			    HTML5.progressHolder = document.getElementById("progress_box");
			    HTML5.playProgressBar = document.getElementById("play_progress");
			    HTML5.currentTimeDisplay = document.getElementById("current_time_display");
			    HTML5.durationDisplay = document.getElementById("duration_display");
			    HTML5.showController();
			    HTML5.positionController();
			    HTML5.sizeProgressBar();
			    HTML5.updateTimeDisplay();
			    HTML5.fullScreenOn();
				HTML5.loadStartDelay = (window.ipad) ? 1000 : 100;
			    
				// CONTROLS
			    $('play').addEventListener("click", function () {
					HTML5.playClicked();
			    }, true);
				$('learnmore').addEventListener('click', function () {
			        if ($('video').paused) {
			            HTML5.playVideo();
			        } else {
			            HTML5.pauseVideo();
						Overview.Show('learn');
			        }
			    }, false);
				$('cc').addEventListener('click', function(){
					Debug('cc clicked')
					HTML5.swapCC();
				}, false);

			    HTML5.progressHolder.addEventListener("mousedown", function () {  //ontouchstart, ontouchmove
			        HTML5.stopTrackingPlayProgress();
			        if ($('video').paused) {
			            HTML5.videoWasPlaying = false;
			        } else {
			            HTML5.videoWasPlaying = true;
			            $('video').pause();
			        }

			        HTML5.blockTextSelection();
			        document.onmousemove = function (e) {
			            HTML5.setPlayProgress(e.pageX);
			        }

			        document.onmouseup = function () {
			            HTML5.unblockTextSelection();
			            document.onmousemove = null;
			            document.onmouseup = null;
			            if (HTML5.videoWasPlaying) {
			                $('video').play();
			                HTML5.trackPlayProgress();
			            }
			        }
			    }, true);

			    window.addEventListener("resize", function () {
			        HTML5.fullScreenOn()
			    }, true)

			    HTML5.progressHolder.addEventListener("mouseup", function (e) {
			        HTML5.setPlayProgress(e.pageX);
			    }, true);

				// LOAD VIDEOS
				if(window.ipad){
					$('video').src = HTML5.videoFile;
				} else { 
					/* not needed for this iteration, only for testing
					HTML5.sources[0].src = "/video/ipadtest.m4v"; */
					HTML5.sources[1].src = "/video/single.ogg" 					
				}
				$('video').load();
				
				//if HTML5, then hide flash share button
				if($('flashShareThis')){ $('flashShareThis').setStyle('visibility','hidden'); }

				// VIDEO EVENT LISTENERS
				$('video').addEventListener('ended', function(){
					HTML5.videoEnded();
				}, false);			
				$('video').addEventListener('canplay', function(){
					setTimeout(function(){HTML5.loadStart()},HTML5.loadStartDelay);
				}, false);
				$('video').addEventListener('canplaythrough', function(){
					setTimeout(function(){HTML5.loadStart()},HTML5.loadStartDelay);
				}, false);
/*
			    HTML5.volumeControl.addEventListener("click", function (e) {
			        HTML5.setVolume(e.pageX);
			    }, true);

				$('video').addEventListener('mousedown', function(){
					console.log('click')
					HTML5.playVideo();
				});
*/
				if(window.ipad){ // START GRAPHIC
					$('html5start').setStyle('visibility', 'visible');
					$('html5startlink').addEventListener('click', function(e){
						HTML5.playClicked();
						e.preventDefault();
					});
				}
				
			}
				
			HTML5.videoEnded = function(){
				Analytics.TrackEnd();
				Debug('end frame show')
				EndFrame.Show();
			}

			HTML5.loadStart = function(time) {
				Debug('video paused: ' + $('video').paused + " | " + 'Overview.On: ' + Overview.On + " | video ended: " + $('video').ended + " | HTML5.Active="+HTML5.Active)
				if(	HTML5.loadStartFirstRun && 
					( (!$('video').paused && !$('video').ended ) 
					  || Overview.On) 
					){
					Debug('loadStart() -> returning '); 
					return;
				}
				Analytics.mediaLength = $('video').duration;
				if(!HTML5.loadStartFirstRun){Analytics.TrackStart();}				
				HTML5.loadStartFirstRun = true;
				$('html5start').setStyle('visibility', 'hidden');
				if(time===0){HTML5.xTime = 0;}
				Debug('loadStart()');
				$$('.share').empty();  // fix for addthis auto-embedding its images in this view.
			    HTML5.updateTimeDisplay();
				if(HTML5.xTime != null && time != 0){
					Debug('HTML5.xTime:' + HTML5.xTime);
					$('video').currentTime = HTML5.xTime;
					Debug('currentTime: ' + $('video').currentTime)
					HTML5.playVideo();
					$('video').play();
				} else {
					HTML5.playVideo();
				}
				HTML5.updatePlayProgress();
				HTML5.Active = true;
			}

			HTML5.swapCC = function() {
				var file_to_swap;
			    HTML5.pauseVideo();
				HTML5.xTime = $('video').currentTime.toFixed(1);
				Debug('HTML5.xTime: ' + HTML5.xTime);
				if(HTML5.onCC == true){
					file_to_swap = HTML5.videoFile;
					HTML5.onCC = false;
					$('cc').removeClass('on');
				} else {
					file_to_swap = HTML5.videoFileCC;
					HTML5.onCC = true;
					$('cc').addClass('on');
				}
				Debug("file_to_swap: "+file_to_swap);
				
				
				if(window.ipad){
					$('video').src = file_to_swap;//"http://www.abcapital.it/index.htm";
				} else { 
					// not needed for this iteration, only for testing
					//HTML5.sources[0].src = "ipadtest.m4v";
					//HTML5.sources[1].src = "single.ogg"
					$('video').src = "single.ogg";
				}
			    $('video').load();
			}




			var Analytics = Object();
				Analytics.account, Analytics.pagename, Analytics.pageurl, Analytics.movieid, Analytics.mediaLength, Analytics.mediaOffset;
				Analytics.mediaPlayerName = (window.ipad) ? 'iPad' : 'HTML5';
				
				Analytics.TrackStart = function(){
					Debug('Analytics.TrackStart ' + Analytics.mediaOffset);
					s.Media.trackSeconds=10;
					s.Media.open(Analytics.movieid,Analytics.mediaLength,Analytics.mediaPlayerName);
				}
				Analytics.TrackPlay = function(){
					Debug('Analytics.TrackPlay ' + Analytics.mediaOffset);
					s.Media.play(Analytics.movieid, Analytics.mediaOffset);
					s.Media.track(Analytics.movieid);
				}
				Analytics.TrackStop = function(){
					s.Media.stop(Analytics.movieid, Analytics.mediaOffset);
					s.Media.track(Analytics.movieid);
					Debug('Analytics.TrackStop ' + Analytics.mediaOffset);
				}
				Analytics.TrackEnd = function(){
					Debug('Analytics.TrackEnd ' + Analytics.mediaOffset);
					s.Media.track(Analytics.movieid);
					s.Media.close(Analytics.movieid);
				}

/**  ***********************************************************************************************  **/
/**  ** DEBUG **************************************************************************************  **/
/**  ***********************************************************************************************  **/
			var DebugOn = false;
			var DebugOn = (document.URL.toLowerCase().indexOf('debug') > 0) ? true : false;
			var Debug = function(what){
				if(DebugOn && $('debugger') != null){
					data = formatTime(new Date(), '%H:%m:%s') + ": " + what + "<br>";
					value = data + $('debugger').innerHTML;
					$('debugger').innerHTML = value;
					console.debug(data)
				}
			}

				window.addEvent('domready',function(){
					
					if(DebugOn){
						var divtag = document.createElement('div');
						divtag.setAttribute('id','debugger');
						document.body.appendChild(divtag);

						$('debugger').setStyles({
							'position':'fixed',
							'bottom':'57px',
							'left': '0px',
							'width':'100%',
							'height':'200px',
							'overflow':'scroll',
							'background' : '#000',
							'color' : '#fff',
							'opacity':.75,
							'z-index':500,
							'visibility': 'visible'
						});
				
						if($('video')!= null){
							Debug('debug events assigned')
							$('video').addEventListener('canplay', function(){
								Debug('EVENT: canplay');
							}, false);
							$('video').addEventListener('canplaythrough', function(){
								Debug('EVENT: canplaythrough - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('ended', function(){
								Debug('EVENT: ended - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('loadeddata', function(){
								Debug('EVENT: loadeddata - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('stalled', function(){
								Debug('EVENT: stalled - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('waiting', function(){
								Debug('EVENT: waiting - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('suspend', function(){
								Debug('EVENT: suspend - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('seeking', function(){
								Debug('EVENT: seeking');
							}, false);
							$('video').addEventListener('seeked', function(){
								Debug('EVENT: seeked');
								Analytics.TrackPlay();
							}, false);
							$('video').addEventListener('playing', function(){
								Debug('EVENT: playing - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('pause', function(){
								Debug('EVENT: pause - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
							$('video').addEventListener('abort', function(){
								Debug('EVENT: ABORT - r' + $('video').readyState + " | n"+$('video').networkState);
							}, false);
						}
				
					}
				});
			
	
			var formatTime = function(date,fmt){
			    function pad(value) {
			        return (value.toString().length < 2) ? '0' + value : value;
			    }
			    return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) {
			        switch (fmtCode) {
			        case 'Y':
			            return date.getUTCFullYear();
			        case 'M':
			            return pad(date.getUTCMonth() + 1);
			        case 'd':
			            return pad(date.getUTCDate());
			        case 'H':
			            return pad(date.getUTCHours());
			        case 'm':
			            return pad(date.getUTCMinutes());
			        case 's':
			            return pad(date.getUTCSeconds());
			        default:
			            throw new Error('Unsupported format code: ' + fmtCode);
			        }
			    });
				
			}
			

			window.addEvent('domready', function(){
				Debug('domready')
			})

/**  ***********************************************************************************************  **/
/**  ***********************************************************************************************  **/
/**  ***********************************************************************************************  **/
	
	
		// FUNCTION RETURNS...
		return {
			initHome: initHome,
			setBackground: setBackground,
			Overview: Overview,
			EndFrame: EndFrame,
			Flash: Flash,
			Share: Share,
			About: About,
			Analytics: Analytics,
			HTML5 : HTML5,
			Video : Video,
			FlashClick: function(){
				toggleHeadher('close');
			}
		}
	
	}
)();



