/**
 * @author Ralph Sledge
 * @copyright 2007 AccuRadio LLC
 * 
 * Abstracted (i.e. non mtype-specific) player commands
 * 
 * @requires jquery.js
 * @requires jquery.ui.js
 * @requires json_parse.js
 * @requires [iewm9.js|swf.js]
 */

/**
 * Returns true if needle in in array haystack, true otherwise.
 * If 'element' is specified, the array is treated as associative
 * (or as an Object) and returns true if 'element' is found equal to 'needle'.
 * 
 * @param {Object} haystack
 * @param {Object} needle
 * @param {Object} element
 */
function inArray(haystack, needle, element) {
	element = element ? element : false;
	
	var found = false;
	for (var i=0; i < haystack.length; i++) {
		if (element) {
			if (haystack[i][element] == needle) {
				found = true;
				break;
			}
		}
		else {
			if (haystack[i] == needle) {
				found = true;
				break;
			}
		}
	}
	return found;
}

function removeDupesFromArray(arr, element) {
	element = element ? element : false;
	
	var newarr = [];
	for (var i=0; i < arr.length; i++) {
		if (element) {
			if (!inArray(newarr, arr[i][element], element)) {
				newarr.push(arr[i]);
			}
		}
		else {
			if (!inArray(newarr, arr[i], false)) {
				newarr.push(arr[i]);
			}
		}
	}
	return newarr;
}

var Controls =
{
	imgPlayId: "img_control_play",
	imgPauseId: "img_control_pause",
	imgSkipId: "img_control_skip",
	
	play_default: "control_play_out",
	pause_default: "control_pause_out",
	skip_default: "control_skip_out",
	
	play_over: "control_play_over",
	pause_over: "control_pause_over",
	skip_over: "control_skip_over",
	
	swapBtn: function(obj, state) {
		var strState = state ? state : "out";
		var re = /(over|out|down)/;
		var s = obj.src;
		s = s.replace(re, strState);
		obj.src = s;
	},
	
	playOver: function() {
		document.images[Controls.imgPlayId].src = document.images[Controls.imgPlayId].src.replace(Controls.play_default, Controls.play_over);
	},
	
	playOut: function() {
		document.images[Controls.imgPlayId].src = document.images[Controls.imgPlayId].src.replace(Controls.play_over, Controls.play_default);
	},
	
	pauseOver: function() {
		document.images[Controls.imgPauseId].src = document.images[Controls.imgPauseId].src.replace(Controls.pause_default, Controls.pause_over);
	},
	
	pauseOut: function() {
		document.images[Controls.imgPauseId].src = document.images[Controls.imgPauseId].src.replace(Controls.pause_over, Controls.pause_default);
	},
	
	skipOver: function() {
		document.images[Controls.imgSkipId].src = document.images[Controls.imgSkipId].src.replace(Controls.skip_default, Controls.skip_over);
	},
	
	skipOut: function() {
		document.images[Controls.imgSkipId].src = document.images[Controls.imgSkipId].src.replace(Controls.skip_over, Controls.skip_default);
	},
	
	attach: function() {
		$('#' + Controls.imgPlayId).bind("mouseover", this.playOver).bind("mouseout", this.playOut);
		$('#' + Controls.imgPauseId).bind("mouseover", this.pauseOver).bind("mouseout", this.pauseOut);
		$('#' + Controls.imgSkipId).bind("mouseover", this.skipOver).bind("mouseout", this.skipOut);
	}
}

var Cover = 
{
	imgId: "img_cover_1",
	errCount: 0,
	
	coverErr: function(obj) {
		if (this.errCount < 10) {
			document.getElementById(this.imgId).src = "/static/images/cover_nolink.gif";
			this.errCount++;
		} else {
			this.errCount = 0;
		}
	}
}

var Volume = 
{
	curVol: 120,
	divId: "div_volume"
}

Volume.curVol = 70;
Volume.create = function() {
	$('#' + this.divId).slider({
		min: 0,
		max: 100,
		startValue: Volume.curVol,
		change: function(e, ui) {
			acVolume(ui.value);
			return false;
		}
	});
}

Volume.setVolume = function(toVolume) {
    $('#' + this.divId).slider('moveTo', toVolume);
}

function setUIVolume(toVolume) {
    Volume.setVolume(toVolume);
}

var Stats =
{
	statId: "span_information_list",
	
	setListFrom: function(jdata) {
		var lists = false;
		
		try {
			lists = json_parse(jdata);
		} catch (e) {}
		
		if (lists) {
			var out = "<strong>from channel</strong> ";
			if (lists.length > 1) out = "<strong>from channels</strong> ";
			out += "<i>" + lists.join(", ") + "</i>";
			$('#' + Stats.statId).html(out);
		} else {
			$('#' + Stats.statId).html(jdata);
		}
		
	}
}

var Welcome = 
{
	divId: "div_welcome",
	
	hide: function() {
		$('#' + Welcome.divId).hide();
		
		// Does this affect BYO/AccuSongs negatively?
		$('#div_list_information').show();
	}
}

// Dummy function which can be redefined later
// (this ought to be implemented as a callback)
function changeInfoFinished(jsData) {}

// Object to format song data
function InfoFormat (jsData) {
	this.jsData = jsData;
	this.prepare();
	this.format();
}

InfoFormat.prototype.truncateAt = 50;

InfoFormat.prototype.toEscape = new Array(
	"title", "artist", "album", "year", "listfrom", "cdcover", "label", "composer");

InfoFormat.prototype.toTruncate = new Array(
	"title", "artist", "album", "label", "composer");

InfoFormat.prototype.whichLink = function () {
	var asin = this.jsData["asin"];
	var buyalbum = this.jsData["buyalbum"];
	var buylink = "http://www.amazon.com";
	
	if (buyalbum != undefined && buyalbum != null && buyalbum != "") {
		buylink = buyalbum;
	} else if (asin != undefined && asin != null && asin != "") {
		buylink = "http://www.amazon.com/exec/obidos/ASIN/" + asin + "/accuradio/";
	}
	
	return buylink;
}

InfoFormat.prototype.escape = function() {
	for (i in this.toEscape) {
		var key = this.toEscape[i];
		this.jsData[key] = unescape(this.jsData[key]);
	}
}

InfoFormat.prototype.truncate = function() {
	for (i in this.toTruncate) {
		key = this.toTruncate[i];
		if (this.jsData[key].length > this.truncateAt) {
			this.jsData[key] = this.jsData[key].substring(0, this.truncateAt) + "...";
		}
	}
}

InfoFormat.prototype.prepare = function() {
	this.escape();
	this.truncate();
}

InfoFormat.prototype.format = function() {
	this.jsData["artist"] = "<strong>by</strong> " + this.jsData["artist"] + ", ";
	
	this.jsData["album"] = '<a target="_blank" href="' + this.whichLink() + '">' + this.jsData["album"] + '</a>';
	this.jsData["album"] = " <strong>from</strong> " + this.jsData["album"];
	
	this.jsData["year"] = " (" + this.jsData["year"] + ")";
}

/**
 * 
 * @param {Object} jsData Contains all the parameters for the currently-playing song
 * 
 * changeInfo ought to be an object (var changeInfo = function(jsData) {})
 * and changeCovers, changeMoney, songTrack, and changeInfoFinished ought to be
 * functions in that object
 */


var changeInfo = function(jsData, oCallChangeMoney) {
	var callChangeMoney = oCallChangeMoney ? callChangeMoney : false;
	
	//alert("changeInfo");
	changeInfo.jsData = jsData;
	
	// Welcome would be defined by player.js
	if (typeof(Welcome) != 'undefined') { Welcome.hide(); }
	
	if (jsData["title"] != "undefined") {
		
		var infoFormat = new InfoFormat(jsData);
		var formatData = infoFormat.jsData;
		
		$('#span_information_title').html(formatData["title"]);
		$('#span_information_artist').html(formatData["artist"]);		
		$('#span_information_album').html(formatData["album"]);
		$('#span_information_year').html(formatData["year"]);
		$('#span_information_label').html(formatData["label"]);
		$('#span_information_composer').html(formatData["composer"]);
		
		if (typeof(Stats) != 'undefined') {
			Stats.setListFrom(formatData["listfrom"]);
		}
		
		// parent.ChannelForm is defined by the player's parent
		try {
			if (typeof(parent.ChannelForm) != 'undefined') {
				parent.ChannelForm.scanAndSetAsPlaying(formatData["listfrom"]);
			}
		} catch (ex) { /* probably parent. is inaccessable */ }
		
		// This should just take jsData or formatData
		//changeCovers(jsData["cdcover"], jsData["asin"], jsData["buyalbum"]);
		changeCovers(formatData, infoFormat.whichLink());
		
		// Right now this is for flash < 9 but it should be for everything
		if (callChangeMoney) {
			var banner = formatData["banner"];
			if (banner != "undefined") {
				var banners = banner.split("|");
				if (banners.length > 1) {
					changeMoney(banners[1], formatData["spotnum"], banners[0]);
				}
			}
		}
		
		// Hit our songtrack function
		songTrack(jsData);
		
		//alert("callback");
		// A callback function...
		changeInfoFinished(jsData);
		
		// Newer jquery event
		$.event.trigger("changeInfoFinished");
	}
}

changeInfo.getTrackId = function() {
	var trackId = -1;
	var cdata;
	try {
		cdata = this.jsData["cdata"];
	} catch (ex) {}
	if (cdata != undefined) {
		try {
			trackId = parseInt(cdata.split(" ")[0]);
		} catch (ex) {}
	}
	return trackId;
}

function songTrack(pJsData, pUrl) {
	var jsData = pJsData ? pJsData : changeInfo.jsData;
	var url = pUrl ? pUrl : "/static/html/songtrack.html";
	
	// This can't use changeInfo.getTrackId in case
	// pJsData is passed and is unique from changeInfo.jsData
	var cdata = "None";
	try {
		cdata = jsData["cdata"];
	} catch (ex) {}
	if (cdata.indexOf("None") <= -1) {
		var trackId = -1;
		try {
			trackId = parseInt(cdata.split(" ")[0]);
		} catch (ex) {}
		if (trackId > -1) {
			// brandid and listid ought to be globals
			var data =
			{
				t: trackId,
				b: brandid ? brandid : -1,
				l: listid ? listid : -1
			}
			$.ajax({
				type: "GET",
				url: url,
				data: data
			});
		}
	}
}

function afoaTrack(jsData) {
    $.ajax({
        type: "GET",
        url: "/static/html/afoatrack.html",
        data: jsData
    });
}


/** Change the cover art
 * 
 * @param {Object} jsData
 */
function changeCovers(jsData, whichLink) {
	if (jsData["cdcover"] != "undefined") {
		$('#img_cover_3').attr('src', $('#img_cover_2').attr('src'));
		$('#a_cover_3').attr('href', $('#a_cover_2').attr('href'))
		
		$('#img_cover_2').attr('src', $('#img_cover_1').attr('src'));
		$('#a_cover_2').attr('href', $("#a_cover_1").attr('href'));
		
		$('#img_cover_1').attr('src', "/static/images" + jsData['cdcover']);
		$('#a_cover_1').attr('href', whichLink);
	}
}


// A dumb banner-changing function, mostly for gateway videos
function changeBanner(appletBanner) {
    if (appletBanner != "" && appletBanner != undefined) {
        try {
            var ifr_money = parent.document.getElementById("ifr_banner_ad");
        } 
        catch (ex) {
        }
        if (ifr_money) {
            try {
                ifr_money.src = appletBanner;
            } 
            catch (ex) {
            }
        }
    }
}

function runChangeMoney(appletBanner, appletRotation, appletSponsor) {
	// These should be globally defined
	var lUseRemnantBanners = false;
	var lUseRemnantBoxes = false;
	try {
		lUseRemnantBanners = useRemnantBanners;
		lUseRemnantBoxes = useRemnantBoxes;
	} catch (ex) { }
	
	if (appletBanner != "" && appletBanner != undefined) {
		var ro = appletRotation ? appletRotation : 0;
		//var endURL = "&ch=accusongs&su=SubPrimary&br=accusongs&ro=" + escape(ro);
		var endURL = "&br=" + brandid;
		
		var useBanner = appletBanner;
		if (unescape(appletBanner).indexOf("http://") > -1) {
			// Banner is a URL call, it whole
			useBanner = appletBanner;
		}
		else if (useBanner == "fastclick.js" || useBanner == "undefined") {
			if (lUseRemnantBanners) useBanner = "/player/ad/?s=1" + endURL;
			else useBanner = false;
		}
		else {
			// Banner is local
			//useBanner = "/player/ads/?ba=" + escape(appletBanner) + endURL;
			useBanner = "/player/ad/?s=1ba=" + escape(appletBanner) + endURL;
		}
		try {
			var ifr_money = parent.document.getElementById("ifr_banner_ad");
		} 
		catch (ex) {
		}
		if (ifr_money && useBanner) {
			try {
				ifr_money.src = useBanner;
			} 
			catch (ex) {
			}
		}
		
		var useSponsor = appletSponsor ? appletSponsor : "transparent.js";
		if (useSponsor == "transparent.js") {
			// Call a remnant 'sponsor'
			if (lUseRemnantBoxes) useSponsor = "/player/ad/?s=2" + endURL;
			else useSponsor = false
		}
		
		// For AFOA
		var bigBox = $("#div_ad_bigbox");
		if (bigBox.length > 0) {
			bigBox.html('<iframe id="ifr_box_ad" name="ifr_box_ad" frameborder="0" scrolling="no" width="100%" height="100%" src="/static/html/transparent.html" allowtransparency="true"></iframe>');
		}
		
		var ifr_box = parent.document.getElementById("ifr_box_ad");
		if (ifr_box && useSponsor) {
			try {
				ifr_box.src = useSponsor;
			} 
			catch (ex) {
			}
		}
	}
}

var changeMoneyTimeoutID;
function changeMoney(appletBanner, appletRotation, appletSponsor) {
	//alert("changeMoney: " + appletBanner);
	// Banner: don't change the banner if this hasn't been called with a valid parameters
	
	//if (appletBanner != undefined) alert(appletBanner);
	//else alert("appletBanner undefined");
    
	
	// Commenting this out to test Google AFOA
	if (mtype.indexOf("swf7") > -1) {
		// This kludge exists for IE6 + Flash < 9
		//alert("delayed call");
		clearTimeout(changeMoneyTimeoutID);
		changeMoneyTimeoutID = setTimeout(function() {
			runChangeMoney(appletBanner, appletRotation, appletSponsor);
		}, 1500);
	} else {
		runChangeMoney(appletBanner, appletRotation, appletSponsor);
	}
}

// The following functions rely on jquery.cookie.js
var fallBack = false;
function showOverlay(bannerURL) {
	var url = "/player/vgw/";
	var doPlay = false;
	if (bannerURL != "" && bannerURL != "undefined" && bannerURL != null) {
		var banners = bannerURL.split("|");
		if (banners.length >= 2) {
			doPlay = banners[1];
		}
	}
	
	// Only work if cookies have been loaded and work
	/*
	try {
		c = $.cookie('gw');
		if (c == 1) {
			doPlay = false;
			acGwFin();
		}
	} catch (ex) { doPlay = false; acGwFin(); }
	*/
	
	
	if (doPlay) {
		// Stop the player
		//acPause();
		
		// Load the ad into the overlay
		$("#div_overlay_outer").addClass("overlay-opacity"); // Can be replaced with CSS
		var data = 
		{
			a: doPlay
		}
		$.ajax({
			type: "GET",
			url: url,
			data: data,
			success: function(msg) {
				$("#div_overlay_outer").show();
				$("#div_overlay_inner").show();
				$("#div_overlay_video").html(msg);
				// Can't use hide() or show() because the "display:none" style
				// does strange things to the Flash plugin
				$("#div_player").css("visibility", "hidden");
				
				try {
					var date = new Date();
					date.setTime(date.getTime() + (1000*60*30));
					$.cookie('gw', 1, {
						path: '/',
						expires: date
					});
				} catch (ex) {}
				
				//fallBack = setTimeout("hideOverlay()", 40000);
			}
		});
	}
}

function showInpageVG(vURL) {
    var url = "/player/vg_inpage_wrapper/"
    url += "?vURL=" + escape(vURL);
    
    // For AFOA
    var bigBox = $("#div_ad_bigbox");
    if (bigBox.length > 0) {
            bigBox.html('<iframe id="ifr_box_ad" name="ifr_box_ad" frameborder="0" scrolling="no" width="100%" height="100%" src="/static/html/transparent.html" allowtransparency="true"></iframe>');
    }
    
    var ifr_box = parent.document.getElementById("ifr_box_ad");
    if (ifr_box && url) {
        try {
            ifr_box.src = url;
        } 
        catch (ex) {}
    }
}

function hideOverlay() {
	if (fallBack != false) clearTimeout(fallBack);
	$("#div_player").css("visibility", "visible");
	$("#div_overlay_inner").hide();
	$("#div_overlay_video").html('');
	$("#div_overlay_outer").hide();
	acGwFin();
}

function overlayFinished() {
	setTimeout("hideOverlay()", 1000);
}
