﻿Viostream.AjaxObject.SetDefaults = function() {
	$.ajaxSetup({
		dataType: "xml",
		type: "GET",
		success: this.handleSuccess,
		failure: this.handleFailure,
		timeout: 20000
	});
}
//NEW STUFF IN HERE
/*
	Template only comes from "tempTemplate" which includes <li>, so is no longer wrapped in one
	MediaBase now has duration. New parseDuration function in Viostream to convert it from milliseconds
	Draw uses new classes from v2 MediaList control, some stuff removed for this portal (views etc)
	"current" class is added to "tabs" after category load
	ChangeView uses new medialist (media menu) classes
	removed thumbnail width and height
*/
Viostream.Templates = {
	Init: function() {
		this.MediaItemInit();
	},
	//tempTemplate holds an HTML string that contains a copy of a single media Item output by the back-end
	tempTemplate: "",

	MediaItemInit: function() {
		this.MediaItem.appendChild($(Viostream.Templates.tempTemplate).get(0));
	},

	MediaItem: document.createDocumentFragment()
};

Viostream.MediaBase = function(oXML) {
	///Prop
	this.MediaId = "";
	this.MediaType = "";
	this.Created = "";
	this.Url = "";
	this.MediaTitle = "";
	this.MediaDescription = "";
	this.ThumbnailURL = "";
	this.rating = 0;
	this.AverageVotes = 0;
	this.Album = new Array();
	this.Keywords = new Array();
	this.Source = "";
	this.Duration = 0;

	///Parse function
	this.Parse = function(itemXML) {
		try {
			var $xml = $(itemXML);
			this.MediaId = $xml.find("MediaId").text();

			this.MediaType = $xml.attr("MediaType");
			///Read ISO formated date
			var d = new Date();
			d.setISO8601($xml.find("DisplayTime").text());
			this.Created = d.getFormatDate();

			var url = "";
			var MediaURLS = $xml.find("MediaUrl");

			for (var i = 0; i < MediaURLS.length; i++) {
				var $murl = $(MediaURLS[i]);
				url = $murl.find("Url").text();
				//need to check for existence of High quality, then low quality, then none...
				if ($murl.find("Quality").text() == "High")
					break;
			}

			this.Url = url; /* used for quickplay functionality */
			this.MediaTitle = $xml.find("MediaTitle").text();
			this.MediaDescription = $xml.find("MediaDescription").text();
			if (this.MediaDescription == "") this.MediaDescription = "&nbsp;";
			this.Source = $xml.find("AuthorName").text();

			this.ThumbnailURL = Viostream.GetThumbnailData(itemXML, Viostream.targetThumbNailWidth, Viostream.targetThumbNailHeight);

			this.AverageVotes = parseFloat($xml.find("AverageVotes").text());
			this.rating = Math.round(this.AverageVotes * 2);
			this.Duration = $xml.find("Duration:eq(0)").text();
				
			var self = this;
			$xml.find("KeyWord").each(function() { self.Keywords.push($(this).text()); });

			if (this.MediaType == "Album") {
				$xml.find("Picture").each(function() { self.Album.push(new Viostream.AlbumPicture(this)); });
			}
		}
		catch (e) {
			if (this.isDebug) {
				alert("MediaBase.Parse(). " + e.message);
				throw e;
			}
		}
	}

	if (typeof (oXML) != "undefined")
		this.Parse(oXML);
};

Viostream.redrawMedia = function(responseXML) {

	var mediaBaseElements = $(responseXML).find("MediaBase");

	///Clear all existing elements in the container item
	this.ClearMediaItemElement()
	$("#" + Viostream.mediaItemListId).empty();
	///Loop each media base item xml data
	mediaBaseElements.each(function() {
		var mb = new Viostream.MediaBase(this);
		mb.Draw();
	});

	return mediaBaseElements.length;
};

Viostream.MediaBase.prototype.AddToPlayList = function(evt) {
	/// <summary> 
	/// Adds this media item to the current playlist. If there is
	/// no playlist, it will create one and then add the item to it.
	/// </summary>
	try {
	
		if (typeof (evt) == "undefined")
			var mb = this;
		else
			var mb = evt.data.mb;

		Viostream.PlayList.ClientSidePlaylist.push(mb);
		var txtPlayListId = ($gE("txtPlayListId") == null) ? document.forms[0].eval("txtPlayListId") : $gE("txtPlayListId");

		var playListId = txtPlayListId.value;

		if (Viostream.QuickPlay) {
			updateMedia(mb.MediaId);
			//update currently playing
			//currentlyPlaying(mb.MediaTitle, 0, mb.MediaDescription, mb.Created, mb.MediaId, mb.AverageVotes)
			return;
		}
		//no current playlist
		if (playListId.length == 0) {
			///Create a new playlist
			Viostream.PlayList.Create(mb.MediaId, txtPlayListId);
		} else {
			//add mediId GUID to playlist
			Viostream.PlayList.AddMedia(txtPlayListId.value, mb.MediaId);
		}
	}
	catch (e) {
		notify("AddToPlayList(playGUID) " + e.message, true);
	}
};

Viostream.MediaBase.prototype.PlayNow = function(evt) {
	/// <summary> 
	/// Adds this media item to the current playlist. If there is
	/// no playlist, it will create one and then add the item to it.
	/// </summary>
	try {
		if (typeof (evt) == "undefined")
			var mb = this;
		else
			var mb = evt.data.mb;

		if (Viostream.QuickPlay) {
			updateMedia(mb.MediaId);
			//update currently playing
			//currentlyPlaying(mb.MediaTitle, 0, mb.MediaDescription, mb.Created, mb.MediaId, mb.AverageVotes)
			return;
		}

	}
	catch (e) {
		notify("PlayNow() " + e.message, true);
	}
};

Viostream.MediaBase.prototype.FormatDesc = function(s) {
	return s;
};

Viostream.MediaBase.prototype.Draw = function() {
	/// <summary> Builds a media item on the screen </summary>
	var mb = this;
	try {
		var oFrag = Viostream.Templates.MediaItem.cloneNode(true);
		var $Frag = $(oFrag.childNodes);

		mb.MediaDescription = (mb.MediaDescription != null) ? mb.MediaDescription : "";

		var itemclass = mb.MediaType.toString().toLowerCase();
		var playtitle = itemclass == "video" ? "Play: " : "View: ";
		$Frag.addClass(itemclass);
		var videoTitleText = $Frag.find(".video-title-text");
		videoTitleText
            .bind("click", { mb: this }, this.AddToPlayList)
            .attr("title", playtitle + " " + mb.MediaTitle)
            .mouseover(function() { window.status = ""; return false; })
            .html(mb.MediaTitle);

		$Frag.find(".vs-description").html(this.FormatDesc(mb.MediaDescription));
		$Frag.find(".vs-thumb img")
            .attr("src", mb.ThumbnailURL)
            .attr("alt", mb.MediaTitle);
		$Frag.find(".vs-date").html(mb.Created);
		$Frag.find(".vs-duration").html(Viostream.parseDuration(mb.Duration));
		$Frag.find(".vs-playnow")
			.bind("click", { mb: this }, this.AddToPlayList)
			.attr("title", playtitle + " " + mb.MediaTitle);

		var ulMediaItemWrapper = $("#" + Viostream.mediaItemListId);
		ulMediaItemWrapper.append($Frag);

		var truncateLength = mb.Duration == 0 ? 62 : 55;
		if (videoTitleText.height() > 69) {
			var text = videoTitleText.text();
			text = text.substring(0, truncateLength) + "&hellip;";
			videoTitleText.html(text);
		}
	}
	catch (e) {
		notify("BuildMediaItemElement(mb) " + e.message, true);
	}
};

Viostream.parseDuration = function(ms) {
	var seconds = Math.floor((ms / 1000) % 60);
	var minutes = Math.floor((ms / (1000 * 60)) % 60);
	var hours = Math.floor((ms / (1000 * 60 * 60)) % 24);
	
	if (seconds <= 9)
		seconds = "0" + seconds; //pad seconds
	if (hours > 1)
		return " (" + hours + ":" + minutes + ":" + seconds + ")";
	else
		return " (" + minutes + ":" + seconds + ")";
}

Viostream.Category.MediaListHandleSuccess = function(oXML, title, categoryId) {
	/// <summary> AJAX response from the MediaList function </summary>
	var nav = $("#" + Viostream.Navigation.ClientId);
	nav.find(".current").removeClass("current")
	nav.find("a[href*=" + categoryId + "]").parent().addClass("current");

	if (!Viostream.AjaxObject.DisplayErrors(oXML, "MediaList")) {
		Viostream.hideLoader();
		this.CompleteLoad(oXML, categoryId, title);
	}
}
Viostream.ChangeView = function(t) {
	/// <summary> Called by a click on the menu-view-options images - changes the video card style </summary>
	try {
		var ulMediaItemWrapper = $gE(Viostream.mediaItemListId);
		var aListView = $gE("aListView");
		var aGridView = $gE("aGridView");

		///Change class on buttons
		aListView.className = ("List" == t) ? "toggle-list current" : "toggle-list";
		aGridView.className = ("Grid" == t) ? "toggle-grid current" : "toggle-grid";

		///Change class on UL wrapper element
		ulMediaItemWrapper.className = "media-menu-" + t.toLowerCase();
	}
	catch (e) {
		notify("ChangeView(type) " + e.message, true);
	}
};
Viostream.GetThumbnailData = function(oXML, width, height){
    /// <summary> Returns the path for the highest quality thumbnail. </summary>
    /// <remarks> Returns Viostream.defaultThumbNailUrl if there isn't a thumbnail available </remarks>
    var ret = Viostream.defaultThumbNailUrl;
    var Thumbnails = $(oXML).find("Thumbnail");
    var i = Thumbnails.length;
	
    while(i--){
        var thumb = new Viostream.Thumbnail(Thumbnails[i]);
        ret = thumb.Path;
        if( (thumb.Width == width) && (thumb.Height == height) )
            break;
    }
    return ret;
};












//stop hiding of pagination with only one page

// viostream.pagination.js 
// version: 1.0
// requires:
//      - viostream.js

Viostream.Paginate = function(recordCount, pageSize, totalPages, currentPageIndex, categoryId) {
	/// <summary>
	/// Builds the list of pagination links on the page
	/// </summary>
	var PageLink = function(content, catID, pageIndex, aClassName, liClassName) {
		// creates and returns the li containing the right link
		var a = document.createElement("a");
		a.href = "javascript:void(0);"

		$(a).click(function() {
			var section = catID + "," + pageIndex + "," + Viostream.SortOrder + "," + Viostream.MediaType;
			try {
				Viostream.CurrentPageIndex = pageIndex;
				$.history.load(section);
			} catch (e) {
				Viostream.LoadCategoryFromGuid(section, 0);
			}
			return false;
		}).html(content).addClass(aClassName);

		$(a).addClass(liClassName);
		return a;
	};

	try {
		if (recordCount > 0) {
			var ul = $cE("div");

			//build first link
			ul.appendChild(PageLink("First Page", categoryId, 0, "", "first"));

			//build previous link
			var previousIndex = (currentPageIndex > 1) ? currentPageIndex - 2 : 0;
			ul.appendChild(PageLink("Previous Page", categoryId, previousIndex, "", "previous"));

			//build page links
			for (var j = 0; j < totalPages; j++) {
				ul.appendChild(PageLink("<span>Page </span>" + (j + 1), categoryId, j, (j + 1 == currentPageIndex ? "current" : ""), ""));
			}

			//build next link
			var nextIndex = (currentPageIndex < totalPages) ? currentPageIndex : totalPages - 1;
			ul.appendChild(PageLink("Next Page", categoryId, nextIndex, "", "next"));

			//build last link
			ul.appendChild(PageLink("Last Page", categoryId, totalPages - 1, "", "last"));
			$("div.pagination-controls").empty().append(ul).show();
		} else {
			$("div.pagination-controls").empty().hide();
		}
	}
	catch (e) {
		if (this.isDebug) {
			alert("paginate)" + e.message);
			throw e;
		}
	}
};


function updateMedia(id) {
	var swf = swfobject.getObjectById('player')
	swf.updateMedia(id);
}
