$(document).ready(function(){

	/*--LOAD VARS FROM PHP--*/

		//var jsvars = new Array();
		
		$('.jsvars').each(function(){
			jsvars[$(this).attr('name')] = $(this).val();
		});




	/*--MAKE INTERACT TABS WORK--*/
		
		$("div#ichurch_interact_nav").tabs("div#ichurch_interact_body > div", {
			effect: 'fade',
			fadeOutSpeed: 200
		}).history();




	/*--TURN ON SCROLLING--*/
	
		$('#ichurch_chat_textarea').autoResize({
			onResize : function(myheight) {
				adjusted_height = (354 - myheight) + 32;
				adjusted_height_2 = (354 - myheight) + 32;
				$('#ichurch_chat_entries').animate({height:adjusted_height}, 150);
				$('div.jScrollPaneContainer').animate({height:adjusted_height_2}, 150);
				setTimeout (function() {
					autoScroll1($('#chat_entries_scroll'));
				}, 750);
			},
			extraSpace: 0,
			limit: 150
		});
		$('#ichurch_chat_textarea').keydown();
		setTimeout (function() {
			autoScroll1($('#chat_entries_scroll'));
		}, 1000);

		var scrollPos = 0;
		var personWidth = parseInt($('.chat_person').css('margin-left').replace("px", "")) + $('.chat_person').width();

		$('#ichurch_people_arrow_left').click(function(ev) {
			currentscroll = ($('#ichurch_people_scroller').width() - $('#ichurch_people_container').scrollLeft()) + ($('#ichurch_people_scroller').width() - $('#ichurch_people_container').width());
			ev.preventDefault();
			if ($('#ichurch_people_container').scrollLeft() > 0) {
				scrollPos = scrollPos - 62;
				$("#ichurch_people_container").animate({scrollLeft: scrollPos }, 500, function() {
					scrollArrowState(scrollPos);				
				});
			}
		});

		$('#ichurch_people_arrow_right').click(function(ev) {
			currentscroll = ($('#ichurch_people_scroller').width() - $('#ichurch_people_container').scrollLeft()) + ($('#ichurch_people_scroller').width() - $('#ichurch_people_container').width());
			nextscroll = currentscroll - personWidth;
			ev.preventDefault();
			if (nextscroll > ($('#ichurch_people_scroller').width())) {
				scrollPos = parseInt(scrollPos) + parseInt(personWidth);
				$("#ichurch_people_container").animate({scrollLeft: scrollPos }, 500, function() {
					scrollArrowState(scrollPos);
				});
				
			}
		});
		
		

		
	/*--INITIAL COUNTDOWN SETTINGS--*/
		event_id = jsvars['event_id'];
		countdown = jsvars['countdown_preroll'];
		countdownClock(countdown);
		countup = jsvars['countup'];
		time_left = jsvars['time_left'];
		if (countdown < 0 && time_left > 0 ) { live = true; } else { live = false; }




	/*--COUNTDOWN TIMER--*/
		countdown_timer = setInterval("videoStatus()", 1000);
		countdown_clock = setInterval(function() {
			countdownClock(countdown);
		}, 500);



		
	/*--INITIAL SYNC--*/
		json_url = jsvars['base_url'] + 'ichurch/video_status/';
		sync();
		
		action_url = jsvars['base_url'] + 'ichurch/get_action/';




	/*--SYNC EVERY 30 SECS--*/
		sync_timer = setInterval("sync()", 30000);


		
		
	/*--INITIATE CHAT ROOM--*/
		chat(1,jsvars['base_url'],'div#chat_entries_scroll','div#chat_entries_padding','input#ichurch_chat_send','textarea#ichurch_chat_textarea','div#ichurch_people_container','div#ichurch_people_scroller','div#ichurch_people_arrows',62);
		currentscroll = (($('#ichurch_people_scroller').width() - $('#ichurch_people_container').scrollLeft()) + ($('#ichurch_people_scroller').width() - $('#ichurch_people_container').width()));		




	/*--VERTICAL ALIGNMENT--*/
		$('.valign').each(function(){
			$(this).vAlign();
		});



});




	/*--DEFINE VARIABLES--*/
		var jsvars = new Array();
		var player = null;
		var count = 1;
		var synched = false;
		var volLevel = 0;
		var faded = false;
		var countup = 0;
		var starttime = 0;
		var buffer_count = 0;
		var buffering_now = false;
		//function update_starttime(countthis) {
		//	starttime = countthis + 3;
		//}
		var currentPosition = null;
		var currentState = null;
		var live;
		var liveStatus = false;
		var chatActive = false;
		var chatStatus = false;
		var time_left;
		var player_exists = false;
		var action_synched = false;
		var current_action = 1;
		var next_action = null;
		var event_id;
		var actionInterval = false;
		var starttime;
		var file_url;
		var	playSync = false;
		var countdownActive = true;
		var clockFinished = false;
		var length;


		

	/*--AUTOSCROLL: automatically scrolls the chat room entries pane--*/
		
		function autoScroll1(element) {
			var autoScroll = element.data('jScrollPanePosition') == element.data('jScrollPaneMaxScroll');
			element.jScrollPane({showArrows:true, animateTo:true, animateInterval:25});
			if (autoScroll) {
				element[0].scrollTo(element.data('jScrollPaneMaxScroll'));
			}
		}




	/*--SCROLLARROWSTATE: change the status of the chat people scroll arrows based on how many people are listed--*/
		
		function scrollArrowState(scrollPos) {
			personWidth = parseInt($('.chat_person').css('margin-left').replace("px", "")) + $('.chat_person').width();
			
			if (($('div#ichurch_people_scroller').width() - (scrollPos + personWidth)) <= $('div#ichurch_people_container').width()) { 
				//Deactivate Right
				$('a#ichurch_people_arrow_right').animate({opacity: .5}).css({cursor: 'default'});
			} else {
				//Activate Right
				if ($('a#ichurch_people_arrow_right').css('cursor') != 'pointer') {
					$('a#ichurch_people_arrow_right').animate({opacity: 1}).css({cursor: 'pointer'});
				}
			}
			
			if ($('#ichurch_people_container').scrollLeft() <= 0) {
				//Deactivate Left
				$('a#ichurch_people_arrow_left').animate({opacity: .5}).css({cursor: 'default'});
			} else {
				//Activate Left
				if ($('a#ichurch_people_arrow_left').css('cursor') != 'pointer') {
					$('a#ichurch_people_arrow_left').animate({opacity: 1}).css({cursor: 'pointer'});
				}
			}
			
			if ($("div#ichurch_people_scroller").width() > $('div#ichurch_people_container').width()) {
				$("div#ichurch_people_arrows").fadeIn(1000);
			} else {
				$("div#ichurch_people_arrows").fadeOut(1000);
			}
			return true;
		}




	/*--VIDEO TIMING FUNCTIONS--*/

		function sync() {
			ts = Math.round(new Date().getTime() / 1000);
			ts_json_url = json_url + ts;
			$.getJSON(ts_json_url, function(data) {
				//$("#debug").html(data.timing.countdown_preroll);
				countdown = data.timing.countdown_preroll;
				countup = data.timing.countup;
				time_left = data.timing.time_left;
				event_id = data.info.event_id;
				length = data.info.length;
			});
		}
		
		function videoStatus() {

			//Update timer vars
			countdown = parseInt(countdown) - 1;
			countup = parseInt(countup) + 1;
			time_left = parseInt(time_left) - 1;
			
			//Determine if chat should be active
			if (countdown < 901) { chatActive = true; } else { chatActive = false; }
			
			//Determine if we should be live
			if (countdown < 0 && time_left > 0 ) { live = true; } else { live = false; }
			
			if (live == true && liveStatus == false) {
				//Go live
				liveStatus = true;
				file_url = jsvars['xml'];
				swf_url = jsvars['flash'] + 'player_licensed_4.swf';
				starttime = countup;
				createPlayer(file_url,null,swf_url,true,starttime);
				if (!actionInterval) {
					actionInterval = setInterval(function() {
						getAction();
					}, 1000);				
				}
			} else if (live == false && liveStatus == true && current_action >= (length - 5)) {
				//Go dark
				$('#ichurch_video_black').fadeIn(1000, function() {
					swfobject.removeSWF("player1");
					$('div#ichurch_video_countdown').show();
					$('#ichurch_video_countdown_text').show();
					$("#ichurch_video_countdown_clock").css({'width' : '400px'});
					setTimeout(function() {
						sync();
						setTimeout(function() {
							$('#ichurch_video_black').fadeOut(1000);
						}, 1000);
					}, 1000);				
				});
				clearInterval(actionInterval);
				liveStatus = false;
			}
			
			if (chatActive == true && chatStatus == false) {
				$('div#ichurch_schedule').fadeOut('slow');
				chatStatus = true;
			}
		}
		
		function startPlayback() {
			setTimeout(function(){
				player.sendEvent('play');
			}, 2500);
		}


	/*--SETACTION: set the action in HTML--*/
		function setAction() {
			ts = Math.round(new Date().getTime() / 1000);
			ts_action_url = action_url + event_id + '/' + current_action + '/' + ts;
			$.getJSON(ts_action_url, function(data) {
				if ($("div#ichurch_live_text_valign").html() != data.current.content) {
					$("div#ichurch_live_text_valign").fadeOut(500, function() {
						$(this).html(data.current.content).vAlign().fadeIn(500);
					});
					if (data.next.time) { next_action = data.next.time; }
					action_synched = true;
				}
			});
		}


	/*--GETACTION: retrieve latest actions over JSON--*/
		function getAction() {
			if (action_synched != true && currentPosition > 2) {
				setAction();
			} else if (current_action >= next_action) {
				setAction();
			}
		}


	/*--VIDEO COUNTDOWN FUNCTIONS--*/
		function padout(number) { return (number < 10) ? '0' + number : number; }
		
		function countdownClock(countdown) {
			var day = parseInt(countdown) / 86400;
			day = Math.floor(day);
			
			var minus = (day * 24);
					  
			var hour = (parseInt(countdown) / 3600) - minus;
			hour = Math.floor(hour);
			
			var min = (parseInt(countdown) / 60) % 60;
			min = Math.floor(min);
			
			var sec = parseInt(countdown) % 60;
			sec = Math.floor(sec);
			
			daydisplay = "Days";
			if (day == 1) { daydisplay = "Day"; }
			
			hourdisplay = "Hours";
			if (hour == 1) { hourdisplay = "Hour"; }
			
			mindisplay = "Minutes";
			if (min == 1) { mindisplay = "Minute"; }
			
			secdisplay = "Seconds";
			if (sec == 1) { secdisplay = "Second"; }
			
			var end_divide_width = 0;
			
			if (min < 1 && sec < 1 && countdownActive == true) {
				$("#ichurch_video_countdown_text").fadeOut(1500);
				$("#ichurch_video_black").fadeIn(1500, function() {
					setTimeout(function() {
						$("#ichurch_video_black").fadeOut(1500);
						countdownActive = false;
					}, 1500);
				});
				return true;
			}
			
			if ($("div#ichurch_video_countdown_text h1").html() != "Our next service starts in" && clockFinished == false) {
				$("div#ichurch_video_countdown_text h1").html("Our next service starts in");
				$("div#ichurch_video_countdown_clock").show();
			}
			
			if (day > 0 && $("#countdown_dy_number").html() != day) {
				$("#countdown_dy_number").html(day);
				$("#countdown_dy_footer").html(daydisplay);
				$("#countdown_dy").show();
			} else if (day <= 0) { 
				$("#countdown_dy").hide();
				$("#ichurch_video_countdown_clock").css({'width' : '300px'});
			}
			
			if (hour <= 0 && day <= 0) {
				$("#countdown_hr").hide();
				$("#ichurch_video_countdown_clock").css({'width' : '200px'});
			} else if ($("#countdown_hr_number").html() != hour) {
				$("#countdown_hr_number").html(hour);
				$("#countdown_hr_footer").html(hourdisplay);
				$("#countdown_hr").show();
			}
			
			if (min <= 0 && hour <= 0 && day <= 0) {
				$("#countdown_mn").hide();
				$("#ichurch_video_countdown_clock").css({'width' : '100px'});
			} else if ($("#countdown_mn_number").html() != min) {
				$("#countdown_mn_number").html(min);
				$("#countdown_mn_footer").html(mindisplay);
				$("#countdown_mn").show();
			}

			if (min <= 0 && hour <= 0 && day <= 0 && sec <= 0 && parseInt(countdown) <= 0) {
				$("#countdown_sc").hide();
				$("#ichurch_video_countdown_clock").css({'width' : '0px'});
				clockFinished = true;
			} else if ($("#countdown_sc_number").html() != sec) {
				$("#countdown_sc_number").html(sec);
				$("#countdown_sc_footer").html(secdisplay);
				$("#countdown_sc").show();
			}
		}




	/*--VIDEO PLAYBACK FUNCTIONS--*/

		function playerReady(thePlayer) {
			player = document.getElementById(thePlayer.id);
			addListeners();
		}
		
		function addListeners() {
			if (player) { 
				player.addModelListener("STATE", "stateListener");
				player.addModelListener("TIME", "timeListener");
			} else {
				setTimeout("addListeners()",100);
			}
		}
		
		function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
			currentState = obj.newstate; 
			previousState = obj.oldstate;
		}
		
		
		function timeListener(obj) {
			currentPosition = obj.position;
			current_action = Math.floor(obj.position);
			var drift = countup - current_action;
			if (drift >= 10) {
				player.sendEvent('SEEK', countup);
			}
			$("#debug3").html(drift);
		}
					
		function createPlayer(file_url,plugin,swf_url,autostart,starttime) {
		   	file_url = file_url;
		    var flashvars = {
		            stretching:"uniform",
					plugins:"gapro-1",
		            "gapro.accountid":"UA-74996-16",
		            "gapro.idstring":"||title||",
		            controlbar:"none",
		            dock:"true",
		            shownavigation:"false",
		            displayclick:"fullscreen",
		            volume:100,
		            "http.startparam":"starttime"
		    }
		    flashvars['file'] = file_url;
		    //flashvars['plugins'] = 'qualitymonitor-2';
		    flashvars['autostart'] = autostart;
		    var params = {
		            allowfullscreen:"true", 
		            allowscriptaccess:"always",
		            wmode:"transparent"
		    }
		    var attributes = {
		            id:"player1",
		            name:"player1"
		    }

		    swfobject.embedSWF(swf_url, "ichurch_video_player", "600", "338", "9.0.115", false, flashvars, params, attributes);
		    player_exists = true;
		}