﻿$('document').ready(function(){
    //title and containter
    $('li.audioListItem').each(function(){
        var $this = $(this);
        $('.audioTitle', $this).hover(function(){
            $(this).css({color:'#B11B2E'});
        }, function(){
            if($this.attr('open') !== 'true'){
                $('.audioTitle', $this).css({color:'#3E4C58'});                 
            }
        }).click(function(){
            if($this.attr('open') === 'true'){
                UHC.Audio.setAudioRowInactive($this);   
            }
            else{
                $('span.openCloseIcon', $this).css({'background-position':'-30px -253px'});
                $this.animate({height:'124px'}).attr('open', 'true');
                $('ul.audioPlayerRow', $this).fadeIn();
                $('li.audioListItem:not(:animated)').each(function(){
                    var $this = $(this);
                    UHC.Audio.setAudioRowInactive($this);
                });
            }
        });
    });
    
    //preload loading animation
    var img = new Image();
    img.src = '/DesktopModules/Podcast/images/loadingAnimation.gif';
 
	//Diabetes Prevention – What is Diabetes?
	UHC.Audio.setPodcastContent(
		'#diabetesOne'
		,UHC.Audio.playerFactory(
			'Diabetes Two English'
			,true
			,'03:18'
			,'Diabetes_1_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Diabetes Two Spanish'
			,false
			,'03:53'
			,'Diabetes_1_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('Diabetes_Prevention_Brochure.pdf')
	);
	
	//Diabetes Prevention – What can you do to help prevent Diabetes
	UHC.Audio.setPodcastContent(
		'#diabetesTwo'
		,UHC.Audio.playerFactory(
			'Diabetes Two English'
			,true
			,'03:24'
			,'Diabetes_2_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Diabetes Two Spanish'
			,false
			,'04:07'
			,'Diabetes_2_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('Diabetes_Prevention_Brochure.pdf')
	);
	
	//Weight Management
	UHC.Audio.setPodcastContent(
		'#weightManagement'
		,UHC.Audio.playerFactory(
			'Weight Management English'
			,true
			,'04:48'
			,'Weight_Control_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Weight Management Spanish'
			,false
			,'05:25'
			,'Weight_Control_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('Weight_Management_Brochure.pdf')
	);
 
	//Exercise and Fitness
	UHC.Audio.setPodcastContent(
		'#exercise'
		,UHC.Audio.playerFactory(
			'Exercise English'
			,true
			,'07:25'
			,'Fitness_Podcast1_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Exercise Spanish'
			,false
			,'08:59'
			,'Fisico_Podcast1_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('Exercise_and_Fitness_Brochure.pdf')
	);
    
	//Stress Management
	UHC.Audio.setPodcastContent(
		'#stressOne'
		,UHC.Audio.playerFactory(
			'Stress English'
			,true
			,'02:58'
			,'Stress_Podcast1_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Stress Spanish'
			,false
			,'03:48'
			,'Estres_Podcast1_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('Stress_Management_Brochure.pdf')
	);
    
	//Stress Management - Exercise to Manage Stress
	UHC.Audio.setPodcastContent(
		'#stressTwo'
		,UHC.Audio.playerFactory(
			'Stress Two English'
			,true
			,'06:43'
			,'Stress_Podcast2_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Stress Two Spanish'
			,false
			,'08:33'
			,'Estres_Podcast2_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('Stress_Management_Brochure.pdf')
	);

	//How to navigate your health plan
	UHC.Audio.setPodcastContent(
		'#yourHealthPlan'
		,UHC.Audio.playerFactory(
			'Navigate Your Health Plan English'
			,true
			,'02:52'
			,'Navigate_Health_Plan_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Navigate Your Health Plan Spanish'
			,false
			,'03:36'
			,'Navigate_Health_Plan_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('HowtoNavigateYourPlanBienHealthCoveragePlan_BILINGUAL.pdf')
	);
    
	//How to select your primary physician
	UHC.Audio.setPodcastContent(
		'#primaryPhysician'
		,UHC.Audio.playerFactory(
			'Select a Primary Physician English'
			,true
			,'03:23'
			,'Primary_Physician_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Select a Primary Physician Spanish'
			,false
			,'04:14'
			,'Primary_Physician_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('HowtoNavigateYourPlanBienHealthCoveragePlan_BILINGUAL.pdf')
	);
	
	//Understanding your payment Responsibilities
	UHC.Audio.setPodcastContent(
		'#paymentResponsibilities'
		,UHC.Audio.playerFactory(
			'Your Responsibilities English'
			,true
			,'02:55'
			,'Payment_Responsibility_English.mp3'
		)
		,UHC.Audio.playerFactory(
			'Your Responsibillities Spanish'
			,false
			,'03:34'
			,'Payment_Responsibility_Spanish.mp3'
		)
		,UHC.Audio.brochureFactory('HowtoNavigateYourPlanBienHealthCoveragePlan_BILINGUAL.pdf')
	);
	
	//What is a primary care physician?
	UHC.Audio.setPodcastContent(
		'#WhatPrimaryCarePhysician'
		,UHC.Audio.playerFactory(
			'What is a primary care physician'
			,true
			,'03:07'
			,'What_is_a_Primary_Care_Physician.mp3'
		)
		,UHC.Audio.playerFactory(
			'What is a primary care physician Spanish'
			,false
			,'04:01'
			,'Que_Es_un_Doctor_Primario.mp3'
		)
		,UHC.Audio.brochureFactory('Levels_of_Care_Brochure_Bilingual.pdf')
	);
	
	//What is a convenience care clinic
	UHC.Audio.setPodcastContent(
		'#ConvenienceCare'
		,UHC.Audio.playerFactory(
			'Convenience Care'
			,true
			,'02:23'
			,'What_is_a_Convenience_Care_Clinic.mp3'
		)
		,UHC.Audio.playerFactory(
			'Convenience Care Spanish'
			,false
			,'03:58'
			,'Que_Es_una_Clinica_de_Atencion_de_Conveniencia.mp3'
		)
		,UHC.Audio.brochureFactory('Levels_of_Care_Brochure_Bilingual.pdf')
	);
	
	//What is an urgent care facility?
	UHC.Audio.setPodcastContent(
		'#UrgentCare'
		,UHC.Audio.playerFactory(
			'UrgentCare Care'
			,true
			,'02:29'
			,'What_Is_an_Urgent_Care_Facility.mp3'
		)
		,UHC.Audio.playerFactory(
			'Urgent Care Spanish'
			,false
			,'04:02'
			,'Que_Es_un_Centro_de_Atencion_de_Urgencia.mp3'
		)
		,UHC.Audio.brochureFactory('Levels_of_Care_Brochure_Bilingual.pdf')
	);
	
	//What is an emergency care facility?
	UHC.Audio.setPodcastContent(
		'#EmergencyCare'
		,UHC.Audio.playerFactory(
			'Emergency Care'
			,true
			,'03:01'
			,'What_Is_an_Emergency_Care_Facility.mp3'
		)
		,UHC.Audio.playerFactory(
			'Emergency Care Spanish'
			,false
			,'04:22'
			,'Que_Es_una_Sala_de_Emergencias.mp3'
		)
		,UHC.Audio.brochureFactory('Levels_of_Care_Brochure_Bilingual.pdf')
	);
	
	//Blood Pressure and Your Health - Part One
	UHC.Audio.setPodcastContent(
		'#BloodPressureOne'
		,UHC.Audio.playerFactory(
			'Blood Pressure - Part One'
			,true
			,'04:11'
			,'Blood Pressure and Your Health Part 1.mp3'
		)
		,UHC.Audio.playerFactory(
			'Blood Pressure - Part One - Spanish'
			,false
			,'05:11'
			,'La Presion Arterial y Su Salud Parte 1.mp3'
		)
		,UHC.Audio.brochureFactory('Blood_Pressure_Brochure.pdf')
	);
	
	//Blood Pressure and Your Health - Part Two
	UHC.Audio.setPodcastContent(
		'#BloodPressureTwo'
		,UHC.Audio.playerFactory(
			'Blood Pressure - Part Two'
			,true
			,'04:45'
			,'Blood Pressure and Your Health Part 2.mp3'
		)
		,UHC.Audio.playerFactory(
			'Blood Pressure - Part Two - Spanish'
			,false
			,'05:42'
			,'La Presion Arterial y Su Salud Parte 2.mp3'
		)
		,UHC.Audio.brochureFactory('Blood_pressure_Brochure.pdf')
	);
});

var UHC = {};
UHC.Audio = (function(){
	var AUDIO_FILE_BASE_PATH = '/DesktopModules/Podcast/podcasts/';
    var BROCHURE_BASE_FILE_PATH = '/DesktopModules/Podcast/podcastBrochures/';
	var JPLAYER_SWF_PATH = '/DesktopModules/Podcast/js';
	var audioHtml = '<ul class="audioPlayerRow"> \
                            <li class="audioPlayerCell audioPlayerLanguageLabel"></li> \
                            <li class="audioPlayerCell audioPlayerButton audioPlayButton"></li> \
                            <li class="audioPlayerCell audioPlayerButton audioStopButton"></li> \
                            <li class="audioPlayerCell audioPlayerButton audioMuteButton"></li> \
                            <li class="audioPlayerCell audioProgressContainer"> \
                               <div class="audioLoadBar"> \
                                    <div class="audioPlayBar"></div> \
                                </div> \
                                <div class="audioPlayTime"></div> \
                            </li> \
                            <li class="audioPlayerCell audioDownloadLabel"></li> \
                            <li class="audioPlayerCell audioPlayerButton audioDownloadButton"></li> \
                        </ul>';
						
    var brochureHtml = '<ul class="audioPlayerRow"> \
                            <li class="audioPlayerCell audioPlayerBrocureLabel">Brochure</li> \
                            <li class="audioPlayerCell audioPlayerButton audioBrochureDownloadButton"><a class="audioBrochureLink" href="" target="_blank"></a></li> \
                        </ul>';      
    
	function playerFactory(title, isEnglish, playLength, audioFileName){
        var audioRow = $(audioHtml);
		//.data() is not available at DOM ready?
		//audioRow.data('player', {instance: undefined, podcastTitle: title, isPlayMode: false, isPauseMode: false, isMuteMode: false});
		
		var isPauseMode = false;
        var isMuteMode = false;      
        
        if(isEnglish){
            audioRow.addClass('first');
        }
        if(isEnglish){
            $('.audioPlayerLanguageLabel', audioRow).text('English');
            $('.audioDownloadLabel', audioRow).text('Download'); 
        }
        else{
            $('.audioPlayerLanguageLabel', audioRow).html('Espa&ntilde;ol');
            $('.audioDownloadLabel', audioRow).text('Descarga');  
        }
		
		var jPlayerInstance = jPlayerFactory(title, audioFileName);
		
		bindPlayerEvents(audioRow, title, jPlayerInstance, audioFileName, playLength);
		
        return audioRow;
    };
	
	function jPlayerFactory(title, audioFileName){
		var playerElement = $('<div></div>');
        playerElement.attr('id', title.replace(/\s/g, '_'));
        $('body').append(playerElement);
        var jPlayerInstance = playerElement.jPlayer({
            ready: function(){
                this.element.jPlayer('setFile', AUDIO_FILE_BASE_PATH + audioFileName);
            }
            ,customCssIds: true
            ,swfPath: JPLAYER_SWF_PATH
        });
		return jPlayerInstance;
	};
    function setAudioRowInactive($this){
        $('.audioTitle', $this).css({color:'#3E4C58'});
        $('span.openCloseIcon', $this).css({'background-position':'0px -253px'});
        $this.animate({height:'14px'}).attr('open', 'false');
        $('ul.audioPlayerRow', $this).fadeOut();
    } 
	function brochureFactory(fileName){		
		var brochure = $(brochureHtml);
		$('.audioBrochureLink', brochure).attr('href', BROCHURE_BASE_FILE_PATH + fileName);
		return brochure;
	}
	function setPodcastContent(){
		var args = Array().slice.apply(arguments);
		var podcastContainer = $(args[0]);
		//podCastContainer.append.apply(podCastContainer, args.splice(1));
		for(var i = 1; i < args.length; i++){
			podcastContainer.append(args[i]);
		}
	}
	
	function bindPlayerEvents(audioRow, title, jPlayerInstance, audioFileName, playLength){
		//setup jQueryUI slider widget
        var slider = $('.audioLoadBar', audioRow).slider({
            slide:function(event, ui){
                jPlayerInstance.jPlayer('playHead', ui.value);
            }
        });
        var sliderHandle = $('.ui-slider-handle', audioRow);
        var audioPlayButton = $('.audioPlayButton', audioRow);
		var audioStopButton = $('.audioStopButton', audioRow);
        var audioMuteButton = $('.audioMuteButton', audioRow);
        var playBar = $('.audioPlayBar', audioRow);
        var playTime = $('.audioPlayTime', audioRow);
		var isPlayMode = false;
		var isPauseMode = false;
		var isMuteMode = false;
		
       //handle play button
       audioPlayButton.click(function(){
            if( ! isPlayMode){
				setPlayButtonState(audioPlayButton, 'active');
                jPlayerInstance.jPlayer('play');
				jPlayerInstance.jPlayer('vloumeMax');
                sliderHandle.show();
                isPlayMode = true;
				if( ! isPauseMode){
					UHC.ConversionTracking.trackAudioEvent('Podcast', 'Play', title.replace(/\s+/g, '_'));
				}
            }
            else{
				setPlayButtonState(audioPlayButton, 'ready');
                jPlayerInstance.jPlayer('pause');
                isPlayMode = false;
				isPauseMode = true;
            }
        }).mouseover(function(){
            if(isPlayMode){               
				setPlayButtonState(audioPlayButton, 'pauseActive');
            }
            else{
				setPlayButtonState(audioPlayButton, 'pauseReady');
            }
        }).mouseout(function(){
            if(isPlayMode){
				setPlayButtonState(audioPlayButton, 'active');
            }
            else{
				setPlayButtonState(audioPlayButton, 'ready');
            }
        });
	   
	   //handle stop button
        audioStopButton.click(function(){
            jPlayerInstance.jPlayer('stop');
			jPlayerInstance.jPlayer('volumeMax');
            sliderHandle.hide();
			setPlayButtonState(audioPlayButton, 'ready');
            setMuteButtonState(audioMuteButton, 'ready');
			playTime.text(playLength);
            isPlayMode = false;
			isPauseMode = false;
        }).hover(function(){
            if(isPlayMode){
                setStopButtonState(audioStopButton, 'ready');
            }
        }
        ,function(){
            setStopButtonState(audioStopButton, 'active');
        });
		
        //handle mute button
        audioMuteButton.click(function(){
            if( ! isMuteMode){
                if(isPlayMode){
					setMuteButtonState(audioMuteButton, 'active');
                    jPlayerInstance.jPlayer('volumeMin');
                    isMuteMode = true;
                }   
            }
            else{
               setMuteButtonState(audioMuteButton, 'ready');
                jPlayerInstance.jPlayer('volumeMax');
                isMuteMode = false;
            } 
        }).hover(function(){
            if(isPlayMode){
                setMuteButtonState(audioMuteButton, 'active');
            }
        }
        ,function(){
            if( ! isMuteMode){
                setMuteButtonState(audioMuteButton, 'ready');
            }
        }); 
		
        //handle audio progress change
        //Parameters - Number: loadPercent, Number: playedPercentRelative, Number: playedPercentAbsolute, Number: playedTime, Number: totalTime
        jPlayerInstance.jPlayer("onProgressChange", function(lp,ppr,ppa,pt,tt) {
            var _ppa = parseInt(ppa);
            playBar.width(_ppa + '%');
            slider.slider('value',  (_ppa - 2));
            if(pt === 0){
                if( ! isPlayMode){
                    playTime.text(playLength);
                }
                else{
                   playTime.html('<img style="padding-top:7px;" src="/DesktopModules/Podcast/images/loadingAnimation.gif" />');
                }
            }
            else{
                $('img', playTime).fadeOut('normal');
                playTime.text($.jPlayer.convertTime(pt));
            }
        });
        //handle audio complete
        jPlayerInstance.jPlayer("onSoundComplete", function() {
            isPlayMode = false;
           audioPlayButton.css({'background-position':'0px 0px'});
        });
        //handle audio download button
        $('.audioDownloadButton', audioRow).click(function(){
			//track conversion and download the file
			UHC.ConversionTracking.trackAudioDownload(AUDIO_FILE_BASE_PATH + 'download.aspx?f=' + audioFileName, 'Podcast', 'Download', title.replace(/\s+/g, '_'));
        });
	}
	
	//ToDo: consider using this as an alternative to bindPlayerEvnts - otherwise delete.
	//what if I passed in an audio row context object and boud each row with delegate?
	function bindEvents(){
		var audioPlayer = $('.audioPlayerRow');
		
		var sliderHandle = $('.ui-slider-handle', audioPlayer);
        varaudioPlayButton = $('.audioPlayButton', audioPlayer);
        var audioMuteButton = $('.audioMuteButton', audioPlayer);
        var playBar = $('.audioPlayBar', audioPlayer);
        var playTime = $('.audioPlayTime', audioPlayer);
		
		//bind and handle mute button events
		audioPlayer.delegate('.audioMuteButton', 'click mouseover mouseout', function(event){
			var button = $(this);
			var playerData = button.parent('.audioPlayerRow').data('player');
			if(event.type === 'click'){
				if(playerData.isPlayMode){
					if( ! playerData.isMuteMode){
						playerData.isMuteMode = true;
						setMuteButtonState(button, 'active');
						playerData.instance.jPlayer('volumeMin');
					}
					else{
						playerData.isMuteMode = false;
						setMuteButtonState(button, 'ready');
						playerData.instance.jPlayer('volumeMax');
					}
				}
			}
			else if (event.type === 'mouseover'){
				if(playerData.isPlayMode){
					setMuteButtonState(button, 'active');
				}
			}
			else if(event.type === 'mouseout'){
				if( ! playerData.isMuteMode){
					setMuteButtonState(button, 'ready');
				}
			}
		});
		
		//bind and handle stop button
		audioPlayer.delegate('.audioStopButton', 'click mouseover mouseout', function(event){
			var button = $(this);
			var player = button.parent('.audioPlayerRow');
			var playerData = player.data('player');
			var sliderHandle = $('.ui-slider-handle', player);
			varaudioPlayButton = $('.audioPlayButton', player);
			var audioMuteButton = $('.audioMuteButton', player);
			var playBar = $('.audioPlayBar', player);
			var playTime = $('.audioPlayTime', player);
			if(event.type === 'click'){
				console.log('click');
				playerData.instance.jPlayer('stop');
				sliderHandle.hide();
				$audioPlayButton.css({'background-position':'0px 0px'});
				setMuteButtonState(audioMuteButton, 'ready');
				playerData.isPlayMode = false;
				playerData.isPauseMode = false;
			}
			else if(event.type === 'mouseover'){
				if(playerData.isPlayMode){
					$(this).css({'background-position':'-45px -275px', 'cursor':'pointer'});
				}
			}
			else if(event.type === 'mouseout'){
				$(this).css({'background-position':'0px -275px', 'cursor':'default'});
			}
		});
	}
	function setPlayButtonState(btn, action){
		if(action === 'ready'){
			btn.css({'background-position':'0px 0px'});
		}
		else if(action === 'active'){
			btn.css({'background-position':'0px -36px'}); 
		}
		else if(action === 'pauseReady'){
			btn.css({'background-position':'-45px 0px'});
		}
		else if(action === 'pauseActive'){
			btn.css({'background-position':'-45px -36px'});
		}
	}
	function setStopButtonState(btn, action){
		if(action === 'ready'){
			btn.css({'background-position':'-45px -275px', 'cursor':'pointer'});
		}
		else if (action === 'active'){
			btn.css({'background-position':'0px -275px', 'cursor':'default'});
		}
	}
	function setMuteButtonState(btn, action){
		if(action === 'ready'){
			btn.css({'background-position':'0px -72px', 'cursor':'default'}); //ready state
		}
		else if(action === 'active'){
			btn.css({'background-position':'-45px -72px', 'cursor':'pointer'}); //active state
		}
	}
    return {
		playerFactory: playerFactory
		,brochureFactory: brochureFactory
		,setAudioRowInactive: setAudioRowInactive
		,setPodcastContent: setPodcastContent
		//,bindEvents: bindEvents
	};
})();

UHC.ConversionTracking = (function(){
	/**
	*	Description: When visitors play or download the podcast or download 
	*	the transcript, we record the event using Google Analytics. 
	*/
	
	function recordDownload(href, category, action, label) {
		try {
			_gaq.push(['_trackEvent', category, action, label]);
			setTimeout('document.location = "' + href + '"', 200)	
		}
		catch(err)
		{
		}
	}
	
	function recordEvent(category, action, label){
		_gaq.push(['_trackEvent', category, action, label]);
	}

	return {
		trackAudioEvent:recordEvent
		,trackAudioDownload:recordDownload
	}
})();
