


var plib = new Class.create({

	initialize: function(el, max) {
		this.element = $(el);
		this.max = max;

		phist.register(
			'pvid',
			'animations*',
			function(newvalue) {
				//switch tab
				console.log("processing ne val of " + newvalue);
				var itemdata = newvalue.split('*');

				this.tab = itemdata[0];
				this.video = itemdata[1];
		
				this.switchItem(itemdata[0],itemdata[1],true);
			}.bind(this));
	},
	switchItem: function(tabname,itemname,skipUpdate) {
		d = new Date();
		console.log("switchitem" + d.getTime() + " switchitem starting..");
		
		//any change to the tab?
		if (!tabname){
			tabname = this.tab;
		}
		
		//store vars
		this.tab = tabname;
		this.video = itemname;

		//store history
		if (!skipUpdate){
			phist.update('pvid', this.tab + '*' + this.video,false);
		}

		//highlight the correct tab
		console.log("switchitem: " + "turning off all tabs but for " + tabname);
		this.tabsOff(tabname);

		//highlight the correct video
		console.log("switchitem: " + "highlighting correct vidoe/media data");
		this.videoSelect(this.video);

		d = new Date();
		console.log("switchitem: " + d.getTime() + " switchitem completed");
	},
	videoSelect : function(videoname){
		console.log("videoSelect: " + videoname);

		//empty download button area
		$('preslib_content_dlbuttons').update('');


		//is this a valid video?
		if ((!videoname) || (videoname == '')){
			//set to 'welcome' screen
			console.log("videoSelect: " + "no video info available, showing default msg");
			
			if ($('flashcontent')){
				swfobject.removeSWF("flashcontent");
			}
			$('welcomeMsg').show();
			$('preslib_content_dlbuttons').insert('<div id="msg">Download options are available upon selection of a presentation.</div>');
			$('content_title').setStyle({backgroundImage : 'url(images/presentationLib/gfx_PresLib_player_top.gif)'});
			$('content_title_label').update('Select an item from the Library');
			$('preslib_content_description').update('');
			
			//hide slideshow
			$('slideshowViewer').hide();
			
			return false;
		}else{
			console.log("videoSelect: " + "video available, hiding welcome msg");
			$('welcomeMsg').hide();
		}

		
		//walk all menu items, removing the 'menuitem_current' class
		console.log("videoSelect: " + "removing all current menu items and setting new current");
		$$('.menuitem').invoke('removeClassName','menuitem_current');

		//reset bg colors
		$$('.menuitem').invoke('setStyle',{backgroundColor:'#F4F4F4'});

		//set new color
		$('menuitem' + videoname).addClassName('menuitem_current');
		
		//storage for button count
		var buttonCount = 0;
		
		//okay, is this a flash video, or a slideshow?
		var found_flash = false;
		console.log("videoSelect: " + "searching for supported media");
		items = $$('a[name="mediadata' + videoname + '"]');
		for (var k=0; k < items.length; k++){
			//is this media type a flv?
			if (items[k].type == 'flv'){

				console.log("videoSelect: " + "FLV detected.. render..");
				
				found_flash = true;

				//hide any slideshow viewer
				console.log("videoSelect: " + "hiding slideshow");
				$('slideshowViewer').hide();
				
				//embed flash
				xiSwfUrlStr = "presentation_media/expressInstall.swf";

				if (swfobject.hasFlashPlayerVersion("8")) {
					console.log("videoSelect: " + "flash version is valid, continuing");
					
					// check if SWF hasn't been removed, if this is the case, create a new alternative content container
					var c = document.getElementById("flashcontent");
					if (!c) {
						console.log("videoSelect: " + "missing flashcontent, needing to re-render");
						var d = document.createElement("div");
						d.setAttribute("id", "flashcontent");
						document.getElementById("flash-content-container").appendChild(d);
					}else{
						console.log("videoSelect: " + "flash content div available");
					}
					
					// create SWF
					vidsrc = new String(items[k].href);
					if (vidsrc.indexOf('?') != -1){
						//remove this
						vidsrc = vidsrc.substring(0,vidsrc.indexOf('?'));
						
					}
					
					var att = { data:"presentation_media/player.php?rt=" + new Date().valueOf(), width:"360", height:"240" };
					var par = { menu:"false", FlashVars : "vidsrc=" + vidsrc, allowscriptaccess : "always" };
					var id = "flashcontent";
					
					console.log("videoSelect: " + "creating SWF...");
					this.doSWFInsertion(att, par, id);

					//show help text
					console.log("videoSelect: " + "Showing help text");
					$('preslib_content_description').update($('media' + videoname).innerHTML);

					//show body title
					$('content_title_label').update($('media_title_' + videoname).innerHTML);
					
					//set body background graphic
					ksrcref = new String(items[k].href);
					
					if (ksrcref.indexOf('width_option=narrow') == -1){
						$('content_title').setStyle({backgroundImage : 'url(images/presentationLib/gfx_PresLib_player_top.gif)'});
					}else{
						$('content_title').setStyle({backgroundImage : 'url(images/presentationLib/gfx_PresLib_player_top_narrow.gif)'});
					}
					
				}else if (xiSwfUrlStr && swfobject.hasFlashPlayerVersion("6.0.65")) {

					console.log("videoSelect: " + "flash version isnt valid, but user is elegible for XPI");
					
					//check flash content exists..
					var c = document.getElementById("flashcontent");
					if (!c) {
						var d = document.createElement("div");
						d.setAttribute("id", "flashcontent");
						document.getElementById("flash-content-container").appendChild(d);
					}
					
					swfobject.custom_goSWFInstallUpgrade(
							"flashcontent", 360, 240, xiSwfUrlStr);
					
				}else{
					console.log("videoSelect: " + "no flash or XPI available");
					$('noflashsupport').show();
				}

				
			}else if (items[k].type.indexOf('slideshow') != -1){
				//show slideshow
				// 
				
				//only do this for the first item..
				if (items[k].type.indexOf('slideshow1') != -1){
	
					//hide flash
					swfobject.removeSWF("flashcontent");
	
					slideshow.newShow($$('a[name="' + items[k].name + '"][type*="slideshow"]'),1);
	
					//show the slideshow
					$('slideshowViewer').show();
					
					//show help text
					console.log("videoSelect: " + "Showing help text");
					$('preslib_content_description').update($('media' + videoname).innerHTML);
	
					//show body title
					$('content_title').setStyle({backgroundImage : 'url(images/presentationLib/gfx_PresLib_player_top.gif)'});
					$('content_title_label').update($('media_title_' + videoname).innerHTML);
				}
			}else{
				if (items[k].type.toUpperCase() != ''){
					console.log("videoSelect: " + "Rendering download button..");
					
					//populate download button
					var dlimgid = videoname + '_dl_' + items[k].type;
					
					var dlbtn = new Element('a');
					dlbtn.href = items[k].href;
					dlbtn.target = '_blank';
	
					var dlimg = new Element('img');
					dlimg.src = 'images/presentationLib/gfx_downloadOptions_btn_' + items[k].type.toUpperCase() + '_all.jpg';
					dlimg.border=0;
					dlimg.id=dlimgid;
					dlimg.className = 'imageSliceHover';
					dlimg.height=85;
	
					switch (items[k].type.toUpperCase()){
						case 'MOV':
							dlimg.width = 80;
							mediaDescr = 'Files in .mov format can be played with Apple Quicktime and compatible players.';
							break;
						case 'MPG':
							dlimg.width = 80;
							mediaDescr = 'Files in .mpg format can be played with most media players, including Windows Media Player, and Apple Quicktime';
							break;
						case 'MP4':
							dlimg.width = 80;
							mediaDescr = 'Files in .mp4 format can be played with most Apple computers, including iPad.';
							break;
						case 'WMV':
							dlimg.width = 124;
							mediaDescr = 'Files in .wmv format can be played with Windows Media Player, and other compatible players.';
							break;
						case 'ZIP':
							dlimg.width = 85;
							//the zip icon appears on it's own, and so needs some padding to round out the box
							dlbtn.style.paddingLeft = '30px';
							mediaDescr = 'Files in .zip format act as a container for other files. Modern versions of Windows and Apple OSX will automatically open these files.';
							break;
						case 'PDF':
							dlimg.width = 85;
							//the pdf icon appears on it's own, and so needs some padding to round out the box
							dlbtn.style.paddingLeft = '30px';
							mediaDescr = 'Files in .pdf can be opened with the Acrobat Reader software. It is pre-installed on 99% of modern PC\'s';
							break;
					}
	
					//append image to href
					console.log("videoSelect: " + "adding image buttons");
					dlbtn.appendChild(dlimg);
	
					$('preslib_content_dlbuttons').insert(dlbtn);
	
					//hoverize
					console.log("videoSelect: " + "requesting hoverize of new image...");
					SPNC.hoverize(dlimg);
					
					console.log("videoSelect: " + "adding observers");
					
					//add mouseover observer
					$(dlimgid).observe('mouseover',function(e){
						//add hover state
						el = Event.element(e);
						SPNC.moveImageIndex(el,1); //0=off
						});
					$(dlimgid).observe('mouseout',function(e){
						//add off state
						el = Event.element(e);
						SPNC.moveImageIndex(el,0); //0=off
						});
	
	
	
					//setup a tooltip for this mouseover
					console.log("videoSelect: " + "rendering tooltip");
					new Tip(dlimgid, "<div class='media_help_tooltip'><img src='images/presentationLib/tooltip_" + items[k].type.toLowerCase() + ".png' align='left'>" + mediaDescr + '</div>', {
						title: "",
						style: 'protogrey',
						stem: 'leftTop',
						hook: { mouse: false, tip: 'leftTop' , target: 'rightTop'},
						offset: { x: -15, y: -10 }/*,
						width: 240,
						hideAfter: 10,
						hideOn: false*/
					});
					
					buttonCount++;
				}
			}
		}
		console.log("videoSelect: " + "done searching for supported media");

		//if we didn't find flash, we need to insert the slideshow instead
		if (!found_flash){
			$('noflashsupport').update('Slideshow required');
		}else{
			console.log("videoSelect: " + "supported media found, all done");
		}

		//show an error if we don't have any download options
		if (buttonCount == 0){
			$('preslib_content_dlbuttons').insert('<span style="padding-left:30px; padding-right:30px">No download options are available for this item.</span>');
		}
		
		//track the event
		if (pageTracker){
			if (pageTracker._trackPageview){
				pageTracker._trackPageview("/physicianResources_presentationLibrary/" + escape($('content_title_label').innerHTML) + ".html");
			}
		}
	},
	doSWFFollowup :  function(att,par,id){
		
		if ($('flashcontent')){
			
			console.log("doSWFFollowup: " + "SWF width: " +  $('flashcontent').getWidth());

			//got flash content, check width?
			if ($('flashcontent').getWidth() == 0){
				console.log("doSWFInsertion : SWF is 0 width after 1 second. Retrying");
				console.warn("doSWFInsertion : SWF/adobe failed to load player.Re-rendering..");
				this.doSWFInsertion(att, par, id);
			}else{
				//all's well!
			}
		}		
	},
	doSWFInsertion : function(att,par,id){
		//create element
		
		console.log("doSWFInsertion : inserting SWF into " + id);
		swfobject.createSWF(att, par, id);
		
		Event.observe(window,'load',function(att,par,id){	
			//check for flash problems..
			setTimeout(this.doSWFFollowup.bind(this,att,par,id),100);
		}.bind(this,att,par,id));

		
		
	},
	tabsOff : function(keepon){
		//turn off un-needed tab images
		$$('span[class~="imageTabIcon"]').each(function(tab){
			if (tab.id != 'tabimg_' + keepon){
				//switch to off mode
				tab.removeClassName('activeTab');
				SPNC.moveImageIndex(tab,0);
			}			
		}.bind(this)); 
		
		//hide "loading" message
		$('loadingMenusMessage').hide();

		//turn off un-used menus
		$$('div[id^="pres_menu_"]').each(function(menu){
			if (menu.id != 'pres_menu_' + keepon){
				//switch to off mode
				menu.hide();
			}			
		}.bind(this)); 

		//enable the correct tab
		SPNC.moveImageIndex($('tabimg_' + keepon),2);
		$('tabimg_' + keepon).addClassName('activeTab'); 

		//enable the correct menu
		if (!$('pres_menu_' + keepon)){
			console.warn("Element pres_menu_" + keepon + " is missing");
		}else{
			$('pres_menu_' + keepon).show();
		}
	},
	_getImageAddress : function(curname, newstate){
		console.log("getting image addr for " + curname + "," + newstate);
		var ext = curname.substr(curname.lastIndexOf('.'),10);
		
		return curname.substr(0,curname.lastIndexOf('_')+1) + newstate + ext;	
	}
});

function slideshow_manager(){
	this.showstore = null;
	this.currentIdx = 1;
	
	this.prevRecord = function(){
		//check if there's a previous record available.. if so, migrate to it
		this.flipTo(this.currentIdx - 1);
		
		this.preload(this.currentIdx - 2);
	};

	this.updateButtons = function(newPos){
		this.currentIdx = newPos;

		if (newPos == 1){
			//switch to off
			SPNC.moveImageIndex($('leftPanelSlideShow'),2);
			$('leftPanelSlideShow').addClassName('disabledButton');
		}else{
			//available for selection
			SPNC.moveImageIndex($('leftPanelSlideShow'),0);
			$('leftPanelSlideShow').removeClassName('disabledButton');
		}
		if (newPos == this.showstore.length){
			//switch to off
			SPNC.moveImageIndex($('rightPanelSlideShow'),2);
			$('rightPanelSlideShow').addClassName('disabledButton');
		}else{
			//available for selection
			SPNC.moveImageIndex($('rightPanelSlideShow'),0);
			$('rightPanelSlideShow').removeClassName('disabledButton');
		}
		
		//update the displayed content in the "slide n of x"
		$('slideshowViewer_bottom_label').update("Slide " + newPos + " of " + this.showstore.length);
	};

	this.flipTo = function(slideID){
		if (typeof(this.showstore[slideID-1]) != "undefined"){
			console.log("moving to idx " + (slideID-1));
			
			$('slideshowViewer_slide').src = this.showstore[slideID-1].href;

			this.updateButtons(slideID);
		}else{
			console.warn("cannot move to slide " + slideID);
		}
		
	};
	
	this.preload = function(idx){
		//confirm a valid index
		if ((idx < 0) || (idx > this.showstore.length)){
			return false;
		}
		
		//preload the content
		var preimg = new Element('img',{src : this.showstore[idx-1].href,style:'display: none'});
		
		$('canvasBottom').insert(preimg);
	};

	this.nextRecord = function(){
		this.flipTo(this.currentIdx + 1);
		
		this.preload(this.currentIdx + 2);
	};

	this.newShow = function(showItems){
		this.showstore = showItems;

		//setup styling
		if (!$('slideshowViewer_bottom_label')){
			$('slideshowViewer_bottom').setStyle({position:'relative'});
			var ss_label = new Element('span',{id: 'slideshowViewer_bottom_label',style:'position:absolute;top:9px;left:0px;text-align:center; width:100%;color:white;'});
			$('slideshowViewer_bottom').insert(ss_label);
		}
		
		this.flipTo(1);
		
		//preload a few items..
		this.preload(2);
		this.preload(3);
	};
	
}


var pres_lib;
var phist;
var slideshow;

Event.observe(document,'dom:loaded',function(){
	//start slideshow mgr
	slideshow = new slideshow_manager();
	
	phist = new HistoryManager();
	pres_lib = new plib();

	//start history mgr
	phist.start();

	
});

//when the window is fully loaded, grab extra icons we'll want later..
Event.observe(window,'load',function(){
	
	ar = [
			'images/presentationLib/tooltip_wmv.png',
			'images/presentationLib/tooltip_mov.png',
			'images/presentationLib/tooltip_mpg.png',
			'images/presentationLib/tooltip_zip.png',
			'images/presentationLib/gfx_downloadOptions_btn_WMV_all.jpg',
			'images/presentationLib/gfx_downloadOptions_btn_ZIP_all.jpg',
			'images/presentationLib/gfx_downloadOptions_btn_MOV_all.jpg',
			'images/presentationLib/gfx_downloadOptions_btn_MP4_all.jpg',
			'images/presentationLib/gfx_downloadOptions_btn_MPG_all.jpg'
		  	];

	for (var ij=0; ij < ar.length; ij++){
		eImg = new Element('img');
		eImg.src = ar[ij];
		eImg.style.display = 'none';
		$('canvasBottom').insert(eImg);
	}
});
