var gSTime=0, gPeriodical='',gInterval=0,gSsVideoSource='', aMEQsParam = new Array(),oVideoSources,iCurrentVideo,gSliderStart=1;
var gSDomain = "";

var amEVideo = {
	articles: {
		getAssociatedArticles: function(iVideoId){
		},
		XML: function(){
			var oXML = new Ajax("/webservice/articleList.php?videoid="+iVideoId, {
				method: "get",
				onSuccess: function(sRequest){
					//alert(iVideoId);
					//amEVideo.XML.videoSource(sRequest);
				}
			}).request();
		}
	},
	buildSlider: function(){

		var oCurrentDiv=0,sCurrentPos=0,i=0, iDivNotFound=1;
		if(typeof($('videoTopList'))=="undefined"){return true;};
		var oVideoTopList = $('videoTopList').getChildren(), oUl = $('videoTopList').getElements('ul'), iLi = oUl[0].getChildren().length, iLiLength = 167;
		var iCurrentPosition = 0;
		var iOriginalPos = 0, iCurrentMargin='0',iLengthMove = 770;
		oAnchorControls = [$('vLeftControl'),$('vRightControl')];

		//Determine Total Positions
		var endEntered=0, beginningEntered=0;
		var iTotalPosition =  Math.floor(iLi/5);
		iTotalPosition = (iLi%5==0) ? iTotalPosition-1 : iTotalPosition; //if full set assume no need to increment

		/* Initialize Controls */
		$('vLeftControl').fade(0.4);
		beginningEntered=1;

		oAnchorControls.each(function(oAnchor){
			oAnchor.addEvent('mouseover', function(e){
					if(this.id == 'vLeftControl' && !beginningEntered || this.id == 'vRightControl' && !endEntered){
/*
						var highlightButton = new Fx.Tween(this);
						highlightButton.set('border', '1px solid yellow');
*/
						this.fade(0.8);
					}
			});
			oAnchor.addEvent('mouseout', function(e){
					if(this.id == 'vLeftControl' && !beginningEntered || this.id == 'vRightControl' && !endEntered){
						this.fade(1);
					}
/*
					var removeHighlight = new Fx.Tween(this);
					removeHighlight.set('border', '1px solid #fff;');
*/
			});
			oAnchor.addEvent('click', function(e){
				if(oAnchor == oAnchorControls[0]){ //Previous Button
					if(endEntered){ //restore button
						$('vRightControl').fade(1);
						endEntered=0;
					}
					if(iCurrentPosition == 0){ //init
						return true;
					}
					iCurrentPosition=iCurrentPosition-1; //Set Pointer (Previous)
					iOriginalPos = iCurrentMargin, iCurrentMargin=iCurrentMargin+iLengthMove;
					var marginChange = new Fx.Tween(oUl[0]);
					marginChange.start('margin-left',iOriginalPos, iCurrentMargin+'px');
					if(iCurrentPosition== 0){ //Are we back to the beginning?
						beginningEntered=1;
						this.fade(0.4);
					} else{
						this.fade(1);
					}
				}	else{ //Next Button
					if(beginningEntered){
						$('vLeftControl').fade(1);
						beginningEntered=0;
					}

					if(iCurrentPosition == (iTotalPosition)){ //tried to click on end of frame
						return true;
					} else{
						iOriginalPos = iCurrentMargin;
					}
					iCurrentPosition=iCurrentPosition+1; //Set Pointer (Next)
					iCurrentMargin=iCurrentMargin-iLengthMove;
					var marginChange = new Fx.Tween(oUl[0]);
					marginChange.start('margin-left',iOriginalPos, iCurrentMargin+'px');
					if(iCurrentPosition == (iTotalPosition)){ //Are we nearing the end?
						endEntered=1;
						this.fade(0.4);
					} else{
						this.fade(1);
					}
				}
			});
		});

		/*
		1. Slide if hash is detected
		2. Highlight selected item
		*/
		
		if((window.location.hash.substring(1)*1)!=0){
			var iCurrentClicked = window.location.hash.substring(1)*1;
			iCurrentClicked = oVideoOrder[iCurrentClicked];
			//$$('#videoTopList ul.videoSelectList li')[iCurrentClicked].getElement('div').setStyle('border','1px solid #cc6600');
			//$$('#videoTopList ul.videoSelectList li')[iCurrentClicked].getElement('h3').getElement('a').setStyle('color','#cc6600');
			$$('#videoTopList ul.videoSelectList li')[iCurrentClicked].getElements('img')[0].fade(0.5);
			iClickedPosition = Math.floor(iCurrentClicked/5);
			iOriginalPos = iClickedPosition;
			iCurrentPosition=iClickedPosition-1; //Set Pointer (Next)
			iCurrentMargin = -1*(iLengthMove*iCurrentPosition);
			iCurrentMargin=iCurrentMargin-iLengthMove;
			var marginChange = new Fx.Tween(oUl[0]);
			marginChange.start('margin-left',iOriginalPos, iCurrentMargin+'px');
			iCurrentPosition=iClickedPosition;
			$('vLeftControl').fade(1); //restore previous button
		} else{ //asumption will play first of video series
			$$('#videoTopList ul.videoSelectList li')[0].getElements('img')[0].fade(0.5);
		}

		//expand containerbox
		var iNewWidth = (iLiLength * iLi) + (24 * iLi); //total + spacing
		$$('.videoSelectList')[0].id = 'slidernewwidth';
		document.getElementById('slidernewwidth').style.width = iNewWidth+'px';
		return true;
	},
	getTopVideoId: function(){
		//return $E('a', 'videoselectlist').toString().split("videoid=")[1].split('&Itemid')[0];
	},
/*
	playlist: {
		clicked: function(sPlayListSource){
			var sVideoSource = "http://www.youtube.com/v/";
			sVideoSource+=sPlayListSource;
			sVideoSource+="&autoplay=1&autoPlay=true&hl=en&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ambientEdge";
			var atts={id:"ambientEdgeVP"},params={allowScriptAccess:"always",bgcolor:"#000000"};
			sDiv="ambientEdgeVP";sPlayerWidth=600;sPlayerHeight=400;
			sVideoPlayerName="ambientEdgeVP";
			swfobject.embedSWF(sVideoSource,sDiv,sPlayerWidth,sPlayerHeight,"7","#000000",null,params,atts);
		},
		init: function(){
			var atts={id:"ambientEdgePlayList"},params={allowScriptAccess:"always",bgcolor:"#000000"};
			//swfobject.embedSWF("/swf/videoSlider.swf?xmlfile=/xml/videos.xml&v=031108&ran="+amEVideo.randomNum(),"playList","600","100","7","#000000",null,params,atts);
		}
	},
*/
	highlight:function(){
		var oLIS = $$('.videoseries');
		oLIS.each(function(iSeries){
			iSeries.addEvent('mouseover', function() {
				oImg = iSeries.getElements('img');
				oAnchor = iSeries.getElements('a');
				oImg[0].style.border="1px solid yellow";
				oAnchor[0].style.color="#ca0002";
			});
			iSeries.addEvent('mouseout', function() {
				oImg = iSeries.getElements('img');
				oAnchor = iSeries.getElements('a');
				oImg[0].style.border="1px solid #CCCCCC";
				oAnchor[0].style.color="#333333";
			});
			
		});
	},
	play: function(sVideoSource, iplayList, iVideoId){  //called from flash
		iCurrentVideo= ((iplayList*1)+1);
		amEVideo.playlist.clicked(sVideoSource);
		amEVideo.articles.getAssociatedArticles(iVideoId);
	},
	playerembed: function(sGenericEmbed){
		if(sGenericEmbed.indexOf('wmode')!=-1){ //alter wmode
			sGenericEmbed = sGenericEmbed.replace(/window/gi,'transparent');
			sGenericEmbed = sGenericEmbed.replace(/wmode="false"/gi,'wmode="transparent"');
			sGenericEmbed = sGenericEmbed.replace(/wmode=\'false\'/gi,'wmode="transparent"');
		} else{ //insert wmode
		  if(sGenericEmbed.indexOf('<iframe')!=-1){ //iframe found
		  } else if(sGenericEmbed.indexOf('<object')!=-1){ //only object also captures embeds inside of an object tag
				if(sGenericEmbed.indexOf('<param name=\'movie\'')!=-1){
					sGenericEmbed = sGenericEmbed.split('<param name=\'movie\'')[0]+'<param wmode="transparent"></param><param name=\'movie\''+sGenericEmbed.split('<param name=\'movie\'')[1];
				} else{
					sGenericEmbed = sGenericEmbed.split('<param name="movie"')[0]+'<param wmode="transparent"></param><param name="movie"'+sGenericEmbed.split('<param name="movie"')[1];
				}
				sGenericEmbed = sGenericEmbed.split('<embed')[0] +'<embed wmode="transparent" '+ sGenericEmbed.split('<embed')[1];
			} else if(sGenericEmbed.indexOf('<embed')!=-1){
				if(sGenericEmbed.indexOf('</embed>')!=-1){//ends with </embed>
					sGenericEmbed = sGenericEmbed.split('></embed>')[0] +'wmode="transparent ></embed>"';
					sGenericEmbed = sGenericEmbed.split('> </embed>')[0] +'wmode="transparent ></embed>"'; //accomodate for space
				} else{
					sGenericEmbed = sGenericEmbed.split('<embed')[0] +'<embed wmode="transparent" '+ sGenericEmbed.split('<embed')[1];
				}
			} 
		}
		$('videoPlayer').innerHTML  = sGenericEmbed;
	},
	queryParam: function(){
	  var query = window.location.search.substring(1), parms = query.split('&'); 	  //Grab all Url Params
	  for (var i=0; i<parms.length; i++) {
	          var pos = parms[i].indexOf('=');
	          if (pos > 0) {
	                  var key = parms[i].substring(0,pos);
	                  var val = parms[i].substring(pos+1);
	                  aMEQsParam[key] = val;
	          }
	  }
	},
	randomNum: function(){ranNum = new String (Math.random());return ranNum.substring (2, 11);}, //use sparingly
	stage: {
		init: function(){
			//amEVideo.XML.get();
			//amEVideo.playlist.init();
		},
		beginning: function(){
			window.parent.location.href = "/index.php?option=com_content&view=section&id=6&Itemid=7&start=1";
			return false;
		},
		next: function(){
			var i = 0, sNextVidLocation;
			var last = $ES('h3', 'videoselectlist').getElements('a').length;
			sLocation = window.location.toString();

/*
			if(sLocation.indexOf('view=section')!=-1){ //first video
					window.location = $ES('h3', 'videoselectlist').getElements('a')[1].toString();
					return true;
			} else if(sLocation == last){ //last video go back to first
				window.location= 'www.ambientedge.com';
				return true;
			} else if(sLocation == $ES('h3', 'videoselectlist').getElements('a')[($ES('h3', 'videoselectlist').getElements('a').length-1)]){
					window.location = $ES('h3', 'videoselectlist').getElements('a')[0].toString();
					return true;
			}
*/

			$ES('h3', 'videoselectlist').getElements('a').each(function(oAnchor){
				if(sLocation==oAnchor.toString()){
						i = i +1;
						window.location = $ES('h3', 'videoselectlist').getElements('a')[i];
				}
				i++;
			});

			return true;
			/*
			window.location = return $ES('a', 'videoselectlist');
			if(((iCurrentVideo*1)+1)>=oVideoSources.length){ //end reached
				amEVideo.stage.beginning();
			} else{
				window.parent.location.href = "/index.php?option=com_content&view=section&id=6&Itemid=7&start=" + ((iCurrentVideo*1)+1);

			}
			return false;
			*/
		}
	},
	video: {

		buildSource: function(sVideoPlayerName, iCurrentVideo){
			/*
			var sTest="http://gdata.youtube.com/apiplayer?key=AI39si6sRVoF_KNTzY9sGXp7vQUG-SGLYYMDnLmVtMEMgTPq4qsdx5nDdeTigzfA-Ikhl5EnkXWdYgftIeOxkyRFv3dhYwUC8Q";
			sTest += "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ambientEdge";
			*/

			if(typeof(iEmbedsourceid)=="undefined" || iEmbedsourceid==0)iEmbedsourceid='1';
			switch(iEmbedsourceid){
				case '1':
					var sVideoSource = "http://www.youtube.com/v/";
					sVideoSource +=sCurrentVideoId;
					//sVideoSource += oVideoSources[iCurrentVideo];
					sVideoSource += "&autoplay=1&autoPlay=true"
					sVideoSource += "&hl=en";
					sVideoSource += "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ambientEdge";
					sVideoSource += "&amps;rel=0&color1=0x2b405b&color2=0x6b8ab6";
					break;
				case '2':
					sVideoSource = "http://www.hulu.com/embed/"
					sVideoSource +=sCurrentVideoId;
					break;
			}
			return sVideoSource;
		},
		playVideo: function(oVideoPlayer, iSecs){
//		oVideoPlayer.loadVideoById(oVideoSources[iCurrentVideo], iSecs);
//	oVideoPlayer.loadVideoById("u1zgFlCw8Aw", iSecs);

		},
		source: function(){return gSsVideoSource;},
		setSource: function(ssVideoSource){gSsVideoSource = ssVideoSource;}
	},
	videoPlayer: {
		delegateEvents: function(eState){
			if(eState==0){//ended
				amEVideo.stage.next();
			}
		},
		ending: function(){
			//alert("called");
		},
		init: function(){
			var atts={id:"ambientEdgeVP"},params={allowScriptAccess:"always",bgcolor:"#000000",wmode:'transparent'},sDiv;
			sDiv="videoPlayer";sVideoPlayerName="ambientEdgeVP";
			if(typeof(iCurrentVideo)!="undefined"){
				var sVideoSource = amEVideo.video.buildSource(sVideoPlayerName, iCurrentVideo);
			} else {
				iCurrentVideo=1;
				var sVideoSource =  amEVideo.video.buildSource(sVideoPlayerName, 1);
			}

			//swfobject.embedSWF("/swf/videoSlider.swf?xmlfile=/xml/videos.xml&v=031108","videoPlayer","600","100","7","#000000",null,params,atts);
//			alert(sDiv);
			swfobject.embedSWF(sVideoSource,sDiv,478,320,"7","#000000",null,params,atts);
//			oVideoPlayer = $("ambientEdgeVP");
			oVideoPlayer = $("videoPlayer");
			if(oVideoPlayer){amEVideo.video.playVideo(oVideoPlayer, 0);}
			//amEVideo.videoPlayer.setEvents(oVideoPlayer);
			amEVideo.buildSlider();
		},
		setEvents: function(oVideoPlayer){
			//alert(oVideoPlayer);
		  oVideoPlayer.addEventListener("onStateChange", "amEVideo.videoPlayer.delegateEvents()");
//		  oVideoPlayer.addEventListener("onYouTubePlayerReady()", "amEVideo.videoPlayer.ending()");
//		  oVideoPlayer.addEventListener("onStateChange", "amEVideo.videoPlayer.delegateEvents()");

		}
	},
	XML: {
		get: function(){
			var oXML = new Ajax(amEVideo.XML.source(), {
				method: "get",
				onSuccess: function(sRequest){
					amEVideo.XML.videoSource(sRequest);
				}
			}).request();
		},
		source: function(){return "/xml/videos.xml";},
		videoSource: function(sRequest){
			var oVideoStrings = sRequest.split("<video_source>");
			oVideoSources = new Array();
			for(var i=0; i< oVideoStrings.length;i++){
					oVideoSources.push(oVideoStrings[i].split("</video_source>")[0]);
			}
			amEVideo.videoPlayer.init();
		}
	}
}

function onYouTubePlayerReady(playerId) {
	oVideoPlayer = $('ambientEdgeVP');
  oVideoPlayer.addEventListener("onStateChange", "amEVideo.videoPlayer.delegateEvents");
}
/*
window.addEvent('domready', function() {
	amEVideo.queryParam(); //build qa params
	if(typeof(aMEQsParam['start'])!="undefined"){
		iCurrentVideo = aMEQsParam['start'];
		amEVideo.stage.init();
	} else{
		amEVideo.stage.init();
	}
});
*/


