/* Teaching.js */

var graceChapel;
if(!graceChapel) graceChapel = {};

window.addEvent('domready', function() {
	if($('home-page')) {
		graceChapel.chooser = new Chooser({});
		graceChapel.checkLiveStream = new CheckLiveStream({
			testMode: 0
		});
	} else {
		if($('latest-message')) activateMsgControls();
	}
}); // end domready

// -----------------------------------------------------------------------------
// MP3 Player Class
// -----------------------------------------------------------------------------

var MP3Player = new Class({
	initialize: function(options) {
		this.date = options.date;
		this.el = $(options.el);
	},
	build: function() {
		this.el.set('html', '');
	
		this.file = "http://a4.g.akamai.net/7/4/29062/v1/multicastsmb.download.akamai.com/29062/MP3/" + this.date + ".mp3";
		this.so = new SWFObject('/swf/mp3player.swf', "mp3player", "340", "20", "8", "#ffffff");
		this.so.addVariable("file", this.file);
		this.so.addVariable("volume", "60");
		this.so.addVariable('autostart', true);
		
		
		$('latest-message').setStyles({
			'background-image':'none',
			'background-color':'#000000'
		});
	
		// find the starting height
		var startHeight = this.el.getStyle('height');
		
		var myFx = new Fx.Morph($('latest-message'), {transition: Fx.Transitions.Quart.easeInOut, duration: 1000, onComplete: this.populate.bind(this)});
		myFx.start({
			'height': 140,
			'background-color':'#8b3d13'
			});
	},
	directLink: function() {
		var lnk = new Element('a');
		lnk.setProperties({
			href: this.file
		});
		lnk.setStyles({
			'display': 'block',
			'margin-top': '14px'
		});
		lnk.set('html', 'MP3 Download Link');
		this.el.adopt(lnk);
	},
	populate: function() {
		this.so.write(this.el);
		this.directLink();
	}
});


// -------------------------------------------------------------------------------------------------
// Vidego Flash Player Class
// -------------------------------------------------------------------------------------------------
var VidegoPlayer = new Class({
	initialize: function(options) {
		this.date = options.date;
		this.el = $(options.el);

	},
	build: function() {
		this.el.set('html', '');
		
		if($('videgoId')) this.videgoId = $('videgoId').get('text');
		
		this.vidego = new Element('iframe', {
			'width':'560px',
			'height':'480px',
			'frameborder':'no',
			'scrolling':'no',
			'src':'http://vidego.multicastmedia.com/player.php?v=' + this.videgoId
		});
	
		// find the starting height
		var startHeight = this.el.getStyle('height');
		
		var myFx = new Fx.Morph($('latest-message'), {transition: Fx.Transitions.Quart.easeInOut, duration: 1500, onComplete: this.populate.bind(this)});
		
		// Update: Clear out possible background image underneath the area where the player will appear and reset positioning of related elements.
		
		$('latest-message').setStyles({
			'background-image':'none',
			'background-color':'#000000'
		});
		
		myFx.start({
			'height': ['580px'],
			'background-color':'#8b3d13'
			});
	},
	directLink: function() {
	
		var lnk = new Element('a');
		lnk.setProperties({
			href: this.url
		});
		lnk.setStyles({
			'display': 'block',
			'margin': '14px 0'
		});
		lnk.set('html', 'Video Direct Link');
		this.el.adopt(lnk);
	},
	fbLink: function() {
		var fbLink = new Element('a', {
			'href':'http://www.facebook.com/sharer.php?u=http://vidego.multicastmedia.com/player.php?v=' + this.videgoId + '&t=Video from Grace Chapel',
			'class':'facebook',
			'target':'_blank'
		}).set('html', 'Share this Video on Facebook');
		
		var fbLi = new Element('li').adopt(fbLink);
		
		var ul = new Element('ul', {
			'class':'connect'
		}).adopt(fbLi);
		this.el.adopt(ul);
	},
	populate: function() {
		this.el.adopt(this.vidego);
		this.fbLink();
	}
});

// -------------------------------------------------------------------------------------------------
// CheckLiveStream Class: Changes the page when the live stream is active.
// -------------------------------------------------------------------------------------------------
var CheckLiveStream = new Class({
	initialize: function(options) {
		if(options.testMode === 1) {
			this.interval = 5000;
			this.testReps = 100;
		} else {
			this.interval = 30000;
			this.testReps = 180;
		}
		this.periodicalId = this.poll.bind(this).periodical(this.interval);
		this.counter = 0;
		this.preload = 1;
		this.loadingDiv = $('loading');
		this.container = $('latest-message-container');
		this.noticeContainer = $('message-notice-container');
		this.poll();
	},
	poll: function(force) {
		
		var query;
		
		if(this.preload === 1) {
			query = 'p=poll_livestream&preload=1';
		} else {
			query = 'p=poll_livestream';
		}
		
		switch(force) {
			case 'flash':
				query += '&force=flash';
				break;
			case 'chooser':
				query += '&force=chooser';
				break;
			}
		
		var request = new Request.JSON({
			url: '/services.php',
			evalResponse: 'true',
			method: 'post',
			onSuccess: this.pollCallback.bind(this)
		}).send(query);
	},
	pollCallback: function(response) {
		if(this.loadingDiv) {
			this.loadingDiv.dispose();
			this.preload = 0;
		}
		
		var stream = response[0];
		var message = response[1];
		var notice = response[2];

		if(stream == '1') {
			this.clearPeriodical();
			this.noticeContainer.empty();
			this.container.set('html', message);
			if($('stream-chooser')) {
				graceChapel.chooser.addBtnEvents();
			} else {
				graceChapel.chooser.createChooseLink();
			}
		} else {
			this.counter++;
			if(this.counter > this.testReps) this.clearPeriodical(); // 360 --> every 15 seconds for 90 minutes
			// Only load the message the first time.
			if(message != 0) {
				this.container.set('html', message);
				activateMsgControls();
			}
			if(notice != 0) {
				if(this.noticeContainer.get('html').length < 1) this.counter = 0; // reset counter if the "services begin soon" notice comes up
				this.noticeContainer.set('html', notice);
			}
		}
	},
	clearPeriodical: function() {
		this.periodicalId = $clear(this.periodicalId);
	}
});



// -------------------------------------------------------------------------------------------------
// Chooser Class: 
// -------------------------------------------------------------------------------------------------
var Chooser = new Class({

	Binds: ['chooseIOS'],
	Binds: ['chooseStd'],
	Binds: ['chooseChooser'],

	initialize: function() {	
		//console.log('chooser init');
		this.iOSStreamURL = 'http://174.129.242.53/GraceChapel/iPhone/playlist.m3u8';
	},
	addBtnEvents: function() {
	
	
	this.iOSStreamURL = 'http://174.129.242.53/GraceChapel/iPhone/playlist.m3u8';
	
	this.iosBtn = $('choose-iOS');
	this.stdBtn = $('choose-std');
	
	if(this.iosBtn) {			
			this.iosBtn.addEvent('click',
				this.chooseIOS
			);
		};
		if(this.stdBtn) {			
			this.stdBtn.addEvent('click',
				this.chooseStd
			);
		};
	},
	chooseIOS: function(evt) {
		(new Event(evt)).stop();
		// need to figure out how to use this.iOSStreamURL instead. Bind... bleargh.
		window.location = 'http://174.129.242.53/GraceChapel/iPhone/playlist.m3u8';
	//		window.location = this.iOSStreamURL;
		
	},
	chooseStd: function(evt) {
		(new Event(evt)).stop();
		
		graceChapel.checkLiveStream.preload = 1;
		graceChapel.checkLiveStream.poll('flash');
	},
	chooseChooser: function(evt) {
		(new Event(evt)).stop();
		
		graceChapel.checkLiveStream.preload = 1;
		graceChapel.checkLiveStream.poll('chooser');
	},
	stdCallback: function() {
	
	},
	createChooseLink: function() {
	
		this.chooseLink = new Element('a', {
			'href':'/',
			'html': 'Additional Viewing Options',
			styles: {
				display: 'block',
				height: '20px',
				color: '#fff',
				margin: '10px 0',
				'font-size': '.8em',
				'padding-left': '20px',
				'background-image': 'url(/images_ui/silk_icons/information.png)',
				'background-repeat': 'no-repeat',
				'background-position': '0px 3px'
			},
			events: {
				click: this.chooseChooser
			}
		}).inject($('livestream'), 'after');
	}
});

// -------------------------------------------------------------------------------------------------
// Function: If there's an archived message showing, assign events to the buttons and controls
// -------------------------------------------------------------------------------------------------
function activateMsgControls() {
	
		//graceChapel.notesDisplay = new NotesDisplay({});
		
		var browser = $('browser-type').innerHTML;
		var videoDirectURL = $('video-direct-url').get('text');
		var audioDirectURL = $('audio-direct-url').get('text');
		
		if($('msg-date')) {
			graceChapel.mp3player = new MP3Player({
				date: $('msg-date').innerHTML,
				el: 'media-playback'
			});
		}

		
		if($('msg-date')) {
			graceChapel.videgoPlayer = new VidegoPlayer({
				date: $('msg-date').innerHTML,
				el: 'media-playback'
			});
		}
		
		
		if($('mp364-listen')) {			
			$('mp364-listen').addEvent('click',
				function(evt) {
					(new Event(evt)).stop();
					
					if(browser == 'iOS') {
						window.open(audioDirectURL);
					} else {
						graceChapel.mp3player.build();
					}
					
				}
			);
		};

		if($('btn-vidego')) {
			$('btn-vidego').addEvent('click',
				function(evt) {
					(new Event(evt)).stop();
					
					if(browser == 'iOS') {
						window.open(videoDirectURL);
					} else {
						graceChapel.videgoPlayer.build();
					}
					
					
				}
			);
		};


}

// -------------------------------------------------------------------------------------------------
// NotesDisplayt Class: Display the Message Notes
// -------------------------------------------------------------------------------------------------
var NotesDisplay = new Class({
	initialize: function(options) {
		this.div = $('msg-notes');
		//console.log(this.div);
		this.btn = $('btn-scripture');
		this.id = $('msg-id').innerHTML;
		this.maxHeight = $('home-page') ? '400px' : '400px'; 
		this.fx = new Fx.Morph(this.div,{transition: Fx.Transitions.Quint.easeInOut, duration: 1500});
		this.btn.addEvent('click', function(evt) {
			new Event(evt).stop();
			this.toggle();
		}.bindWithEvent(this));
	},
	toggle: function() {
		if(this.div.getStyle('height') != '0px') {
			this.hide();
		} else {
			this.show();
		} 
	},
	show: function() {
		
		new Request.JSON({
			url: '/services.php',
			onSuccess: this.ajaxCallback.bind(this)
		}).get({'p': 'msg_notes', 'id': this.id});
	},
	hide: function() {
		//console.log('hide');
		this.fx.start({'height':[this.maxHeight,'0px'], onComplete: function() {this.div.set('html', '');}.bind(this)});
	},
	ajaxCallback: function(responseJSON, responseText) {
		this.div.setStyles({
			'display':'block',
			'height':'0px',
			'overflow':'auto'
		});
				
		var enclosingDiv = new Element('div', {
			'styles': {
				'padding':'10px',
				'background-color':'#7b1a19'
			}
		});
		
		var responseType = responseJSON[0];
		var responsePayload = responseJSON[1];

		if(responseType === 'file') {
			
			this.maxHeight = '60px';
			
			var downloadLink = new Element('a', {
				'href':'/media/sermons/' + this.id + '/' + responsePayload,
				'class':'download pdf'
			}).set('html', 'Download message notes in PDF format. (Right-click, choose Save As...)');
			
			enclosingDiv.adopt(downloadLink);
		} else if(responseType === 'text' || responseType === 'none') {
			if(responseType === 'none') this.maxHeight = '60px';
			enclosingDiv.set('html', responsePayload);
		}
		
		this.fx.start({'height':['0px',this.maxHeight]});
	
		this.fade = new Fx.Tween(enclosingDiv).set('opacity', '0');
		
		this.div.adopt(enclosingDiv);
		this.fade.start('opacity', '0', '1');
		
	}
});

// -------------------------------------------------------------------------------------------------
// HelpDisplay Class: Display the Message Notes
// -------------------------------------------------------------------------------------------------
var HelpDisplay = new Class({
	initialize: function(options) {
		this.state = 'closed';
		this.testMode = options.testMode;
		this.file = options.file;
		this.div = options.div;
		this.btn = options.btn;
		this.maxHeight = '150px';
		
		this.fx = new Fx.Morph(this.div,{transition: Fx.Transitions.Quint.easeInOut, duration: 1500});
		this.btn.addEvent('click', function(evt) {
			new Event(evt).stop();
			this.toggle();
		}.bindWithEvent(this));
	},
	toggle: function() {
		//console.log('height: ' + this.div.getStyle('height'));
		if(this.div.getStyle('height') != '0px') {
			this.hide();
		} else {
			this.show();
		}
	},
	show: function() {
		this.div.setStyles({
			'display':'block',
			'height':'0px',
			'overflow':'auto'
		});
		this.fx.start({'height':['0px',this.maxHeight]});
		
		new Request.HTML({onSuccess: this.ajaxCallback.bind(this)}).get(this.file);
		this.state = 'open';
	},
	hide: function() {
		//console.log('hide');
		this.fx.start({'height':[this.maxHeight,'0px'], onComplete: function() {this.div.set('html', '');}.bind(this)});
	},
	ajaxCallback: function(responseTree, responseElements, responseHTML, responseJavaScript) {
		//console.log('yeah');
		var enclosingDiv = new Element('div', {
			'styles': {
				'padding':'10px',
				'margin': '5px'
			}
		});
		enclosingDiv.set('html', responseHTML);
		this.div.adopt(enclosingDiv);
		
	}
});
