/**
 * @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,
		value: Volume.curVol,
		change: function(e, ui) {
			acVolume(ui.value);
			return false;
		}
	});
}

Volume.setVolume = function(toVolume) {
    $('#' + this.divId).slider('value', 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 + "/slipstream-20/";
	}

	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", jsData);
	}
}

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
    });
}

function addRecent() {
  $.ajax({
    type: "POST",
    url: "/listener/v4.1/json/recent/",
    data: {
      b: brandid ? brandid : -1,
      l: listid ? listid : -1,
      w: 1
    },
    success: function() {
		try {
			window.opener.doReload();
	 } catch (ex) {}
    }
  });
}


/** 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'));

        var coverDir = "";
        var useCoverDir = false;
        try {
            if (typeof(COVERMAX) == undefined) {}
            else {
                coverDir = COVERMAX;
                useCoverDir = true;
            }
        } catch (ex) {}

        if (useCoverDir) {
            $('#img_cover_1').attr('src', "/static/images/" + coverDir + jsData['cdcover'].toLowerCase());
        } else {
            $('#img_cover_1').attr('src', "/static/images" + jsData['cdcover']);
        }

        //$('#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) {
    // Hide the targetspot container
    //hideTS(false);
    
	// 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);
}

var FavoriteButton =
{
  imgOut: $("#img_add_favorite").attr("src"),
  imgPath: "/static/images/skins/" + skin + "/",
  favNoFav: function() { return this.imgPath + "fav_nofav.gif" },
  favYesFav: function() { return this.imgPath + "fav_yesfav.gif" },
  favHover: function() { return this.imgPath + "fav_hover.gif" },
  favActive: function() { return this.imgPath + "fav_active.gif" },
  active: false,

  autoSetButton: function() {
    if (FavoriteButton.active) {
        FavoriteButton.imgOut = FavoriteButton.favYesFav();
      } else {
        FavoriteButton.imgOut = FavoriteButton.favNoFav();
      }
      $("#img_add_favorite").attr("src", FavoriteButton.imgOut);
  },

  setButton: function() {
    $("#img_add_favorite").hover(function() {
      FavoriteButton.imgOut = $(this).attr("src");
      $(this).attr("src", FavoriteButton.favHover());
    }, function() {
      FavoriteButton.autoSetButton();
    }).mousedown(function() {
      $(this).attr("src", FavoriteButton.favActive());
      FavoriteButton.active = !FavoriteButton.active;
    }).mouseup(function() {
      $(this).attr("src", FavoriteButton.favHover());
    }).click(function() {
      var operation = -1;
      if (FavoriteButton.active == true)
        operation = 1;  // Add
      else
        operation = 3;  // Remove
      $.ajax({
        type: "POST",
        url: "/listener/v4.1/json/favorite/",
        dataType: 'json',
        data: {
          b: brandid ? brandid : -1,
          l: listid ? listid : -1,
          o: operation,
          w: 1
        },
        success: function(result) {
          // Parse the results and re-set the button if it's a failure
          if (result.favorite == true) {
            $("#span_favorite_added").css("visibility", "visible").animate({
              opacity: 0.0
            }, 3000, function() {
              $(this).css("visibility", "hidden").css("opacity", 1);
            })
          }
          try {
          	window.opener.doReload();
          } catch (ex) {}
        },
        error: function() {
          // Re-set the button
          FavoriteButton.active = !FavoriteButton.active;
          FavoriteButton.autoSetButton();
        }
      });
    });
  },

  checkFavorite: function() {
    $.ajax({
      type: "GET",
      url: "/listener/v4.1/json/favorite/",
      dataType: 'json',
      data: {
        b: brandid ? brandid : -1,
        l: listid ? listid : -1,
        o: 4,
        w: 1
      },
      success: function(result) {
        if (result[0] == true) {
          FavoriteButton.active = true;
          FavoriteButton.autoSetButton();
        }
      }
    })
  }
}

function showTS(changeRemnant) {
    var bb = $("#div_ad_bigbox");
    var ts = $("#div_ad_targetspot");
    ts.css("top", bb.css("top"));
    ts.css("left", bb.css("left"));
    bb.css("visibility", "hidden");
    

    var lChangeRemnant = changeRemnant ? changeRemnant : false;
    if (lChangeRemnant == true) {
        // Change the remnant banner
        var lUseRemnantBanners = false;
	var lUseRemnantBoxes = false;
	try {
	    lUseRemnantBanners = useRemnantBanners;
	    lUseRemnantBoxes = useRemnantBoxes;
	} catch (ex) { }
        if (lUseRemnantBanners) {
            try {
	        var ifr_money = parent.document.getElementById("ifr_banner_ad");
            } catch (ex) {}
            if (ifr_money) {
                var endURL = "&br=" + brandid;
                ifr_money.src = "/player/ad/?s=1" + endURL;
            }
        }
    }
}

function hideTS(changeRemnant) {
    var ts = $("#div_ad_targetspot");
    var bb = $("#div_ad_bigbox");

    if (ts.css("left") != "-300px" && bb.css("visibility") != "visible") {
        console.log("hideTS");
        ts.css("left", -300);    
        bb.css("visibility", "visible");
        
        var lChangeRemnant = changeRemnant ? changeRemnant : false;
        if (lChangeRemnant == true) {
            // Change the remnant banner
            var lUseRemnantBanners = false;
	    var lUseRemnantBoxes = false;
	    try {
	        lUseRemnantBanners = useRemnantBanners;
	        lUseRemnantBoxes = useRemnantBoxes;
	    } catch (ex) { }
            if (lUseRemnantBoxes) {
	        if (bb.length > 0) {
		    bb.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>');
	        }
                try {
	            var ifr_box = parent.document.getElementById("ifr_box_ad");
                } catch (ex) {}
                if (ifr_box) {
                    var endURL = "&br=" + brandid;
                    ifr_box.src = "/player/ad/?s=2" + endURL;
                }
            }
        }
    }
}

$(document).ready(function() {
  FavoriteButton.setButton();
  FavoriteButton.checkFavorite();
  addRecent();
});

