/**
 * @author Ralph Sledge
 * @copyright 2007 AccuRadio, LLC
 * 
 * Requires:
 * jquery.js
 * jquery.cluetip.js
 * jquery.color.js
 * jquery.dimensions.js
 * jquery.hoverIntent.js
 * mootools.js
 * 
 * This is the javascript file that gets loaded when
 * the page that embeds the player is loaded.  This is not
 * the js for the player itself.
 * 
 */

// Helper for jquery
function h(s) {
	return "#" + s;
}

var IFRPlayer =
{
	divId: "div_ifr_player"
}

var Page = 
{
	bannerAdId: "banner_ad",
	
	isIEFlagBool: false,
	isIEBool: false,
	
	isIE: function() {
		if (!this.isIEFlagBool) {
			var ua = navigator.userAgent;
			if (ua.indexOf("MSIE") > -1) {
				this.isIEBool = true;
			}
			this.isIEFlagBool = true;
		}
		return this.isIEBool;
	}
}

var ChannelTable = 
{
	duration: 300,
	
	getA: function(divId) {
		var aId = parseInt(divId.split("_").getLast());
		return "#a_showhide_" + aId;
	},
	
	showHide: function(obj, showOnly) {
		var showOnly = showOnly ? showOnly : false;
		
		var divId = obj;
		var wrapId = obj + "_wrapper";
		
		var currHeight = $("#" + wrapId).height();
		if (currHeight > 0 && !showOnly) {
			// hide
			$('#' + wrapId).animate({
				height: 0 + "px"
			}, this.duration);
			$(this.getA(divId)).html("Show subchannels");
		} else {
			// show
			var newHeight = $('#' + divId).height();
			$('#' + wrapId).animate({
				height: newHeight + "px"
			}, this.duration, null, function() {
				$('#' + wrapId).css("height", "auto");
			});
			$(this.getA(divId)).html("Hide subchannels");
		}
	}
}

var ChannelForm = 
{
	divId: "div_form_channel",
	formId: "form_channel",
	updateStatusId: "span_update_status",
	
	dropped: false,
	toColor: "#ffffff",
	
	/*
	select: function(obj) {
		var cbId = "cb_channel_" + obj.value;
		document.getElementById(cbId).click();
	},
	*/
	
	select: function(obj) {
		var dtId = "div_table_" + obj.value + "_wrapper";
		var dtObj = $("#" + dtId);
		var inputs = dtObj.find("input");
		inputs[0].click();
	},
	
	/** Takes the id of an input item on the form in the channel
	 * and returns the id of the string surrounding it. Uses
	 * mootools arrays.
	 *
	 * @param o {Object|int|string} javascript object of the input control
	 * @returns {string} id of the surrounding <td>
	 */
	getTdId: function(o) {
		var out = "";
		
		var t = typeof(o);
		switch (t) {
			case "object":
				out = "td_channel_" + o.value;
				break;
			case "number":
				out = "td_channel_" + o;
				break;
			case "string":
				strId = o.split('_').getLast()
				out = "td_channel_" + strId;
				break;
		}
		
		return out;
	},
	
	/** (yui cruft for later porting)
	 * 
	 * @param id {string} id of the input to highlight
	 */
	/*
	setCellAsPlaying: function(id) {
		var tdId = this.getTdId(id);
		YAHOO.util.Dom.setStyle(tdId, 'border-color', '#FFFFFF');
	},
	*/
	
	/** (yui cruft for later porting)
	 * 
	 * @param id {string} id of the input to un-highlight
	 */
	/*
	setCellAsNotPlaying: function(id) {
		var tdId = this.getTdId(id);
		var normalBgColor = YAHOO.util.Dom.getStyle(this.divId, "background-color");
		YAHOO.util.Dom.setStyle(tdId, 'border-color', normalBgColor);
	},
	*/
	
	/** Scans through the label tags in the Channel Form, and puts a
	 * border around those whose value is contained in cnames.  Uses
	 * mootools arrays.
	 * 
	 * (yui cruft for later porting)
	 *
	 * @param cnames {string} json-encoded array of channel names
	 */
	/*
	scanAndSetAsPlaying: function(cnames) {
		var jnames = false;
		
		try {
			jnames = YAHOO.lang.JSON.parse(cnames);
		} catch (e) {}
		
		if (jnames) {
			var f = document.getElementById(this.formId);
			var labels = f.getElementsByTagName("label");
			for (var i=0; i<labels.length; i++) {
				if (jnames.contains(labels[i].innerHTML)) {
					this.setCellAsPlaying(this.getTdId(labels[i].htmlFor));
				} else {
					this.setCellAsNotPlaying(this.getTdId(labels[i].htmlFor));
				}
			}
		}
	},
	*/
	scanAndSetAsPlaying: function(cnames) {},
	
	// Dummy so that the last element ends correctly and IE doesn't freak out
	zzz: {}
}


/** Set the cookie for the BYO player
 * 
 * @param {Object} callback The function to call on success/failure
 */
ChannelForm.setBYOCookie = function(callback) {
	var postvars = $("#" + this.formId).serialize();
	$.ajax({
		type: "POST",
		url: '/player/set_byo_cookie/',
		data: postvars,
		complete: callback.complete,
		error: callback.error
	});
}

/** Process the selected channels and launch the player.
 * "drop" is a crufty name, from when the channel table 
 * "dropped" to reveal the player.
 * 
 * This function lacks a throbber.
 */
ChannelForm.drop = function() {
	if (!this.dropped) {
		// Player has been launched for the first time
		var offset = $("#" + this.divId);
		
		var callback =
		{
			complete: function(x, t) {
				$("#" + ChannelForm.formId).unbind("submit").submit();
			},
			
			error: {}
		}
		this.setBYOCookie(callback);
		
		// Set flag so that the div doesn't get dropped again
		this.dropped = true;
		
		// This maybe ought to go somewhere else
		var f = document.forms[this.formId];
		f.form_channel_submit1.value = "Update selections";
		f.form_channel_submit2.value = "Update selections";
	} else {
		// Player is playing
		
		// Set the cookie via XHR, and then set the deselect flag in the player
		var callback =
		{
			complete: function(x, t) {
				var player = false;
				try {
					player = window.frames["ifr_player"];
				} catch (ex) {}
				if (player) {
					try {
						player.acSetDs();
					} catch (ex) {}
				}
				ChannelForm.updateAlert("Player updated.");
			},
			
			error: function(x, t, e) {
				ChannelForm.updateAlert("Player not updated!");
			}
		}
		this.setBYOCookie(callback);
	} 
}

/** Put text into the update_status div and flash the background color
 * 
 * @param {Object} alertText Text to add to the span
 */
ChannelForm.updateAlert = function(alertText) {
	var us = $(h(ChannelForm.updateStatusId));
	us.html(alertText);
	
	us.css("backgroundColor", "#e06");
	
	// Better than YUI because it seems to work across 
	// browsers predictably, but worse because the color
	// animation doesn't take the 'transparent' value
	// (this might have been what was causing problems with YUI
	// anyway)
	
	var toColor = $("#" + ChannelForm.divId).css("background-color");
	if (toColor == "transparent") {
		toColor = $('body').css("background-color");
		if (toColor == "transparent") {
			toColor = this.toColor;
		}
	}
	
	ChannelForm.updateTextDefaultColor = us.css("color");
	us.animate({
		backgroundColor: toColor
	}, 7000).animate({
		color: toColor
	}, 3000, null, function() {
		var us = $("#" + ChannelForm.updateStatusId);
		us.html("");
		us.css("color", ChannelForm.updateTextDefaultColor);
	});	
}

/** Color the background of the table cell of a 
 * selected subchannel
 * 
 * @param {Object} o A checkbox object
 */
ChannelForm.setCellBg = function(o) {
	var tdId = this.getTdId(o);
	
	if (o.checked) {
		$('#' + tdId).addClass("css_channel_highlight");
	} else {
		$('#' + tdId).removeClass("css_channel_highlight");
	}
	
	ChannelForm.indicateSelection(o);
}

/** Scan all the tables, coloring the background
 * for all checked boxes and expanding the tables
 * as necessary.
 */
ChannelForm.scanAndSetBg = function() {
	var inputs = $('#' + ChannelForm.formId).find('input[checked]');
	inputs.each(function(i) {
		ChannelForm.setCellBg(this);
		ChannelForm.expandGroup(this);
	});
}

/** Expand the group a checked box is in
 * 
 * @param {Object} o A checkbox object
 */
ChannelForm.expandGroup = function(o) {
	// Find the parent table's DIV
	var x = $('#' + o.id).parents(".table_channels_body")[0];
	ChannelTable.showHide(x.id, true);
}

/** Color the primary channel header of boxes with 
 * selections.
 * 
 * @param {Object} o Checkbox object
 */
ChannelForm.indicateSelection = function(o) {
	// Find the parent DIV wrapper
	var x = $('#' + o.id).parents('.table_channels_wrapper:first');
	
	// The the header underneath that DIV
	var header = $(x).find('.css_selection_indicator:first');
	
	if (header) {
		if (o.checked) {
			//$(header).css("color", "#FDE95B");
			header.children("span").addClass("css_selection_indicated");
			ChannelForm.header = header;
		} else {
			// Need to check and see if any of the checkboxes
			// are still checked
			var c = $(x).find("input[checked]");
			if (c.length <= 0) {
				//$(header).css("color", "#FFFFFF");
				header.children("span").removeClass("css_selection_indicated");
			}
		}
	}
}

// set the clueTip hover boxes
$(document).ready(function() {
	$('td.td_channel_class').cluetip({
		positionBy: 'mouse',
		cluetipClass: 'byo',
		fx: {
			open: 'fadeIn'
		},
		hoverIntent: {
			sensitivity: 3,
			interval: 100
		}
	});
});
