// viostream.js 
// version: 1.0
// requires:
//      - jquery.js // min version 1.2

// Here are some things to make the codebase smaller
trace = function(msg){
  if(typeof(console)!="undefined"){
    console.log(msg);
  }
};

trace("viostream.js");

var $cE = function(o){return document.createElement(o);}
var $cT = function(o){return document.createTextNode(o);}
var $gE = function(o){ return document.getElementById(o);}

notify = function(msg, debug, exception){ 
    /// <summary> This is the custom alert function which can be overridden to use a different alert method </summary>
    /// <remarks> e.g. Have a box on the screen that pops up like in google mail
    if(typeof(debug) == "undefined") debug = false;
    if(!debug){
        alert(msg); //show the user something
    }else if(Viostream.isDebug){
        alert(msg); //show the debug message
    }
    if(typeof(Viostream.Error) != "undefined")
        new Viostream.Error(msg, exception);
};



var Viostream = {
	/// <summary>
	/// This is the base class/namespace for Viostream. All variables and objects 
	/// should live within this Javascript object
	/// </summary>

	// GLOBAL OPTIONS
	// javascript version
	Version: "2.0.jquery",

	Extend: function (target, opts) {
		///<summary> 
		/// Used to add values (via an associate array) to an object. If only one object is provided, then the target becomes the base Viostream object.
		/// </summary>
		///<param name="target">The target object that we're extending</param>
		///<param name="opts">An associative array of options</param>
		if (typeof (opts) == "undefined") {
			opts = target;
			target = this;
		}
		for (var a in opts) {
			target[a] = opts[a];
		}
	},


	SetValues: function (o) {
		Viostream.Extend(this, o);
	},

	Navigation: {
		Init: function (o) {
			Viostream.Extend(this, o);
		}
	},
	// When set to false, all alerts are hidden
	isDebug: true,
	//When set to true users see friendly error messages - ie without the operation name
	friendlyErrors: true,
	// When encryption is enabled, then this key will not be null
	key: null,
	// Set to true once Init() has finished.
	isReady: false,
	isMediaPage: true,
	displayLoader: true,
	fading: false,
	//loadingNoticeID: "loadingNoticeSnake",
	MessageVisibility: { Hide: 0, Show: 1 },
	CurrentCategory: "",
	CurrentPageIndex: 0,
	SortOrder: "Alphabetical",
	SessionId: "",
	MediaId: null,
	MediaType: "All",
	SessionTimeOut: 20,
	SearchTerm: "",

	WSUrl: "/Service/Core.asmx/",
	PlayListWSUrl: "/Service/Playlist.asmx/",
	SessionWSUrl: "/Service/Session.asmx/",
	UserWSUrl: "/Service/User.asmx/",
	CommentWSUrl: "/Service/Comment.asmx/",
	RatingWSUrl: "/Service/Rating.asmx/",
	PollWSUrl: "/Service/Poll.asmx/",
	MiscWSUrl: "/Service/Miscellaneous.asmx/",

	UserIsLoggedIn: false,

	// user object    
	user: null,

	// poll object
	poll: null,

	PollVariables: { // the selectors for the poll pieces
		PollDiv: "#poll", // The heading will be appended to this
		PollContent: "#pollQuestion" // The radio buttons will be appended to this
	},


	formValidation: [
	/// <summary> This is an array of all the fields on the page, and their corresponding validity tests </summary>
	/// <remarks> 
	/// Tests are: 
	///     - text : must pass a regex for alpha values
	///     - email : must pass a regex for email format
	///     - string : must be a string with a length > 0
	///     - password : htmlId.value == htmlId2.value
	///     - check : must be checked
	///     - option : an option must be chosen
	///     - dob : htmlIdDay/htmlIdMonth/htmlIdYear should return a year
	///
	/// The "id" property is the query string parameter that is to be sent to the webservice
	/// The "error" is the error message that is appended to the final error notification if it fails validation.
	/// defaultValue is an optional variable for the default value to use
	/// </remarks>

        {id: "firstname", required: true, htmlId: "regFirstName", test: "text", error: "\n- First name is required" },
        { id: "lastname", required: true, htmlId: "regLastName", test: "text", error: "\n- Last name is required" },
        { id: "emailAddress", required: true, htmlId: "regEmail", test: "email", error: "\n- Email address is required" },
        { id: "password", required: true, htmlId: "regPassword", test: "string", error: "\n- Password is required" },
        { id: "_password", required: true, htmlId: "regPassword2", htmlId2: "regPassword", test: "password", error: "\n- Both Password fields must match" },
        { id: "dob", required: true, htmlIdDay: "regDOBDay", htmlIdMonth: "regDOBMonth", htmlIdYear: "regDOBYear", test: "dob", error: "\n- Date Of Birth is required" },
        { id: "address", required: true, htmlId: "regAddress1", htmlId2: "regAddress2", test: "address", error: "\n- Address is required" },
        { id: "city", required: true, htmlId: "regCity", test: "string", error: "\n- City is required" },
        { id: "postCode", required: true, htmlId: "regPostCode", test: "string", error: "\n- PostCode is required" },
        { id: "country", required: true, htmlId: "regCountry", test: "string", error: "\n- Country is required" },
        { id: "state", required: true, htmlId: "regRealState", test: "string", error: "\n- State is required" },
        { id: "phone", required: true, htmlId: "regPhone", test: "string", error: "\n- Phone Number is required" },
        { id: "mobile", required: true, htmlId: "regMobile", test: "string", error: "\n- Mobile Number is required" },
        { id: "optin", required: true, htmlId: "regOptin", test: "check", error: "\n- You must agree to the terms and conditions before you can register" },
        { id: "gender", required: false, htmlId: "regGender", test: "option", error: "\n- Gender is required", defaultValue: "Unspecified" },
        { id: "alias", required: false, htmlId: "regDisplayName", test: "string", error: "\n- A prefered name is required" },
        { id: "xmlData", required: false }
    ],

	//this is the initial order that media Items are displayed in when users visit the homepage. Valid values : {'Alphabetical', 'DateAdded', 'Views'}
	InitialOrder: 'Alphabetical',

	UseShadowBox: false,

	//default registration/login and password reminder panel heights - overridden in codebehind if needed
	LoginPanelToHeight: 232,
	forgotPasswordToHeight: 118,
	RegistrationToHeight: 320,
	LoginPanelFromHeight: 0,
	forgotPasswordFromHeight: 0,
	RegistrationFromHeight: 0,

	//use the deault images/content/img_sample.jpg image for each channel - set to true if channel images are specified in database
	UseCategoryImages: false,



	showLittleLoader: function (domNode) {
		try {
			//            var newpic = document.createElement('img');
			//            newpic.src = "/images/interface/ajax_loader_small.gif";
			$(domNode).attr("src", this.smallLoad.src);
			$(domNode).addClass("vs-loading");

			//            document.getElementById(domNode).appendChild(newpic);
		} catch (e) {
			trace("showLittleLoader" + e);
		}
	},
	trim: function (s) {
		return s.replace(/^\s+|\s+$/g, '');
	},

	//AutoplayMedaiId if != null then this is added to the default playlist onload
	AutoplayMediaId: null,

	SetCurrentSortOrder: function (sortOrder) {
		/// <summary> Changes the indicator on the sort order links in UI </summary>
		try {
			this.SortOrder = sortOrder;
			$("#" + Viostream.History.AlphabetSortLink + ", #" + Viostream.History.DateAddedSortLink + ", #" + Viostream.History.ViewsSortLink + ", #" + Viostream.History.RatingSortLink).removeClass("current");
			switch (sortOrder) {
				case "Alphabetical":
					$("#" + Viostream.History.AlphabetSortLink).addClass("current");
					break;
				case "DateAdded":
					$("#" + Viostream.History.DateAddedSortLink).addClass("current");
					break;
				case "Views":
					$("#" + Viostream.History.ViewsSortLink).addClass("current");
					break;
				case "Rating":
					$("#" + Viostream.History.RatingSortLink).addClass("current");
					break;
			}
		}
		catch (e) {
			notify("SetCurrentSortOrder(sortOrder) " + e.message, true);
		};
	},
	SetCurrentFilterOption: function (mediaType) {
		/// <summary> Changes the indicator on the media type filter links in UI </summary>
		try {

			this.mediaType = mediaType;
			$("#" + Viostream.History.ContentFilterAll + ", #" + Viostream.History.ContentFilterVideo + ", #" + Viostream.History.ContentFilterImage + ", #" + Viostream.History.ContentFilterAudio).removeClass("current");
			switch (mediaType) {
				case "All":
					$("#" + Viostream.History.ContentFilterAll).addClass("current");
					break;
				case "Video":
					$("#" + Viostream.History.ContentFilterVideo).addClass("current");
					break;
				case "Audio":
					$("#" + Viostream.History.ContentFilterAudio).addClass("current");
					break;
				case "Image":
					$("#" + Viostream.History.ContentFilterImage).addClass("current");
					break;
			}
		}
		catch (e) {
			notify("SetCurrentFilterOtpion(mediaType) " + e.message, true);
		};
	},


	_OnLoad: new Array(),

	OnLoad: function (oFunc) {
		/// <summary> 
		/// This sets up an array of functions to be called after Viostream.Init is called. 
		/// e.g. Viostream.OnLoad(myFunc);
		/// </summary>
		if (!this.isReady)
			Viostream._OnLoad.push(oFunc);
		else
			oFunc();
	},

	_PreLoad: new Array(),

	PreLoad: function (oFunc) {
		/// <summary> 
		/// This sets up an array of functions to be called within Viostream.Init before anything else is. 
		/// this applies most to the base settings eg. UseRating, PaginationSize etc.
		/// (previously part of the PortalAppsettings Object - now properties of the Viostream object)
		/// e.g. Viostream.PreLoad(myFunc);
		/// </summary>
		if (!this.isReady)
			Viostream._PreLoad.push(oFunc);
		else
			oFunc();
	},

	_PostLoad: new Array(),

	PostLoad: function (oFunc) {
		/// <summary> 
		/// This sets up an array of functions to be called after Viostream.OnLoad is called. 
		/// e.g. Viostream.PostLoad(myFunc);
		/// </summary>
		if (!this.isReady)
			Viostream._PostLoad.push(oFunc);
		else
			oFunc();
	},

	Init: function () {
		trace("Init");
		if (typeof (Viostream.User) != "undefined") {
			Viostream.user = new Viostream.User();
			trace("new Viostream.User");
		}
		for (var i = 0; i < Viostream._PreLoad.length; i++) {
			Viostream._PreLoad[i]();
			//trace("Viostream._PreLoad["+ i + "] = " + Viostream._PreLoad[i]);
		}

		Viostream.AjaxObject.SetDefaults();
		Viostream.Templates.Init();


		/* image preloading */
		Viostream.smallLoad = new Image();
		Viostream.smallLoad.src = "/images/interface/ajax-loader_blacktrans.gif";
		$(Viostream.smallLoad).addClass("vs-loading");


		if (typeof (Viostream.User) != "undefined") {
			$("#" + Viostream.User.forgotpassword.buttonId).click(function () {
				Viostream.ForgotPassword();
				//Viostream.Animation.closePasswordAnim(); 
			});
		}


		//if this isn't the home page then don't do the browser History Manager thing
		if (document.location.href.toLowerCase().indexOf("upload.aspx") > -1) {
			Viostream.isMediaPage = false;
		}
		if (Viostream.isMediaPage) {
			/// STOP FORMS FROM SUBMITTING ONENTER
			$("form").submit(function () { return false; });

			var initSection;
			Viostream.History.Init();

			/*if (Viostream.AutoplayMediaId != null && txtPlayListId.value == '') {
			$(document).ready(function() { Viostream.PlayList.AddByMediaId(Viostream.AutoplayMediaId); });
			}*/

			/* LOAD POLL */
			if (typeof (Viostream.LoadPoll) == "function")
				Viostream.LoadPoll();

			/* SHADOWBOX */
			if (this.UseShadowBox) {
				Shadowbox.init({
					// let's skip the automatic setup because we don't have any
					// properly configured link elements on the page
					overlayBgImage: '/images/interface/overlay-85.png',
					loadingImage: '/images/interface/loading.gif',
					skipSetup: true,
					counterType: 'skip'
				});
			}

			/* Start SessionKeepAlive */
			setInterval(Viostream.AjaxObject.SessionKeepAlive, (Viostream.SessionTimeOut - 1) * 60 * 1000);

			//additional override methods
			if (typeof (Viostream.Hook) != "undefined")
				Viostream.Hook();
		}

		//Add onmouseover changestatus to all links...
		//$("a").mouseover(function() { window.status = ""; });

		// Now that all the Init stuff is done, call Viostream.OnLoad
		Viostream.isReady = true;
		for (var i = 0; i < Viostream._OnLoad.length; i++) {
			Viostream._OnLoad[i]();
		}

		for (var i = 0; i < Viostream._PostLoad.length; i++) {
			Viostream._PostLoad[i]();
		}
	}

};

// The Viostream
$(document).ready(function(){ Viostream.Init(); });


//date.js
trace("date.js");
Date.prototype.setISO8601 = function (str, useOffset){
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = str.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3])   { date.setMonth(d[3] - 1); }
    if (d[5])   { date.setDate(d[5]); }
    if (d[7])   { date.setHours(d[7]); }
    if (d[8])   { date.setMinutes(d[8]); }
    if (d[10])  { date.setSeconds(d[10]); }
    if (d[12])  { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14])  
    {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    
    if(typeof(useOffset) == "undefined" || !useOffset){
        offset = 0;
    }
    time = (Number(date) + (offset * 60 * 1000));
    
    this.setTime(Number(time));
    
    this.getFormatDate = function()
    {
        return AddZero(this.getDate()) + "/" + AddZero(parseInt(this.getMonth() + 1),10) + "/" + this.getUTCFullYear();
    }
    
    this.getFormatDateTime = function()
    {
        return AddZero(this.getDate()) + "/" + AddZero(parseInt(this.getMonth() + 1),10) + "/" + this.getUTCFullYear() + " " + AddZero(this.getUTCHours()) + ":" + AddZero(this.getMinutes());
    }
    
    function AddZero(value)
    {
        return (value.toString().length == 1) ? "0" + value : value;
    }
};

//EmbedDialog.js
trace("EmbedDialog.js");

if (typeof (Viostream) == "undefined") {
    Viostream = { };
}

if (typeof (Viostream.EmbedDialog) == "undefined") {
    Viostream.EmbedDialog = { };
}

Viostream.Extend(Viostream.EmbedDialog, {
    
    Init: function(o) {
        Viostream.Extend(this, o); 
        
        if(this.PanelId!=null){
            $("#" + this.PanelId).bind("MediaChanged", this.MediaChangedCallback);
        }
        
        
        
        if(this.PageFieldButtonId!=null){
            $("#" + this.PageFieldButtonId).click(function(e){
                $("#" + Viostream.EmbedDialog.PageField).select();
            });
            //$("#" + this.PageFieldButtonId).bind("mouseover",{ targetElement : this.PageField}, this.CopyToClipBoard);
            //z-index issues abound :(
        }
    },
    
    MediaChangedCallback : function(e,data){
        //trace("Viosteam.EmbedDialog.MediaChangeCallBack();");
        
        var swfwidth = 490;
        var swfheight = 312;
        if(typeof(swf)!="undefined"){
            swfwidth = swf.width;
            swfheight = swf.height;
        }
        var embedLink = "<object width=\"" + swfwidth + "\" height=\"" + swfheight + "\"><param name=\"movie\" value=\"http://www.viotv.com/&hl=en&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.viotv.com/&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" + swfwidth + "\" height=\"" + swfheight + "\"></embed></object>";
        var pageLink = Viostream.PortalUrl + "?mediaId=" + data.MediaId;
        $("#" + Viostream.EmbedDialog.PageField).val(pageLink);
        $("#" + Viostream.EmbedDialog.LinkFieldId).val(embedLink);
        
        //Viostream.EmbedDialog.CopyToClipBoard(Viostream.EmbedDialog.PageFieldButtonId, Viostream.EmbedDialog.PageField);
    }
   
});
//MediaListMenu.js
trace("MediaListMenu.js");

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 = ("List" == t) ? "media-menu-list sort-by-featured" : "media-menu-grid sort-by-featured";        
    }
    catch(e)
    {
        notify("ChangeView(type) " + e.message, true);
    }
};

// NowPlayingFooter.js
// version: 5.0
// requires:
//      - viostream.js

trace("NowPlayingFooter.js");

if(typeof(Viostream) == "undefined"){
    Viostream = { };
}

if (typeof (Viostream.NowPlayingFooter) == "undefined") {
    Viostream.NowPlayingFooter = { };
}


Viostream.Extend(Viostream.NowPlayingFooter, {
    Init: function(o) {
        Viostream.Extend(this, o);

        if (this.PanelId != null) {
            $("#" + this.PanelId).bind("AddToPlayList", this.AddedToPlayListCallback);
            $("#" + this.PanelId).bind("MediaChanged", this.MediaChangedCallback);
            $("#" + this.PanelId).bind("PlayListCleared", this.PlayListClearedCallback);
            $("#" + this.PanelId).bind("PlaylistChanged", this.PlaylistChangedCallback);
            if (jQuery.support.objectAll && !jQuery.support.opacity) {
                window.alert('ie6');
                this.IE6NowPlayingWidth = $(".tab-content").outerWidth();
            }

        }
    },

    PlaylistChangedCallback: function(e, data) {
        $(this).empty();
        for (var i = 0; i < Viostream.PlayList.ClientSidePlaylist.length; i++) {
            $(this).append(
                Viostream.NowPlayingFooter.PlayingFragment((i > 0), Viostream.PlayList.ClientSidePlaylist[i], i)
            );
        }
        SetPlayListSliders();
    },

    ///Move the current NowPlayingFooter div so that the current NowPlaying Item is centred
    MediaChangedCallback: function(e, data) {

        var mediaId = data.MediaId;

        //window.alert("Viostream.NowPlayingFooter.MediaChangedCallback");

        var footeritemcount = 0;

        var footerItems = $("#" + Viostream.NowPlayingFooter.PanelId).children(".now-playing-footer-inner").each(function() {

            var inner = $(this);
            //trace('Viostream.NowPlayingFooter.MediaChanged().footerItem, mediaId = ' + $(this).data("MediaId"));
            if ($(this).data("MediaId") == mediaId) {
                var outer = $(this).parent();
                var innerpos = -1 * parseInt($(this).width(), 10) * footeritemcount;
                trace('Viostream.NowPlayingFooter.MediaChanged().footerItem, innerpos = ' + innerpos);
                outer.animate({
                    left: innerpos
                }, "normal");
            }

            footeritemcount++;
        });

        //window.alert("hjgjhg");

    },
    PlayListClearedCallback: function(e, playlistid) {
        $(this).empty();
    },

    AddedToPlayListCallback: function(e, data) {
        //window.alert('Viostream.NowPlayingFooter.AddedToPlayListCallback()');

        var i = Viostream.PlayList.ClientSidePlaylist.length - 1;

        $("#" + Viostream.NowPlayingFooter.PanelId).append(
            Viostream.NowPlayingFooter.PlayingFragment((i > 0), Viostream.PlayList.ClientSidePlaylist[i], i)
        );
        //SetPlayListSliders();
    },



    PlayingFragment: function(includePreviousButton, mediabaseitem, index) {

        var div = $cE('DIV');
        div.className = "now-playing-footer-inner";

        var img = $cE('IMG');

        if (includePreviousButton) {
            var prevbutton = $cE('A');
            prevbutton.className = "previous-button";
            prevbutton.appendChild(document.createTextNode("Previous item"));
            prevbutton.title = "Previous item in playlist";
            prevbutton.href = "JavaScript:void(0);";

            div.appendChild(prevbutton);
        } else {
            img.style.marginLeft = "14px";
        }


        img.className = "next-thumb";
        img.src = mediabaseitem.ThumbnailURL;


        div.appendChild(img);

        //nextbutton is hidden by default
        var nextbutton = $cE('A');
        nextbutton.className = "next-button";
        nextbutton.appendChild(document.createTextNode("Next item"));
        nextbutton.title = "Next item in playlist";
        nextbutton.href = "JavaScript:void(0);";
        $(nextbutton).hide();

        div.appendChild(nextbutton);


        var dl = $cE("DL");
        dl.className = "next-info";
        var dt = $cE("DT");
        dt.appendChild(document.createTextNode("Title"));
        var dd = $cE("DD");
        var dda = $cE("A");
        dda.href = "javascript:void(0);";
        dda.title = "Play Now";
        dda.innerHTML = mediabaseitem.MediaTitle;
        $(dda).bind("click", { Index: index }, function(e) { trace("playIndex(" + e.data.Index + ")"); playIndex(e.data.Index); });
        dd.appendChild(dda);
        dl.appendChild(dt);
        dl.appendChild(dd);

        var dtc = $cE("DT");
        var ddc = $cE("DD");
        dtc.appendChild(document.createTextNode("Channel"));
        ddc.appendChild(document.createTextNode("Channel Name"));
        dl.appendChild(dtc);
        dl.appendChild(ddc);

        div.appendChild(dl);

        var aplaynow = $cE("A");
        aplaynow.href = "javascript:void(0);";
        aplaynow.className = "vs-playnow";
        aplaynow.appendChild(document.createTextNode("Play now"));
        $(aplaynow).bind("click", { Index: index }, function(e) { trace("playIndex(" + e.data.Index + ")"); playIndex(e.data.Index); });

        $(div).data("MediaId", mediabaseitem.MediaId);

        div.appendChild(aplaynow);
        img.width = 80; //have to resize the thumbnail after it's been added to the parent, otherwise IE doesn't resize it
        img.height = 45; //I know! seriously IE, WTF?
        return div;
    }



});


var SetPlayListSliders = function() {
    trace("SetPlayListSliders()");
    // now-playing-footer
    var innerWidth = 0;

    $(".now-playing-footer").each(function() {

        var o = $(this);
        var npInners = o.children('div.now-playing-footer-inner');
        if (Viostream.NowPlayingFooter.IE6NowPlayingWidth) {
            innerWidth = Viostream.NowPlayingFooter.IE6NowPlayingWidth;
        } else {
            innerWidth = o.parent().outerWidth();
        }

        //totlawidth is the width of the outer 'sleeve' that will get animated
        var totalwidth = npInners.length * innerWidth;
        var currentIndex = 0;
        // now-playing-footer-inners
        npInners.each(function() {
            var inner = $(this);

            //make each playlistitem's width fixed 
            inner.width(innerWidth);

            //next button action
            var nextbutton = inner.children("a.next-button");
            nextbutton.click(function() {
                var curleft = parseInt(o.css("left"), 10);
                o.animate({
                    left: curleft - inner.width()
                }, "slow");
            });

            currentIndex++;

            //if current playlist item is not the last in the ClientSidePlaylist then unhide next button.
            if (currentIndex < npInners.length) {
                nextbutton.show();
            }

            //previous button action
            inner.children("a.previous-button").click(function() {
                var curleft = parseInt(o.css("left"), 10);
                o.animate({
                    left: curleft + inner.width()
                }, "slow");
            });

        });
        o.width(totalwidth);
        // end now-playing-footer-inners
    });
    // end now-playing-footer

}
$(document).ready(function(){
    $(window).resize(SetPlayListSliders).resize();
});
///////////////////////////////////////////////////////////////////////////////////////////////////
// PLAYER  JAVASCRIPT FUNCTIONS
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created: December 2007
// Client:	VioCorp
///////////////////////////////////////////////////////////////////////////////////////////////////

// playerobject.js 
// version: 5.0
// requires:
//      - viostream.videoinfo.js

trace("playerinfo.js");

var swf;

function FlashInit(swfID) {
    
    if (navigator.appName.indexOf("Microsoft") > -1) {
		swf = window[swfID];
	} else {
		swf = document[swfID];
	}
	swf = window["swf"] = window[swfID] = document.getElementById(swfID);
	swf.style.backgroundImage = "none";
	trace("FlashInit");
	Viostream.Extend(window, {
		vioPlayerReady: function () {
			//called when the player is ready
			swf.addEventListener("mediaUpdatedEvent", "onMediaUpdate");
			swf.addEventListener("playlistUpdatedEvent", "onPlaylistUpdate");

			var playListId = $("#txtPlayListId").val();
			if (playListId.length > 0) {
				//playlist was created serverside
				swf.playlistLoad(playListId, "first");
				$("#" + Viostream.VideoInfo.PanelId).trigger("AddToPlayList");
				$("#" + Viostream.PlayListUrlForm.PanelId).trigger("PlayListCreated", { PlayListId: playListId });
				$("#" + Viostream.SharePlaylistForm.PanelId).trigger("PlayListCreated", { PlayListId: playListId });
			}

			if (typeof (Viostream.AutoplayMediaId) != "undefined" && Viostream.AutoplayMediaId != null) {
				Viostream.PlayList.AddByMediaId(Viostream.AutoplayMediaId);
			}
		},

		addToPlayList: function (playListId, mediaId) {
			//var swf = swfobject.getObjectById('player');
			//window.alert("window.addToPlayList swf = " + typeof(swf.addToPlayList));
			//trace("swf.playlistRefresh()");
			swf.addToPlayList(playListId, mediaId);

			//swf.playlistRefresh();

			var addtoplaylistNotice = document.getElementById("addtoplaylistNotice");
			if (addtoplaylistNotice) {
				addtoplaylistNotice.style.display = 'block';

				setTimeout("document.getElementById(\"addtoplaylistNotice\").style.display='none';", 5000);

			}
		},
		reloadPlayList: function () {
			trace("swf.playlistReload();");
			swf.playlistReload();
		},
		refreshPlayList: function () {
			trace("swf.playlistRefresh();");
			swf.playlistRefresh();
			//swf.playlistReload();
		},
		loadPlayList: function (playListId) {
			trace("swf.playlistLoad(" + playListId + ")");
			swf.playlistLoad(playListId);
		},

		shareForm: function (type) {
			//var swf = window["swf"] = window[swfID] = swfobject.getObjectById('player');
			swf.openShareForm(type);
		},
		pausePlay: function (stat) {
			//var swf = window["swf"] = window[swfID] = swfobject.getObjectById('player');
			swf.pausePlayAction(stat);
		},

		updateMedia: function (id, type) {
			//var swf = window["swf"] = window[swfID] = swfobject.getObjectById('player');
			//swf.updateMedia(id,type);
			swf.loadViostream(id);
		},

		playIndex: function (index) {
			trace("swf.playlistPlayIndex(" + index + ");")
			swf.playlistPlayIndex(index);
		},
		// for cogs advertising
		openWindow: function (pageUrl) {
			//var swf = window["swf"] = window[swfID] = swfobject.getObjectById('player');
			var winNew = window.open(pageUrl, "_blank", "toolbar=1,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width=800,height=700,left=200,top=100");
			if (!winNew) {
				swf.openWindowFromSwf(pageUrl);
			}
			else {
				winNew.focus();
			}
		},

		onPlaylistUpdate: function (data) {
			try {
				Viostream.PlayList.ClientSidePlaylist = jQuery.map(data.playlist, function (viostream, i) {
					var mb = new Viostream.MediaBase();
					mb.ParseJSON(viostream);
					return mb;
				});

				jQuery.event.trigger("PlaylistChanged");

			} catch (e) {
				notify("VideoInfo.onPlayListUpdate " + e);
			}
		},

		onMediaUpdate: function (data) {
			try {
				trace("onMediaUpdate");
				if (data.MediaId != "") {
					//happens when playlist is cleared

					var mb = new Viostream.MediaBase();
					mb.ParseJSON(data);
					Viostream.MediaId = mb.MediaId;
					var title = mb.MediaTitle;
					jQuery.event.trigger("MediaChanged", mb);

					/* UPDATE BOOKMARKS */
					var linksObjects =
					{
						"delicious": { "base": "http://del.icio.us/post",
							"urlDelim": "url",
							"titleDelim": "title"
						},
						"digg": { "base": "http://digg.com/submit",
							"urlDelim": "url",
							"titleDelim": "title"
						},
						"reddit": { "base": "http://reddit.com/submit",
							"urlDelim": "url",
							"titleDelim": "title"
						},
						"facebook": { "base": "http://www.facebook.com/sharer.php",
							"urlDelim": "u",
							"titleDelim": null
						},
						"stumbleupon": { "base": "http://www.stumbleupon.com/submit",
							"urlDelim": "url",
							"titleDelim": "title"
						},
						"myspace": { "base": "http://www.myspace.com/index.cfm",
							"urlDelim": "fuseaction=postto&u",
							"titleDelim": "t"
						},
						"twitter": { "base": "http://twitter.com/home",
							"urlDelim": "status",
							"titleDelim": "%20",
							"appendTitle": true
						},
						"linkedin": {
							"base": "http://www.linkedin.com/shareArticle?mini=true",
							"urlDelim": "url",
							"titleDelim": "title",
							"summaryDelim": "summary",
							"sourceDelim": "source"
						}
					};

					if (typeof (Viostream.VideoInfo) != "undefined") {
						$("#" + Viostream.VideoInfo.SocialBookMarkId + " a").each(function () {

							var linkid = this.id.toLowerCase();
							var linkurl = location.href.split("#")[0].split("?")[0] + escape("?MediaId=") + mb.MediaId;
							var linkstr = linksObjects[linkid].base + "?" + linksObjects[linkid].urlDelim + "=" + linkurl;
							if (linksObjects[linkid].titleDelim != null) {
								var title = Viostream.PortalName + " : " + mb.MediaTitle;
								if (linksObjects[linkid].appendTitle)
									linkstr += linksObjects[linkid].titleDelim + title;
								else
									linkstr += "&" + linksObjects[linkid].titleDelim + "=" + title;
							}
							if (linksObjects[linkid].summaryDelim != null) {
								linkstr += "&" + linksObjects[linkid].summaryDelim + "=summary:" + mb.MediaDescription;
							}
							if (linksObjects[linkid].sourceDelim != null) {
								linkstr += "&" + linksObjects[linkid].sourceDelim + "=" + Viostream.PortalName;
							}

							this.href = linkstr;
						});

						var SocialBookMarkButton = $("#" + Viostream.VideoInfo.SocialBookMarkButtonId);
						if (SocialBookMarkButton.length) {
							SocialBookMarkButton[0].onclick = function () {
								addthis_url = location.href.split("#")[0].split("?")[0] + "?MediaId=" + mb.MediaId;
								addthis_title = document.title;
								return addthis_click(this);
							}
						}
					}
				}

			} catch (e) {
				notify("VideoInfo.onMediaUpdate " + e);
			}

		}
	});
}


//PlayListUrlForm.js

trace("PlaylistUrlForm.js");

if (typeof (Viostream) == "undefined") {
    Viostream = { };
}

if (typeof (Viostream.PlayListUrlForm) == "undefined") {
    Viostream.PlayListUrlForm = { };
}


Viostream.Extend(Viostream.PlayListUrlForm, {
	Init: function (o) {
		Viostream.Extend(this, o);

		if (this.PanelId != null) {
			$("#" + this.PanelId).bind("PlayListCreated", this.PlayListCreatedCallback);
		}

		$("#" + this.UrlFieldButtonId).click(function (e) {
			$("#" + Viostream.PlayListUrlForm.UrlFieldId).select();
			return false;
		});
	},

	PlayListCreatedCallback: function (e, data) {
		var PlayListId = data.PlayListId;
		$("#" + Viostream.PlayListUrlForm.UrlFieldId).val(Viostream.PortalUrl + "?playListId=" + PlayListId);
	}
});
//sendtofriend.js

trace("sendtofriend.js");

if(typeof(Viostream) == "undefined"){
    Viostream = { };
}

if (typeof (Viostream.SendToFriendForm) == "undefined") {
    Viostream.SendToFriendForm = { };
}


Viostream.Extend(Viostream.SendToFriendForm, {
    Init: function(o) {
        Viostream.Extend(this, o); 

        if(this.PanelId!=null){
            $("#" + this.PanelId).bind("MediaChanged", this.MediaChangedCallback);
        }
    },
    
    MediaChangedCallback : function(e,mb){
        
        
        trace("Viostream.SendToFriendForm.MediaChangeCallback");
        $("#" + Viostream.SendToFriendForm.SendButton).unbind();
        $("#" + Viostream.SendToFriendForm.SendButton).click(function(){
        
            var senderName =    $("#" + Viostream.SendToFriendForm.SenderName).val();
            var senderEmail =   $("#" + Viostream.SendToFriendForm.SenderEmail).val();
            var receiverEmail = $("#" + Viostream.SendToFriendForm.ReceiverEmail).val();
            var comment =       $("#" + Viostream.SendToFriendForm.Comment).val();
            
            trace("Viostream.SendToFriendForm.SendToFriend(" + mb.MediaId + ", this, " + senderEmail + ", " + receiverEmail + ", " + comment + ")");
            Viostream.SendToFriendForm.SendToFriend(mb.MediaId, this, senderEmail, receiverEmail, comment);
            
        });
        
    },
    
    SendToFriend : function(mediaId, panel, afromEmail, atoEmail, amessage){
        trace("SendToFriend.Click()!");
        $.ajax({
            url : Viostream.MiscWSUrl + "SendToFriend", 
            success : function(o){ Viostream.SendToFriendForm.SendToFriendHandleSuccess(o, panel); },
            data : { contentType : "MediaItem", id : mediaId, fromEmail : afromEmail, toEmail : atoEmail, message : amessage }
        });
        
    },
    
    SendToFriendHandleSuccess : function(o, panel){
        /// <summary> AJAX success event for getting a single media item. Adds the item to the playlist. </summary>
        if(!Viostream.AjaxObject.DisplayErrors(o,"SendToFriend")){
        	$("#" + Viostream.SendToFriendForm.PanelId).hide(); 
        }
    }
});
//SharePlayListForm.js
trace("SharePlayListForm.js");

if(typeof(Viostream) == "undefined"){
    Viostream = { };
}

if (typeof (Viostream.SharePlaylistForm) == "undefined") {
    Viostream.SharePlaylistForm = { };
}


Viostream.Extend(Viostream.SharePlaylistForm, {
    Init: function(o) {
        Viostream.Extend(this, o);
        /*$(document).bind("MediaChanged",this.MediaChanged); 
        $(document).bind("AddToPlayList",this.AddedToPlayList);*/
        if (this.PanelId != null) {
            $("#" + this.PanelId).bind("PlayListCreated", this.PlayListCreatedCallback);
            $("#" + this.PanelId).bind("UserLoggedIn", this.setSenderAttributes);
            $("#" + this.PanelId).bind("UserLoggedOut", this.setSenderAttributes);
        }
    },

    PlayListCreatedCallback: function(e, data) {
        trace("Viostream.SharePlaylistForm.PlayListCreatedCallback()");
        var playListId = data.PlayListId;

        $("#" + Viostream.SharePlaylistForm.SendButton).unbind();
        $("#" + Viostream.SharePlaylistForm.SendButton).click(function() {

            var senderEmail = $("#" + Viostream.SharePlaylistForm.SenderEmail).val();
            var receiverEmail = $("#" + Viostream.SharePlaylistForm.ReceiverEmail).val();
            var comment = $("#" + Viostream.SharePlaylistForm.Comment).val();
            ///TODO: monkey about with webservice
            Viostream.SharePlaylistForm.SendToFriend(playListId, this, senderEmail, receiverEmail, comment);

        });

    },

    setSenderAttributes: function(e, data) {
        //handler for UserLoggedIn UserLoggedOut event - populates SharePlayList Form and disables fields
        if (data != null) {
            
            $("#" + Viostream.SharePlaylistForm.SenderEmail).val(data.EmailAddress);
            $("#" + Viostream.SharePlaylistForm.SenderEmail).attr("disabled", true);
        } else {
            
            $("#" + Viostream.SharePlaylistForm.SenderEmail).attr("disabled", false);
        }
        return;
    },

    SendToFriend: function(playlistId, panel, afromEmail, atoEmail, amessage) {
        trace("SendToFriend.Click()!");
        $.ajax({
            url: Viostream.MiscWSUrl + "SendToFriend",
            success: function(o) { Viostream.SharePlaylistForm.SendToFriendHandleSuccess(o, panel); },
            data: { contentType: "PlayList", id: playlistId, fromEmail: afromEmail, toEmail: atoEmail, message: amessage }
        });

    },

    SendToFriendHandleSuccess: function(o, panel) {
        /// <summary> AJAX success event for getting a single media item. Adds the item to the playlist. </summary>
        if (!Viostream.AjaxObject.DisplayErrors(o, "SendToFriend")) {
        	$("#" + Viostream.SharePlaylistForm.PanelId).hide(); 
        }
    }
});
/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
// TabMenu.js

trace("TabMenu.js");

$(document).ready(function(){
	// Tabs
	$(".tabs").each(function(){
		var o = $(this);
		var tabContainers = o.children('div.tab-content');
		tabContainers.hide().filter(':first').show();
		
		o.children("ul.tab-menu").children("li").children("a").click(function () {
			tabContainers.hide();
			tabContainers.filter(this.hash).show();
			o.children("ul.tab-menu").children("li").children("a").removeClass('tab-selected');
			$(this).addClass('tab-selected');
			return false;
		}).filter(':first').click();
	});
	// End Tabs
});

// viostream.ajax.js 
// version: 1.0
// requires:
//      - viostream.js

trace("viostream.ajax.js");

if(typeof(Viostream) == "undefined"){
    Viostream = { };
}

if(typeof(Viostream.AjaxObject) == "undefined"){
    Viostream.AjaxObject = { };
}

Viostream.Extend(Viostream.AjaxObject,
    {
        SetDefaults : function(){
            $.ajaxSetup({
                dataType : "xml",
                type : "GET",
                success : this.handleSuccess,
                failure : this.handleFailure,
                timeout : 20000
            });
        },
         
        handleSuccess : function(o){
            // This member handles the success response
            // and passes the response object o to AjaxObject's
            // processResult member.
            Viostream.AjaxObject.processResult(o);
            //alert('success');
        },

        processResult:function(o){
            // This member is called by handleSuccess
        },
           
        handleFailure:function(oXMLHttpRequest, textStatus, errorThrown){
            // Failure handler
            Viostream.Category.hideLoader();
            if(oXMLHttpRequest.status==-1){
                notify("Transaction timeout: The server took too long to respond\n\nTransaction ID = " + oXMLHttpRequest.tId, true);
            }else if(status==0){
                notify("Communication failure:", true);
            }
        },

        DisplayErrors : function(oXML, operationName){
            var ErrorMessage = operationName + " Error: \n";
            var Errors = $(oXML).find("Error");
            if(Errors.length > 0){
                Errors.each(function(){ ErrorMessage += $(this).find("Message").text() + "\n\n";  });
                notify("The following errors occurred\n" + ErrorMessage, true);
                Viostream.Category.hideLoader();
                return true;
            }else{
                return false;
            }
        },

        SessionKeepAlive : function(){
            $.ajax({  
                url : Viostream.SessionWSUrl + "SessionPing",
                data : { portalId : Viostream.PortalId, sessionId : Viostream.SessionId }
            });
        }
    }
);


// viostream.animation.js 
// version: 1.0
// requires:
//      - viostream.js

// Handles all animation on the page

trace("viostream.animation.js");

if (typeof (Viostream.Animation) == "undefined") {
    Viostream.Animation = { };
}
Viostream.Extend(Viostream.Animation, {

    /// <summary> Contains all animations used on the page </summary>
    
    /// post open events for use with overloading 
    onRegOpen : function(){ },
    onLoginOpen : function(){ },
    onPasswordOpen : function(){ },
    onRegClose : function(){ },
    onLoginClose : function(){ },
    onPasswordClose : function(){ }
    
    
    /// Registration box
   /* openRegAnim : function(){ $("#" + Viostream.User.register.panelId).animate({height : Viostream.User.register.ToHeight}, Viostream.User.register.Duration, "swing", function(){ this.style.height = 'auto'; Viostream.ScrollTo(this); Viostream.Animation.onRegOpen(); } ); },
    closeRegAnim : function(oCallBack){ $("#" + Viostream.User.register.panelId).animate({height : Viostream.User.register.FromHeight}, Viostream.User.register.Duration, "swing", oCallBack); },
	    
	    
    /// Login Box
    openLoginAnim : function(){ $("#" + Viostream.User.login.panelId).animate({height : Viostream.User.login.ToHeight}, Viostream.User.login.Duration*1, "swing", function(){ this.style.height = 'auto'; Viostream.ScrollTo(this); Viostream.Animation.onLoginOpen(); }); },
    closeLoginAnim : function(oCallBack){ $("#" + Viostream.User.login.panelId).animate({height : Viostream.User.login.FromHeight}, Viostream.User.login.Duration*1, "swing", oCallBack); },
   
	    
    /// Forgotten Password box
    openPasswordAnim : function(){ $("#" + Viostream.User.forgotpassword.panelId).animate({height : Viostream.User.forgotpassword.ToHeight}, Viostream.User.forgotpassword.Duration, "swing", function(){ this.style.height = 'auto'; Viostream.ScrollTo(this); Viostream.Animation.onPasswordOpen(); }); },
    closePasswordAnim : function(oCallBack){ $("#" + Viostream.User.forgotpassword.panelId).animate({height : Viostream.User.forgotpassword.FromHeight}, Viostream.User.forgotpassword.Duration, "swing", oCallBack); }
    */
});

Viostream.ScrollTo = function(elem){
    /// <summary>Performs the scrolling for login/registration boxes. Can be overridden to prevent scrolling.</summary>    
    var wh = window.innerHeight || document.documentElement.clientHeight;
    var wt = window.scrollTop || document.documentElement.scrollTop;
    var ot = $(elem).offset({relativeTo : "body"}).top;    
    if( (ot < wt) || ( ot > (wt+wh) )) elem.scrollIntoView();
};

Viostream.TogglePassword = function(){
   
   $("#" + Viostream.User.forgotpassword.panelId).slideToggle(Viostream.User.forgotpassword.Duration, 
        function(){
            if($(this).is(":visible"))
            {
                //fire event - retgistration form has opened
                Viostream.Animation.onPasswordOpen();
                Viostream.ScrollTo(this);
            }
            else
            {
                //fire event - retgistration form has closed
                Viostream.Animation.onPasswordClose();
            }
        }
     );
     $("#" + Viostream.User.register.panelId + ", #" + Viostream.User.login.panelId).slideUp(Viostream.User.forgotpassword.Duration);
   
   
    
};

Viostream.ClosePassword = function(oCallBack){
    $("#" + Viostream.User.forgotpassword.panelId).slideUp(Viostream.User.forgotpassword.Duration,oCallBack);
};

// The actual open and close functions
Viostream.OpenLogin = function(evt){
    
};

Viostream.CloseLogin = function(oCallBack){
    $("#" + Viostream.User.login.panelId).slideUp(Viostream.User.login.Duration,function(){Viostream.Animation.onLoginClose();oCallBack;});
    //window.alert("closeLogin");
};

Viostream.ToggleLogin = function(){
    $("#" + Viostream.User.login.panelId).slideToggle(Viostream.User.login.Duration, 
        function(){
            if($(this).is(":visible"))
            {
                //fire event - login form has opened
                Viostream.Animation.onLoginOpen();
                //Login from cookie - set if the user wants to be rememebered (on login)
                var email = "";
                var cookieContents = Viostream.Cookies.Read("ViostreamPortal");
                if(cookieContents!=null){
                    var contents = cookieContents.split('&');
                    for(var i=0; i<contents.length; i++){
                        var contContent = contents[i].split('=');
                        if(contContent[0]=='email')
                            email = contContent[1];                
                    }
                }
                
                if( $gE(Viostream.User.login.email) ){
                    $("#" + Viostream.User.login.email).val(email);
                    $("#" + Viostream.User.login.password).val("");
                    $gE(Viostream.User.login.rememberMe).checked = email.length == 0 ? false : true;
                }
                Viostream.ScrollTo(this);
            }
            else
            {
                //fire event - login form has closed
                Viostream.Animation.onLoginClose();
            }
        }
     );
     $("#" + Viostream.User.register.panelId + ", #" + Viostream.User.forgotpassword.panelId).slideUp(Viostream.User.login.Duration);

    
};

Viostream.OpenRegistration = function(){
    // close login first and then open the registration
    /*if($("#" + Viostream.User.login.panelId).height() == 0)
        $("#" + Viostream.User.login.panelId).slideUp(Viostream.User.login.Duration);
    $("#" + Viostream.User.register.panelId).slideDown(Viostream.User.register.Duration);*/
};
    
Viostream.CloseRegistration = function(oCallBack){
    $("#" + Viostream.User.register.panelId).slideUp(Viostream.User.register.Duration,oCallBack);
};

Viostream.ToggleRegistration = function(){
    
    $("#" + Viostream.User.register.panelId).slideToggle(Viostream.User.register.Duration, 
        function(){
            if($(this).is(":visible"))
            {
                //fire event - retgistration form has opened
                Viostream.Animation.onRegOpen();
                Viostream.ScrollTo(this);
            }
            else
            {
                //fire event - retgistration form has closed
                Viostream.Animation.onRegClose();
            }
        }
     );
     $("#" + Viostream.User.forgotpassword.panelId + ", #" + Viostream.User.login.panelId).slideUp(Viostream.User.register.Duration);
};

// viostream.categories.js 
// version: 1.0
// requires:
//      - viostream.js
//      - viostream.pagination.js

trace("categories.js");


Viostream.Extend(Viostream,{

    LoadCategoryFromGuid : function(categoryId, pageIndex, sortOrder, mediaType){
        /// <summary>
        /// This is the main entry for loading/sorting categories. Both searches and category links enter here.
        /// </summary>
        if((typeof(categoryId) == "undefined") || (categoryId == "")) categoryId = this.CurrentCategory;
        if((typeof(pageIndex) == "undefined") || (pageIndex == "")) pageIndex = this.CurrentPageIndex || 0;
        if((typeof(sortOrder) == "undefined") || (sortOrder == "")) sortOrder = this.SortOrder;
        if(typeof(mediaType) == "undefined") mediaType = this.MediaType;
        
        Viostream.MediaType = mediaType;
        
        //change display to show current sort Order - but only bother if sortOrder has changed
        if ((sortOrder != null) && (sortOrder != this.SortOrder)) {
            Viostream.SetCurrentSortOrder(sortOrder);
        }

        //change display to show current media type - but only bother if mediaType has changed
        if ((mediaType != null) && (mediaType != this.mediaType)) {
            Viostream.SetCurrentFilterOption(mediaType);
        }

        Viostream.MediaType = mediaType;

        //show menu sort option controls - they are hidden when user performs a search
        //$(".menu-controls").show();
        
        trace("LoadCategoryFromGuid('" + categoryId + "','" + pageIndex + "','" + sortOrder +"','" + mediaType +"');");
        
        var description = new String();
        var title = new String();
        $("#" + Viostream.messageBoxId).empty().hide();
        try
        {
            if(categoryId=="searchterm"){  
                          
                this.Search((this.SearchTerm=="" ? sortOrder : this.SearchTerm ), pageIndex, mediaType);
            }else{
                
                Viostream.Category.Get(categoryId, pageIndex, sortOrder, mediaType);
            }
            
        }
        catch(e)
        {
            if(this.isDebug)
            {
                alert("LoadCategoryFromGuid(categoryId)" + e.message);
                throw e;
            }
        }
    }

}
);


if (typeof (Viostream.Category) == "undefined") {
    Viostream.Category = { };
}

Viostream.Extend(Viostream.Category, {

    Init: function(o) {
        Viostream.Extend(this, o);    
    },
    /// <summary> All Category functions/ajax </summary>
    CompleteLoad : function(oXML, categoryId, title){
        /// <summary> Draws all category info on the page </summary>
        
        //is this used?
        //var MenuControls = $("div.menu-controls", "#menu-controls");
        
        var ItemInfo = $(oXML).find("ItemInfo");
        
        var recordCount = parseInt(ItemInfo.find("TotalRows").text());
        var pageIndex = parseInt(ItemInfo.find("PageCurrent").text());
        var pageSize = parseInt(ItemInfo.find("PageSize").text());
        
        var totalPages = parseInt(ItemInfo.find("PageCount").text());

        //Viostream.redrawMedia redraws all media elements from responseXML object - returns number of items found/drawn
        if(Viostream.redrawMedia(oXML)==0){
            $("#" + Viostream.messageBoxId).html("There are currently no media files in "+ title +"").show();
        }
       
        ///Pagination
        Viostream.Paginate(recordCount, pageSize, totalPages, pageIndex, categoryId);
    },
    
    MediaListHandleSuccess : function(oXML, title, categoryId){
        /// <summary> AJAX response from the MediaList function </summary>
        
        if(!Viostream.AjaxObject.DisplayErrors(oXML, "MediaList")){
            this.hideLoader();
            this.CompleteLoad(oXML, categoryId, title);
        }
    },
    
    MediaList : function(categoryId, title, pageIndex, sortOrder, mediaType){
        /// <summary> Gets the list of media items from the webservice along with paging info</summary>
        var oParam = {categoryId : categoryId, pageIndex : ++pageIndex, sortby : sortOrder };
        var url = Viostream.WSUrl;
        if((typeof(mediaType) == "undefined") || (mediaType == "") || (mediaType == "All")){
            url += "MediaListPagination";
        } else {
            url += "MediaListTypePagination";
            oParam["mediaType"] = mediaType;
        }
        this.showLoader();        
        $.ajax({
            url : url,
            success : function(oXML){ Viostream.Category.MediaListHandleSuccess(oXML, title, categoryId); },
            data : oParam
        });
    },
        
    GetHandleSuccess : function(oXML, pageIndex, sortOrder, categoryId, mediaType){
        /// <summary> Takes the category info and then calls the MediaList </summary>        
        if( !Viostream.AjaxObject.DisplayErrors(oXML, "Get Category") )
        {            
            var description = $(oXML).find("Description").text();
            var title = $(oXML).find("Title").text().replace(/(&nbsp;)/g," ");
            
            ///Add Category title and discription
            $("#" + this.CategoryTitle).html("<span>" + title + "</span>");
            $("#" + this.CategoryDescription).html(description);
       
            // Check for any Generic HTML items
            $(oXML).find("GenericHTMLModule").each(function() {
                var HtmlElementId = $(this).find("HtmlElementId").text();
                if(HtmlElementId.length > 0){
                    $("#" + HtmlElementId).html($(this).find("Content").text());
                }                
            });
            
            Viostream.CurrentCategory = categoryId;
            Viostream.CurrentPageIndex = pageIndex;
            Viostream.SortOrder = sortOrder;
            
            this.MediaList(categoryId, title, pageIndex, sortOrder, mediaType);
            document.title = Viostream.PortalName + " : " + title;
        }              
    },

    Get : function(categoryId, pageIndex, sortOrder, mediaType){
        /// <summary> Gets the category from the webservice </summary>
        this.showLoader();
        if(Viostream.CurrentCategory == categoryId){
            this.MediaList(categoryId, "this category", pageIndex, sortOrder, mediaType);
        } else {        
            $.ajax({
                url : Viostream.WSUrl + "CategoryGet",
                data : { categoryId : categoryId},
                success : function(oXML){ Viostream.Category.GetHandleSuccess(oXML, pageIndex, sortOrder, categoryId, mediaType); }
            });   
        } 
    },
    showLoader : function(){
        /// <summary> Show the loading notice </summary>
        var oNotice = $("#" + Viostream.loadingNoticeID);
        if(oNotice.length > 0 && !Viostream.fading){
                oNotice.show();
                Viostream.fading = true;
                $("#" + this.CategoryDescription + ", #ulMediaItemWrapper").addClass("opaque");
        }
    },
    hideLoader : function(){
        /// <summary> Hide the loading notice </summary>
        var oNotice = $("#" + Viostream.loadingNoticeID);
        if(oNotice.length > 0){
            oNotice.hide();
            Viostream.fading = false;
            $("#" + this.CategoryDescription + ", #ulMediaItemWrapper").removeClass("opaque");
        }
    }


}
);

// viostream.comments.js 
// version: 2.0
// requires:
//      - viostream.js

trace("viostream.comments.js");

Viostream.Comments = {
	Init: function (o) {

		this.CommentPageSize = 20; //TODO:config setting

		Viostream.Extend(this, o);

		if (this.PanelId != null) {
			$("#" + this.PanelId).bind("MediaChanged", this.MediaChangedCallback);
		}

	},
	AddInit: function (o) {

		Viostream.Extend(this, o);

		if (this.AddCommentPanelId != null) {
			$("#" + this.AddCommentPanelId).bind("MediaChanged", function (e, mb) {
				$(this).data("MediaId", mb.MediaId);
			});
			$("#" + Viostream.Comments.SendButton).click(function () { Viostream.Comments.Validate() });
		}
		if (Viostream.Comments.CreateCaptcha) {
			setTimeout(function () { Viostream.Comments.CreateCaptcha(); }, 200);
		}
	},
	MediaChangedCallback: function (e, mb) {
		var MediaId = mb.MediaId;
		if (MediaId != null && MediaId != "") {
			Viostream.Comments.Populate(MediaId);
		}
	},

	CommentRefresh: function (source) {
		trace("commentRefresh");
		if (typeof (source) != "undefined") {
			source.blur();
		}
		if (Viostream.MediaId != null)
			Viostream.Comments.Populate(Viostream.MediaId, "POST");

	},
	_TransObject: null,

	PopulateHandleSuccess: function (o) {
		try {
			trace(["PopulateHandleSuccess", $("#" + Viostream.Comments.commentLoading)]);
			//set display to none to force it to hide even when the element is hidden. Possible jQuery bug.
			$("#" + Viostream.Comments.commentLoading).fadeOut("fast", function () { this.style.display = "none" });
			$("#" + Viostream.Comments.PanelId).find(".comment").remove();

			if (!Viostream.AjaxObject.DisplayErrors(o, "Populate Comments")) {

				$(o).find("UserComment").each(function (i) {
					var $this = $(this);
					var userAlias = $this.find("Alias").text();
					if (userAlias == "")
						userAlias = "Anonymous";
					var commentId = $this.find("Id").text();
					var d = new Date();
					d.setISO8601($this.find("Created").text(), true);
					var comment = $this.find("Comment").text();

					var oFrag = Viostream.Templates.CommentItem.cloneNode(true);
					var $Frag = $(oFrag.childNodes);


					$Frag.find(".comment-name").find("a")
                        .mouseover(function () { window.status = ""; return false; })
                        .html(userAlias);
					$Frag.find(".comment-date").html(d.getFormatDateTime());
					$Frag.find("P").html(comment);
					$Frag.find("A.comment-flag")
		                .unbind("click")
		                .bind("click", function () { Viostream.Comments.Flag(commentId); });

					var commentPanel = $("#" + Viostream.Comments.PanelId);
					commentPanel.append($Frag);
				});
			}

		}
		catch (e) {
			notify("PopulateHandleSuccess() " + e.message, true);
		}
	},

	PopulateHandleFailure: function (XMLHttpRequest, textStatus, errorThrown) {
		/// <summary> The comments AJAX has failed, so clean up.</summary>

		// Failure handler
		$("#" + Viostream.Comments.commentLoading).fadeOut("fast");
		$("#" + Viostream.Comments.PanelId).find(".comment").remove();

		if (XMLHttpRequest.status == -1) {
			notify("Transaction timeout - PopulateComments : The server took too long to respond");
		} else if (status == 0) {
			notify("Communication failure: - PopulateComments");
		}
	},

	Populate: function (mediaId, type) {

		$("#" + Viostream.Comments.commentLoading).fadeIn("fast");
		trace("comment.fadeIn");
		if ((this._TransObject != null) && (this._TransObject.readyState !== 4) && (this._TransObject.readyState !== 0)) {
			this._TransObject.abort();
		}
		this._TransObject = $.ajax({
			type: type || "GET",
			url: Viostream.CommentWSUrl + "CommentGet",
			data: { mediaId: mediaId },
			success: this.PopulateHandleSuccess,
			error: this.PopulateHandleFailure
		});

	},

	Validate: function () {
		var txtComment = $("#" + Viostream.Comments.Comment).val();
		var txtAnonName = $("#" + Viostream.Comments.SenderName).val();
		var txtAnonEmail = $("#" + Viostream.Comments.SenderEmail).val();
		txtComment ? txtComment = Viostream.trim(txtComment) : txtComment = "";
		txtAnonName ? txtAnonName = Viostream.trim(txtAnonName) : txtAnonName = "";
		txtAnonEmail ? txtAnonEmail = Viostream.trim(txtAnonEmail) : txtAnonEmail = "";

		//$("#" + Viostream.Comments.commentAddProgress).fadeIn("fast");
		Viostream.Comments.Add(txtComment, txtAnonName, txtAnonEmail);

	},
	AddHandleSuccess: function (o, commentText) {
		/// <summary>Success event of adding a comment - inserts the new element</summary>
		if (!Viostream.AjaxObject.DisplayErrors(o, "Add Comment")) {
			Viostream.Comments.Populate(Viostream.MediaId, "POST");

			$("#" + Viostream.Comments.AddCommentPanelId).hide();
			Viostream.Comments.ResetAddForm();


		} else {
			try {
				if (typeof (RecaptchaState) != "undefined") {
					Recaptcha.reload();
				}
			} catch (e) { }
		}

		/*$("#" + Viostream.Comments.commentControls).removeClass("opaque");*/
		$("#" + Viostream.Comments.commentAddProgress).fadeOut("fast");
	},
	ResetAddForm: function () {
		$("#" + Viostream.Comments.Comment).val('');
		$("#" + Viostream.Comments.SenderName).val('');
		$("#" + Viostream.Comments.SenderEmail).val('');
		if (typeof (RecaptchaState) != "undefined") {
			Recaptcha.reload();
		}
	},
	Add: function (commentText, anonAlias, anonEmail) {
		/// <summary>Add a new comment to the currently playing media</summary>

		//only allow adding of comments if Useris logged in, or anonymous comments are allowed AND if there is a currently playing clip...
		if (Viostream.MediaId != null) {
			trace('Comment Add');
			$("#" + Viostream.Comments.commentAddProgress).fadeIn("fast");
			if (Viostream.AnonymousComments) {
				$.ajax({
					url: Viostream.CommentWSUrl + "CommentAddAnonymous",
					success: function (o) { Viostream.Comments.AddHandleSuccess(o, commentText); },
					error: function () { if (typeof (RecaptchaState) != "undefined") { Recaptcha.reload(); } },
					data: {
						sessionId: Viostream.SessionId,
						mediaId: Viostream.MediaId,
						comment: commentText,
						anonAlias: anonAlias,
						anonEmail: anonEmail,
						challenge: Recaptcha.get_challenge(),
						response: Recaptcha.get_response()
					}
				});
			} else {
				if ((Viostream.UserIsLoggedIn)) {
					$.ajax({
						url: Viostream.CommentWSUrl + "CommentAdd",
						success: function (o) { Viostream.Comments.AddHandleSuccess(o, commentText); },
						data: {
							sessionId: Viostream.SessionId,
							mediaId: Viostream.MediaId,
							comment: commentText
						}
					});
				} else {
					notify("Sorry, you need to be logged in before you can comment.");
					if (typeof (Viostream.ToggleLogin) == "function")
						Viostream.ToggleLogin();
				}
			}

		}
		else {
			notify("Sorry, there needs to be a currently playing video clip to comment on.");
		}
	},
	Flag: function (commentId) {
		///<summary>Flag this comment</summary>
		trace("Flag(" + commentId + ")");
		$.ajax({
			url: Viostream.CommentWSUrl + "CommentFlag",
			data: { sessionId: Viostream.SessionId, commentId: commentId },
			success: function (o) {
				if (!Viostream.AjaxObject.DisplayErrors(o, "CommentFlag"))
					notify("The comment has been flagged.");
			}
		});
		return false;
	},

	CaptchaCallback: function () {
		//override if you want this
	}

};

Viostream.PopulateComments = function(mediaId) {
	//check if comment controls are present if not then don't load comments
	if (mediaId != null && $("#" + Viostream.Comments.PanelId).length) {
		Viostream.Comments.Populate(mediaId);
		//Viostream.Comments.ShowControls();
		//Viostream.Comments.CreateCaptcha is provided by the CommentContainer control
		if (Viostream.Comments.CreateCaptcha) {
			setTimeout(function() { Viostream.Comments.CreateCaptcha(); }, 200);
		}
	}
};


// viostream.cookies.js 
// version: 1.0
// requires:
//      - viostream.js

trace("viostream.cookies.js");

Viostream.Cookies = {
    Create : function(name,value,days) {
	    if (days) {
		    var date = new Date();
		    date.setTime(date.getTime()+(days*24*60*60*1000));
		    var expires = "; expires="+date.toGMTString();
	    }
	    else var expires = "";
	    document.cookie = name+"="+value+expires+"; path=/";
    },
    Read : function(name) {
	    var nameEQ = name + "=";
	    var ca = document.cookie.split(';');
	    for(var i=0;i < ca.length;i++) {
		    var c = ca[i];
		    while (c.charAt(0)==' ') c = c.substring(1,c.length);
		    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	    }
	    return null;
    },
    Erase : function(name) { this.Create(name,"",-1); }
};

// viostream.errors.js 
// version: 1.0
// requires:
//      - jquery.tojson.js
//      - viostream.js

trace("viostream.errors.js");

Viostream.Error = function(Message, Data){
    var o = { "m" : Message };
    if(typeof(Data) != "undefined")
        o["d"] = $.toJSON(Data);
    $.ajax({ url: "JSLog.axd", type: "POST", data: o, dataType: "text" });
};

// global ajax error handler
$(document).bind("ajaxError", function(event, XMLHttpRequest, ajaxOptions, thrownError){
        if(ajaxOptions.url != "JSLog.axd"){
            // don't bubble
            new Viostream.Error("Ajax Error: " + thrownError + " [" + XMLHttpRequest.status + "]", ajaxOptions);
        }
}); 

// viostream.history.js 
// version: 1.0
// requires:
//      - viostream.js
//      - jquery.history.js

trace("viostream.history.js");

if (typeof (Viostream.History) == "undefined") {
    Viostream.History = {};
}


Viostream.Extend(Viostream.History, {

    SetValues: function(o) {
        Viostream.Extend(this, o);
    },

    PageClick: function(state) {
        /// <summary> Called on every click action </summary>
        var ParseNavString = function(navstring) {
            navstring = navstring.replace("%2C", ",");
            var matches = navstring.split(",");
            matches.unshift(navstring);
            return matches;
        }

        // if we're not provided with a state, then check for the backend bound query string param else go to default front page
        if (state == "") state = Viostream.History.QueryStringParameter("section") ||
                                    Viostream.firstCategoryId + ",0," + Viostream.SortOrder;
        var matches = ParseNavString(state)
        if (matches != null) {
            var catID = matches[1];
            var pageIndex = matches[2];
            var sortOrder = matches[3];
            var mediaType = matches.length >= 4 ? matches[4] : "All";
            Viostream.LoadCategoryFromGuid(catID, pageIndex, sortOrder, mediaType);
        } else {
            alert("No match for state = " + state);
        }
    },

    SortClick: function(e) {
        try {
            $.history.load(Viostream.CurrentCategory + "," + Viostream.CurrentPageIndex + "," + e.data.sort + "," + Viostream.MediaType);
        } catch (e) {
            Viostream.LoadCategoryFromGuid(Viostream.firstCategoryId, 0, e.data.sort);
        }
        return false;
    },

    FilterClick: function(e) {
        try {
            $.history.load(Viostream.CurrentCategory + "," + Viostream.CurrentPageIndex + "," + Viostream.SortOrder + "," + e.data.filter);
        } catch (e) {
            Viostream.LoadCategoryFromGuid(Viostream.firstCategoryId, 0, Viostream.SortOrder, e.data.filter);
        }
        return false;
    },

    Init: function() {
        /// <summary> Initialises the history object </summary>
        $.history.init(this.PageClick);
        $("a:not(.ignore)", "#" + Viostream.Navigation.ClientId).click(function() {
            var $this = $(this);
            var href = $this.attr("href");
            var section = Viostream.History.QueryStringParameter("section", href) || Viostream.firstCategoryId + ",0," + Viostream.SortOrder;
            $("li.current", "#" + Viostream.Navigation.ClientId).removeClass("current");
            if ($this.hasClass("sub")) {
                //this is a subcategory so make the parent category li the 'current' one
                $(this.parentNode.parentNode.parentNode).addClass("current");
            } else {
                $(this.parentNode).addClass("current");
            }
            $.history.load(section);
            return false;
        });

        ///attach events to SortOrder links
        $("#" + this.AlphabetSortLink).bind("click", { sort: "Alphabetical" }, this.SortClick);
        $("#" + this.DateAddedSortLink).bind("click", { sort: "DateAdded" }, this.SortClick);
        $("#" + this.ViewsSortLink).bind("click", { sort: "Views" }, this.SortClick);
        $("#" + this.RatingSortLink).bind("click", { sort: "Rating" }, this.SortClick);

        //attach the filtering events
        $("#" + this.ContentFilterAll).bind("click", { filter: "All" }, this.FilterClick);
        $("#" + this.ContentFilterVideo).bind("click", { filter: "Video" }, this.FilterClick);
        $("#" + this.ContentFilterImage).bind("click", { filter: "Image" }, this.FilterClick);
        $("#" + this.ContentFilterAudio).bind("click", { filter: "Audio" }, this.FilterClick);

        //attach the tag clound event if viostream.tags.js is included
        if (Viostream.TagCloud) {
            Viostream.TagCloud.Init(this.TagCloudLink);
        }
    },

    QueryStringParameter: function(paramName, url) {
        /// <summary> Returns a section of the query string </summary>
        /// <remarks> Base code "inspired" by YUI code</remarks>
        var i, len, idx, queryString, params, tokens;

        url = url || location.href;

        idx = url.indexOf("?");
        queryString = idx >= 0 ? url.substr(idx + 1) : url;

        // Remove the hash if any
        idx = queryString.lastIndexOf("#");
        queryString = idx >= 0 ? queryString.substr(0, idx) : queryString;

        params = queryString.split("&");

        for (i = 0, len = params.length; i < len; i++) {
            tokens = params[i].split("=");
            if (tokens.length >= 2) {
                if (tokens[0] === paramName) {
                    return unescape(tokens[1]);
                }
            }
        }

        return null;
    }
});

//viostream.keywords.js

trace("viostream.keywords.js");

if (typeof (Viostream.Keywords) == "undefined") {
	Viostream.Keywords = {};
}

Viostream.Extend(Viostream.Keywords, {
	Init: function(o) {
		Viostream.Extend(this, o);
		$("#" + this.sTags).bind("MediaChanged", this.MediaChangedCallback);
	},
	
	MediaChangedCallback: function(e,data){
	    trace("Viostream.Keywords.MediaChangedCallback");
	    var tags = $(this);
	    tags.empty();
	    
	    var keywordDisplay = $(this).parents("dl").children(".videoInfoKeywords");
	    var i = data.KeyWords.length;
	    if(i>0)
	    {
	        keywordDisplay.show(); 
			while (i--) 
	        {
			    var keyword = data.KeyWords[i];
			    var taglink = $(document.createElement("A"));
			    taglink.attr("href", "#searchterm,0," + keyword + ",All");
			    taglink.attr("onclick", "Viostream.PMSearch('" + keyword + "'); return false;");
			    taglink.text(keyword);
			    tags.append(taglink);
			    tags.append(" ");
		    }
		}else{
		    //hide dt and dd
		    keywordDisplay.hide();
		}
	    
	}
});


// viostream.mediabase.js 
// version: 1.0
// requires:
//      - viostream.js
//      - viostream.playlist.js

trace("viostream.MediaBase.js");

if(typeof(Viostream) == "undefined"){
    Viostream = { };
}

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;
	this.ViewCount = 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();
			this.ViewCount = parseInt($xml.find("ViewCount").text(),10);
				
			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.AlbumPicture = function(oXML){
    this.Id = new String();
    this.Created = new String();
    this.Title = new String();
    this.Description = new String();
    this.Width = new String();
    this.Height = new String();
    this.Url = new String();    
    
    this.Parse = function(itemXML){
        var $xml = $(itemXML);
        this.Id = $xml.find("Id").text();
        this.Created = $xml.find("Created").text();
        this.Title = $xml.find("Title").text();
        this.Description = $xml.find("Description").text();
        this.Width = parseInt($xml.find("Width").text());
        this.Height = parseInt($xml.find("Height").text());        
        this.Url =  $xml.find("MediaUrl").find("Url").text();
    }
    
    if(typeof(oXML) != "undefined")
        this.Parse(oXML);

}
Viostream.MediaBase.prototype.ParseJSON = function (viostream) {
	this.MediaId = viostream.MediaId;
	this.MediaType = viostream.MediaType;

	var d = new Date();
	d.setISO8601(viostream.CreateTimeStamp);
	this.Created = d.getFormatDate();

	var mediaURL;
	$.each(viostream.MediaURLs, function () {
		mediaURL = this;
		if (this.Quality == "High")
			return false; //break;
	});

	this.Url = mediaURL.Url;
	this.MediaTitle = viostream.MediaTitle;
	this.MediaDescription = viostream.MediaDescription;
	var thumbnailURL;
	$.each(viostream.Thumbnails, function () {
		thumbnailURL = this.Path;
		if ((this.Width == Viostream.targetThumbNailWidth) && (this.Height == Viostream.targetThumbNailHeight))
			return false; //break;
	});

	this.ThumbnailURL = thumbnailURL;
	this.AverageVotes = viostream.AverageVotes;
	this.rating = Math.round(this.AverageVotes * 2);
	this.KeyWords = viostream.KeyWords;
	this.Source = viostream.AuthorName;
	this.Duration = mediaURL.Duration;
	this.ViewCount = viostream.ViewCount;
};

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 {
		var mb;
		var playNow;

		if (typeof (evt) == "undefined") {
			mb = this;
			playNow = true;
		}
		else {
			mb = evt.data.mb;
			playNow = evt.data.playnow;
		}

		if (typeof (Viostream.PlayList) != "undefined") {
			Viostream.PlayList.ClientSidePlaylist.push(mb);
		}

		var txtPlayListId = $("#txtPlayListId").get(0);
		var playListId = txtPlayListId.value;
		//no current playlist
		if (typeof (Viostream.PlayList) != "undefined") {
			if (playListId.length == 0) {
				///Create a new playlist
				trace("Viostream.PlayList.Create");
				Viostream.PlayList.Create(mb.MediaId, txtPlayListId);
			} else {
				//add mediId GUID to playlist
				Viostream.PlayList.AddMedia(playListId, mb.MediaId, playNow);
				trace("Viostream.PlayList.AddMedia");
			}
		}

		trace("Viostream.MediaBase.prototype.AddToPlayList()");
		jQuery.event.trigger("AddToPlayList", mb);

	}
	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;
		
		updateMedia(mb.MediaId);
		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 : "";
        
		$Frag.addClass(mb.MediaType.toString().toLowerCase()); 
		$Frag.find(".video-title-text")
            .bind("click", { mb: this, playnow: true }, this.AddToPlayList)
            .mouseover(function() { window.status = ""; return false; })
            .html(mb.MediaTitle);
		$Frag.find(".vs-description").html(this.FormatDesc(mb.MediaDescription));
		$Frag.find(".vs-thumb").find("img")
            .attr("src", mb.ThumbnailURL)
            .width(Viostream.targetThumbNailWidth)
            .height(Viostream.targetThumbNailHeight);
		$Frag.find(".vs-date").html(mb.Created);
		$Frag.find(".vs-duration").html(Viostream.parseDuration(mb.Duration));
		$Frag.find(".vs-playnow").bind("click", { mb: this, playnow: true }, this.AddToPlayList);
		$Frag.find(".vs-views").html("Views : " + mb.ViewCount);
		$Frag.find(".vs-addtoplaylist").bind("click", { mb: this, playnow: false }, this.AddToPlayList);
		//$Frag.find(".vs-removefromplaylist").bind("click", { MediaId: this.MediaId }, Viostream.PlayList.RemoveFromPlayList);
		if( (Viostream.UseRating) && (mb.rating > 0)){
            $Frag.find(".rateList").find("li").slice(0,mb.rating).each(function(){ 
                if(this.className.indexOf("right") != -1) 
                    this.className = this.className.replace("right", "rightstarred");
                else
                    this.className += " starred";
                });
        }


        $Frag.find(".vs-container").bind("MediaChanged", { MediaId: this.MediaId }, this.MediaChangedCallback);
        //$Frag.find(".vs-container").bind("MediaRemovedFromPlaylist", { MediaId: this.MediaId }, this.MediaRemovedCallback);
        
              
		var ulMediaItemWrapper = $("#" + Viostream.mediaItemListId);
		
		ulMediaItemWrapper.append($Frag);
	}
	catch (e) {
		notify("BuildMediaItemElement(mb) " + e.message, true);
	}
};

//remove inplaylist indicator and switch remove from playlist button with add to playlist button
Viostream.MediaBase.prototype.MediaRemovedCallback = function(e,data){
    trace("MediaBase.prototype.MediaRemovedCallback");
    if(e.data.MediaId == data){
        $(this).removeClass("vs-inplaylist");
        $(this).find(".vs-removefromplaylist").hide();
        $(this).find(".vs-addtoplaylist").show();
    } 
}

//hide/show now playing indicator
Viostream.MediaBase.prototype.MediaChangedCallback = function(e,data){
    trace("MediaBase.prototype.MediaChangedCallback");
    if(e.data.MediaId == data.MediaId){
        $(this).find(".now-playing-indicator").show();
    }else{
        $(this).find(".now-playing-indicator").hide();
    } 
}

Viostream.Extend(Viostream, {
    ClearMediaItemElement : function(){

        /// <summary> Empty the media items </summary>
        try
        {
            $("#" + Viostream.mediaItemListId).empty();
        }
        catch(e)
        {
            notify("Viostream.MediaBase.ClearMediaItemElement() " + e.message, true);
        }
    },
    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 + ")";
    },

    redrawMedia : function(responseXML) {

	    var mediaBaseElements = $(responseXML).find("MediaBase");

	    ///Clear all existing elements in the container item
	    Viostream.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.pagination.js 
// version: 1.0
// requires:
//      - viostream.js

trace("viostream.pagination.js");

Viostream.Extend(Viostream,{
    
    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() {
	        trace("pageclick");
		    var section = catID + "," + pageIndex + "," + Viostream.SortOrder + "," + Viostream.MediaType;
		    try {
			    Viostream.CurrentPageIndex = pageIndex;
			    $.history.load(section);
		    } catch (e) {
			    Viostream.LoadCategoryFromGuid(section, 0);
		    }
		    return false;
	    }).append($cT(content)).addClass(aClassName).addClass(liClassName);
	    return a;
    },
    Paginate : function(recordCount, pageSize, totalPages, currentPageIndex, categoryId){
        try {
		    if (recordCount > pageSize) {  //only draw pagination controls if the total number of records > the page size
    		    trace("paginate");
			    var ul = $cE("div");
                
			    //build first link
    			var b = new Viostream.PageLink("&lt;&lt;", categoryId, 0, "", "first");
			    ul.appendChild(b);
                
			    //build previous link
			    var previousIndex = (currentPageIndex > 1) ? currentPageIndex - 2 : 0;
			    ul.appendChild(new Viostream.PageLink("&lt;", categoryId, previousIndex, "", "previous"));

			    //build page links
			    for (var j = 0; j < totalPages; j++) {
				    ul.appendChild(new Viostream.PageLink(j + 1, categoryId, j, (j + 1 == currentPageIndex ? "current" : ""), ""));
			    }

			    //build next link
			    var nextIndex = (currentPageIndex < totalPages) ? currentPageIndex : totalPages - 1;
			    ul.appendChild(new Viostream.PageLink("&gt;", categoryId, nextIndex, "", "next"));

			    //build last link
			    ul.appendChild(new Viostream.PageLink("&gt;&gt;", categoryId, totalPages - 1, "", "last"));
			    //$("div.pagination-controls").empty().append(ul).show();
			    $("div.pagination-controls").each(function(){
			        var u = $(ul).clone(true);
			        $(this).empty();
			        $(this).append(u);
			        $(this).show();
			    });
		    } else {
			    $("div.pagination-controls").empty().hide();
		    }
	    }
	    catch (e) {
	        trace("errrr");
		    if (this.isDebug) {
			    alert("paginate)" + e.message);
			    throw e;
		    }
	    }   
    }
});



// viostream.playlist.js 
// version: 1.0
// requires:
//      - viostream.js
//      - viostream.mediabase.js

trace("viostream.playlist.js");

if (typeof (Viostream) == "undefined") {
    Viostream = { };
}

if (typeof (Viostream.PlayList) == "undefined") {
    Viostream.PlayList = { };
}

Viostream.Extend(Viostream.PlayList, {
    Init: function(o) {
        Viostream.Extend(this, o); 
        
        if(this.PanelId!=null){
            $("#" + this.PanelId).bind("PlayListCreated", this.PlayListCreatedCallback);
            $("#" + this.PanelId).bind("AddToPlayList", this.AddToPlayListCallback);
            $("#" + this.PanelId).bind("MediaChanged", this.MediaChangedCallback);
            $("#" + this.PanelId).bind("PlayListCleared", this.PlayListClearedCallback);
            $("#" + this.PanelId).bind("PlaylistChanged",this.RedrawPlayList);
            //$(document).bind("MediaChanged",this.MediaChangedCallback);
        }
    },
    InitClearBehaviour: function(o){
        Viostream.Extend(this, o); 
        
        if(this.ClearPanelId!=null)
        {
            $("#" + this.ClearPlayListButton).bind("click", this.ClearPlayList);
        }
    },
    ClearPlayList : function(e){
        var PlayListId = $("#txtPlayListId").val();
        if(PlayListId.length>0){
            trace(PlayListId);
            $.ajax({
                url : Viostream.PlayListWSUrl + "PlayListClear", 
                success : function(o) {  Viostream.PlayList.ClearPlayListHandleSuccess(o,PlayListId); },
                data : { playListId : PlayListId }
            });
        }
    },
    ClearPlayListHandleSuccess : function(o, PlayListId){
        trace("ClearPlayListhandleSuccess");
        if(!Viostream.AjaxObject.DisplayErrors(o,"ClearPlayList")){
            jQuery.event.trigger("PlayListCleared",PlayListId);  
            $("#" + Viostream.PlayList.ClearPanelId).hide();
            refreshPlayList();
        }
    },
    
    MediaChangedCallback : function(e,data){
        trace("Viostream.PlayList.MediaChangedCallback()");
        Viostream.PlayList.IndicateNowPlaying(data.MediaId);
    },
    
    PlayListClearedCallback : function(e,data){
        trace("Viostream.PlayList.PlayListClearedCallback()");
        Viostream.PlayList.ClientSidePlaylist.length = 0;
        var ulMediaItemWrapper = $(this).find(".playlist-list-view");   
        ulMediaItemWrapper.empty();
    },

    AddToPlayListCallback : function(e,data){
        try {
		    
		    //populate the playlist list
            
		    Viostream.PlayList.RedrawPlayList();
		    
	    }
	    catch (e) {
	        //window.alert("AddToPlayListCallback  -Error");
		    notify("Viostream.PlayList.AddToPlayListCallback(e,mb) " + e.message, true,e);
	    }
    },
    RedrawPlayList : function()
    {
        var ulMediaItemWrapper = $("#" + Viostream.PlayList.PanelId).find(".playlist-list-view");
            
        ulMediaItemWrapper.empty();
        
        var i = Viostream.PlayList.ClientSidePlaylist.length;
        while(i--)
        {
            var oFrag = Viostream.Templates.PlayListItem.cloneNode(true);
            var mb = Viostream.PlayList.ClientSidePlaylist[i];
            var $Frag = $(oFrag.childNodes);
	        $Frag.find(".vs-name")
                .bind("click", { Index : i }, function(e){ playIndex(e.data.Index);/*updateMedia(e.data.MediaId,"mediaId");*/})
                .mouseover(function() { window.status = ""; return false; })
                .html(mb.MediaTitle);
	        $Frag.find(".vs-description").html(mb.MediaDescription);
	        $Frag.find(".vs-thumb")
                .attr("src", mb.ThumbnailURL);
	        $Frag.find(".vs-date").html(mb.Created);
	        $Frag.find(".vs-duration").html(Viostream.parseDuration(mb.Duration));
	        $Frag.find(".vs-playnow").bind("click", { Index : i }, function(e){ playIndex(e.data.Index); });
	        $Frag.find(".vs-removefromplaylist").bind("click", { MediaId : mb.MediaId, ClientSidePlayListIndex : i }, Viostream.PlayList.RemoveFromPlayList); 
            $Frag.find(".now-playing-indicator").hide();
	        $Frag.data("MediaId",mb.MediaId);
	        ulMediaItemWrapper.prepend($Frag);
	    }
    },
    
    RemoveFromPlayList : function(e){
        var MediaId = e.data.MediaId;
        var PlayListId = $("#txtPlayListId").val();
        var cspi = e.data.ClientSidePlayListIndex;
        $.ajax({
            url : Viostream.PlayListWSUrl + "PlayListRemoveMedia", 
            success : function(o){ Viostream.PlayList.RemoveFromPlayListHandleSuccess(o, MediaId, cspi); },
            data : { playListId : PlayListId ,mediaId : MediaId }
        });
    },

    RemoveFromPlayListHandleSuccess : function(o, MediaId, cspi){
        trace("RemoveFromPlayListHandleSuccess");
        if(!Viostream.AjaxObject.DisplayErrors(o,"RemoveFromPlayList")){
            $(".playlist-list-view").children("li").each(function(){
                if($(this).data("MediaId")==MediaId){
                    $(this).fadeOut("normal", function(){ 
                        $(this).remove(); 
                        trace("removed");
                    });
                }
            });
            jQuery.event.trigger("MediaRemovedFromPlaylist",MediaId);
            //remove from clientsideplaylist too
            if(typeof(cspi)!="undefined"){
                Viostream.PlayList.ClientSidePlaylist.splice(cspi,1);
            }
            
            refreshPlayList();
            
        }
        
        
    },
    IndicateNowPlaying : function(){
        
        var targ =  $("#" + this.PanelId).find(".playlist-list-view");
        var lis = $(targ).children("li");
        var mediaId = (arguments.length==1 ? arguments[0] : Viostream.MediaId);
        trace("IndicateNowPlaying(mediaId = " + mediaId + ")");
        var i = lis.length;
        while(i--)
        {
            var $frag = $(lis[i]);
            if($frag.data("MediaId") == mediaId){
                $frag.find(".vs-container").addClass("vs-nowplaying");
                $frag.find(".now-playing-indicator").show();
            }else{
                $frag.find(".vs-container").removeClass("vs-nowplaying");
                $frag.find(".now-playing-indicator").hide();
            }
        }
    },
    
    ClientSidePlaylist : new Array(),
    
    

    MediaGetHandleSuccess : function(o){
        /// <summary> AJAX success event for getting a single media item. Adds the item to the playlist. </summary>
        if(!Viostream.AjaxObject.DisplayErrors(o,"MediaGet")){
            var mb = new Viostream.MediaBase( $(o).find("MediaBase")[0] );
            mb.AddToPlayList();
        }
    },

    MediaGet :  function(mediaId){
        /// <summary> Gets a single media item for adding to the playlist </summary>
        $.ajax({
            url : Viostream.WSUrl + "MediaGet", 
            success : this.MediaGetHandleSuccess,
            data : { mediaId : mediaId }
        });
    },

    AddHandleSuccess : function(o, playListId, mediaId, playNow){
        if(!Viostream.AjaxObject.DisplayErrors(o,"AddtoPlaylist")){ 
            /// COMMENT THIS LINE - PLAYER 2
            //addToPlayList(playListId, mediaId); //mediaId --> addToPlaylist is flash function - playerobject.js
            
            /// UNCOMMENT THESE LINES - PLAYER 2
            if(playNow){
                
                trace("swf.playlistLoad('" + playListId + "','last');");
                swf.playlistLoad(playListId,"last");
            }else{
                //swf.playlistLoad(playListId);
                trace("swf.playlistRefresh();");
                swf.playlistRefresh();
                
            }

            Viostream.Category.hideLoader();
        }
    },

    AddMedia : function(playListId, mediaId, playNow){
        // <summary> Add a media item to the playlist </summary>
        Viostream.Category.showLoader();
        $.ajax({
            url : Viostream.PlayListWSUrl + "PlayListAddMedia", 
            data : { playListId : playListId, mediaId : mediaId },
            success : function(o){ Viostream.PlayList.AddHandleSuccess(o, playListId, mediaId, playNow);  }
        });
    },

    Create : function(playGUID, txtPlayListId){
        /// <summary> Creates a new playlist and then adds the media item to it </summary>
        Viostream.Category.showLoader();
        trace("Visoteam.PlayList.Create()");
        $.ajax({
            url : Viostream.PlayListWSUrl + "PlayListCreate", 
            success : function(o){ Viostream.PlayList.CreateHandleSuccess(o, playGUID, txtPlayListId); },
            data : { }
        });
    },
    
    CreateHandleSuccess : function(o, playGUID, txtPlayListId){
        /// <summary> AJAX success event for creating a new playlist </summary>
        if(!Viostream.AjaxObject.DisplayErrors(o,"PlayList Create")){
            txtPlayListId.value = $(o).find("Id").text();
            //add mediId GUID to playlist
            //window.alert("Playlist.CreateHandleSuccess");
            //this.AddMedia(txtPlayListId.value, playGUID, true);
            //jQuery.event.trigger("PlayListCreated" , {"Guid" : playGUID} );
            trace("Visoteam.PlayList.CreateHandleSuccess(" + o + "," + playGUID + "," + txtPlayListId.value + ")")
            
            
            jQuery.event.trigger("PlayListCreated" , {"Guid" : playGUID, "PlayListId" : txtPlayListId.value} );
         }
    },

    PlayListCreatedCallback : function(e,data){
        
        trace("Viostream.PlayList.PlayListCreatedCallback(" + e + "," + data + ")");
        
        //UNCOMMENT THE FOLLOWING LINE - PLAYER 2
        Viostream.PlayList.AddMedia(data.PlayListId, data.Guid, true);
        
    },

    AddByMediaId : function(playGUID){
        /// <summary>
        /// Add a single media item to the playlist. Used by the AutoPlay at onload.
        /// </summary>
        try
        {
            this.MediaGet(playGUID)
        }
        catch(e)
        {
            if(Viostream.isDebug)
            {
                alert("Playlist.AddByMediaId(playGUID) " + e.message);
                throw e;
            }
        }
    }
});

// viostream.rating.js 
// version: 1.5
// requires:
//      - viostream.js

trace("viostream.rating.js");

if (typeof(Viostream.Ratings) == "undefined") {
    Viostream.Ratings = { };
}

jQuery.extend(Viostream.Ratings,{

    //used to store collection of RatedMediaItem objects
    RatedMedia: new Array(),
    Stars: null,

    RatedMediaItem: function(mediaId, userRating) {
	    this.mediaId = mediaId;
	    this.userRating = userRating;
    },

    SubmitHandleSuccess: function(o, rating) {
	    if (!Viostream.AjaxObject.DisplayErrors(o, "Rating")) {
		    this.RatedMedia.push(new this.RatedMediaItem(Viostream.MediaId, rating));
		    if (Viostream.AnonymousRating) {
			    Viostream.Ratings.SetRatingsCookie(Viostream.MediaId, rating);
		    }
	    }
    },

    Submit: function(rating) {
	    var uId = Viostream.user.Id || 0;
	    $.ajax({
		    url: Viostream.RatingWSUrl + "RatingSubmit",
		    data: { sessionId: Viostream.SessionId, mediaId: Viostream.MediaId, vote: rating, userId: uId },
		    success: function(o) { Viostream.Ratings.SubmitHandleSuccess(o, rating); }
	    });
    },

    AlreadyRated: function(mediaId) {
	    for (var i = 0; i < this.RatedMedia.length; i++) {
		    if (mediaId == this.RatedMedia[i].mediaId)
			    return true;
	    }
	    return false;
    },

    Rate: function(rating) {
	    if (!this.AlreadyRated(Viostream.MediaId)) {
		    this.Submit(rating);
	    }
    },

    // -------------- Code below this is for the display of a rating under the media player ---------------------

    mouseOver: function(e) {
	    /// <summary> Event called when user hovers over a star </summary>
	    //only allow rating if user is logged in
	    Viostream.Ratings.UnrateStars();
	    Viostream.Ratings.RateStars(this, "starred");

    },

    RateStars: function(j, classname) {
	    /// <summary> Turns all stars up to the currently hovered star to yellow(classname) </summary> 
	    var links = this.Stars;
	    for (var i = 0; i < links.length; i++) {
		    links[i].className = links[i].className.replace("starred", "") + " " + classname;
		    //we want to stop highlighting stars at this point
		    if (links[i] == j)
			    break;
	    }
	    
    },

    UnrateStars: function(rating) {
	    /// <summary> Resets the star ratings </summary>
	    
	    var links = Viostream.Ratings.Stars;
	    for (var i = 0; i < links.length; i++) {
		    links[i].className = links[i].className.replace("starred", "");
		    //links[i].className = links[i].className.replace("rated", "");
	    }

    },

    UnrankStars: function() {
	    /// <summary> Resets the star ratings </summary>
	    var links = Viostream.Ratings.Stars;
	    for (var i = 0; i < links.length; i++) {
		    links[i].className = links[i].className.replace("rated", "");
	    }

    },

    SetRating: function() {
        var $rating = null;
        if(typeof(Viostream.VideoInfo.Rating)=="undefined"){
            $rating = $(".rating");
        }else{
            $rating = $("#" + Viostream.VideoInfo.Rating);
        }
        //var $rating = (typeof(Viostream.VideoInfo.Rating)=="undefined" ? $(".rating") : $("#" + Viostream.VideoInfo.Rating));
	    if (Viostream.UserIsLoggedIn || Viostream.AnonymousRating) {
		    //only allow rating if user is logged in
		    //set rating
		    Viostream.Ratings.RateStars(this, "starred");
		    //variable to store numerical rating
		    var newRating = 0;
		    //remove event handler functions and work out the index of this anchor
		    newRating = 1 + Viostream.Ratings.Stars.unbind().index(this);

		    $rating.unbind();
		    //newRating is actually count of "half stars" selected by user
		    newRating /= 2;
		    Viostream.Ratings.Rate(newRating);
	    } else if (!$("#" + Viostream.User.login.panelId).is(":visible")) {
		    Viostream.ToggleLogin();
	    }
    },

    UpdateDisplay: function(rating) {
        
	    var $rating = null;
        if(typeof(Viostream.VideoInfo.Rating)=="undefined"){
            $rating = $(".rating");
        }else{
            $rating = $("#" + Viostream.VideoInfo.Rating);
        }
	    rating = Math.round(parseFloat(rating) * 2);
	    if (($rating.length > 0) && Viostream.UseRating) {
		    if (this.Stars == null)
			    this.Stars = $rating.find("a");

		    $rating.unbind()
                .css("visibility", "visible"); // show the container

		    //clear the slate
		    this.UnrateStars(rating);
		    this.UnrankStars();

		    //If user has already rated this clip then display their rating
		    for (var i = 0; i < this.RatedMedia.length; i++) {
			    if (Viostream.MediaId == this.RatedMedia[i].mediaId) {
				    this.RateStars(this.Stars[(Math.round(this.RatedMedia[i].userRating * 2)) - 1], "starred");
				    this.Stars.unbind()
				    return; //exit at this point
			    }
		    }

		    $rating.bind("mouseout", this.UnrateStars);

		    this.Stars.unbind()
                      .bind("mouseover", this.mouseOver)
                      .bind("click", this.SetRating);

		    //set current rating
		    if (rating > 0) {
			    this.RateStars(this.Stars[rating - 1], "rated");
		    }
	    }
    },

    SetRatingsCookie: function(mediaId, rating) {
	    var cookie = mediaId + ":" + rating + ",";
	    var ratings = this.GetRatingsCookie();
	    for (mediaId in ratings) {
		    cookie += mediaId + ":" + ratings[mediaId] + ","
	    }
	    Viostream.Cookies.Create("ViostreamRatings", cookie, 1);
    },

    GetRatingsCookie: function() {
	    var ratings = {};
	    var anonRatings = Viostream.Cookies.Read("ViostreamRatings");
	    if (anonRatings) {
		    var arrAnonRatings = anonRatings.split(",");
		    if (arrAnonRatings.length) {
			    var i = arrAnonRatings.length - 1;
			    while (i--) {
				    var kv = arrAnonRatings[i].split(":");
				    if (kv.length) {
					    ratings[kv[0]] = kv[1];
				    }
			    }
		    }
	    }
	    return ratings;
    },

    CheckForAnonRating: function() {
	    var ratings = this.GetRatingsCookie();
	    for (mediaId in ratings) {
		    Viostream.Ratings.RatedMedia.push(new this.RatedMediaItem(mediaId, ratings[mediaId]));
	    }
    }
	
});

jQuery.extend(Viostream,{
    RateThis : function(rating) 
    {
        trace("RateThis");
	    /// <summary> 
	    /// Called after the media player has started playing an item. This should 
	    /// display the average rating, or the user's rating for the media item.
	    /// </summary>
	    if (Viostream.AnonymousRating) {
		    Viostream.Ratings.CheckForAnonRating();
	    }

	    Viostream.Ratings.UpdateDisplay(rating);


    }
});


// viostream.search.js 
// version: 1.0
// requires:
//      - viostream.js
//      - viostream.mediabase.js
trace("viostream.search.js");

if (typeof(Viostream) == "undefined") {
    Viostream = { };
}

if (typeof(Viostream.search) == "undefined") {
    Viostream.search = { };
}

Viostream.Extend(
    Viostream.search,{
        Init: function(o){
            Viostream.Extend(this, o); 
            $("#" + this.SearchBoxId).keydown(function(e) {
	            if (e.keyCode == 13) {
		            //setTimeout("Viostream.PortalMediaSearch()", 10);
		            Viostream.PortalMediaSearch();
		            return false;
	            }
            });
            
        }
    }
);

jQuery.extend(Viostream,{

    PortalMediaSearch : function(){
        /// <summary> Fired by the DoSearch event </summary>
        try
        {   
            var searchword = $("#" + Viostream.search.SearchBoxId).val();
            this.SearchTerm = searchword;
            Viostream.PMSearch(searchword);
        }
        catch(e)
        {
            if(Viostream.isDebug)
            {
                alert("PortalMediaSearch() " + e.message);
                throw e;
            }
        }
    },
    PMSearch : function(searchword){
        /// <summary> 
        /// Converts the search phrase into a suitable querystring and/or calls the history manager to navigate to it.
        /// </summary>
        try
        {
            if(searchword.length!=0 && searchword!="SEARCH"){
                section = "searchterm,0," + searchword + "," + this.MediaType;
                //alert("wtf = " + section);
                if(document.location.href.toLowerCase().indexOf("upload.aspx")!=-1){
                    document.location.href="default.aspx#navbar=" + section;
                }else{
                    Viostream.SearchTerm = searchword;
                    $.history.load(section);
                }
            }else{
                notify("No keywords entered. Please enter at least one search keyword");
                //this.ClearMediaItemElement();
            }

            
        }
        catch(e)
        {
            if(Viostream.isDebug){
                alert("PMSearch() " + e.message);
                throw e;
            }
        }
    },
    Search : function(SearchWord, PageIndex, MediaFilter ){
        /// <summary> Performs the search </summary>
        
        
        if(typeof(MediaFilter) == "undefined") MediaFilter = this.MediaType;
        
        // change the current variables so that we can sort and filter the search results
        this.CurrentCategory = "searchterm";
        this.CurrentPageIndex = PageIndex;
        this.MediaType = MediaFilter;
        this.SearchTerm = SearchWord;
        
        var SearchHandleSuccess = function(o){
            /// <summary> AJAX search response </summary>
            if(!Viostream.AjaxObject.DisplayErrors(o,"Search")){
                $("div.pagination-controls").empty().hide(); // search does not paginate
                if(Viostream.redrawMedia(o) == 0){
                    notify("Search result doesn't return any data");
                } 
            }
            Viostream.Category.hideLoader();
            $("#" + Viostream.Category.CategoryTitle).html("<span>Search Results</span>");
            $("#" + Viostream.Category.CategoryDescription).html("<p>Displaying search results for the search term:" + SearchWord + "</p>");
            //$(".menu-controls").hide();
        };
        
        
        Viostream.Category.showLoader();
        //BACKWARDS COMPATABILITY BULLSHIT - IF ONLY WE WERE USING A GAC CORE ASSEMBLY WE WOULDN'T NEED TO ADD THIS KIND OF HACK
        //DELETE THIS CONDITIONAL STATEMENT ONCE ALL PORTALS ARE USING THE LATEST VERSION OF CORE
        if(MediaFilter!="All"){
            $.ajax({
                url : Viostream.WSUrl + "MediaSearchMediaType",
                data : { searchWord : SearchWord, pageIndex : PageIndex, mediaType : MediaFilter },
                success : SearchHandleSuccess
            });
        }else{
            $.ajax({
                url : Viostream.WSUrl + "MediaSearch",
                data : { searchWord : SearchWord, pageIndex : PageIndex },
                success : SearchHandleSuccess
            });
        }
        
    }

});

// viostream.templates.js 
// version: 1.0
// requires:
//      - viostream.js

trace("viostream.templates.js");

Viostream.Templates = {
    Init: function() {
        this.MediaItemInit();
        this.PlayListItemInit();
        this.CommentItemTemplate();
    },
    //tempTemplate holds an HTML string that contains a copy of a single media Item output by the back-end
    tempTemplate: "",
    playlistTemplate: "",
    commentItemTemplate: "",

    MediaItemInit: function() {
        if (typeof (this.MediaItem) != "undefined" && Viostream.Templates.tempTemplate != "") {
            this.MediaItem.appendChild($(Viostream.Templates.tempTemplate).get(0));
        }
    },

    PlayListItemInit: function() {
        if (typeof (this.PlayListItem) != "undefined" && Viostream.Templates.playlistTemplate != "") {
            this.PlayListItem.appendChild($(Viostream.Templates.playlistTemplate).get(0))
        }
    },

    CommentItemTemplate: function() {
        if (typeof (this.CommentItem) != "undefined" && Viostream.Templates.commentItemTemplate != "") {
            this.CommentItem.appendChild($(Viostream.Templates.commentItemTemplate).get(0))
        }
    },

    MediaItem: document.createDocumentFragment(),
    PlayListItem: document.createDocumentFragment(),
    CommentItem: document.createDocumentFragment()

};

// viostream.thumbnails.js 
// version: 1.0
// requires:
//      - viostream.js

trace("viostream.thumbnails.js");

Viostream.Thumbnail = function(oXML){
    /// <summary> Parses out the thumbnail xml to get useful thumbnail info </summary>
    var Width = 0;
    var Height = 0;
    var Path = "";
    
    this.Parse = function(itemXML){
        try
        {            
            var $item = $(itemXML);
            this.Width = parseInt( $item.find("Width").text() );
            this.Height = parseInt( $item.find("Height").text() );
            this.Path = $item.find("Path").text();            
        }
        catch(e)
        {
            if(Viostream.isDebug){
                alert("Thumbnail.Parse(). " + e.message);
                throw e;
            }
        }
    };
    
    if(typeof(oXML) != "undefined")
        this.Parse(oXML);
};

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");       
    for(var i=0; i < Thumbnails.length; i++){
        var thumb = new Viostream.Thumbnail(Thumbnails[i]);
        ret = thumb.Path;
        if( (thumb.Width == width) && (thumb.Height == height) )
            break;
    }
    return ret;
};

// viostream.user.js 
// version: 1.0
// requires:
//      - viostream.js
// optional:
//      - viostream.comment.js

trace("viostream.user.js");
if (typeof (Viostream) == "undefined") {
    Viostream = { };
}

if (typeof (Viostream.User) == "undefined") {
    Viostream.User = function(){}
}



jQuery.extend(Viostream.User.prototype, {
    Id:"",
    FirstName:"",
    LastName:"",
    EmailAddress:"",
    Alias:"",
    
    PopulateUser : function(id,firstname, lastname, email, alias){
        /// <summary> Called after the user has logged, fills in the user details and updates the login status </summary>
        this.Id = id;
        this.FirstName = firstname;
        this.LastName = lastname;
        this.EmailAddress = email;
        this.Alias = (alias == null ? email : alias);
        Viostream.UserIsLoggedIn = true;
        if(typeof(Viostream.CloseLogin)=="function"){
            Viostream.CloseLogin();
        }
        jQuery.event.trigger("UserLoggedIn", Viostream.user);
        Viostream.changeLoginStatus();
    }
});



Viostream.Extend(Viostream,{
    ForgotPassword : function(){
        /// <summary> Called when a user clicks on the "Retrieve Password" button </summary>
        var email = $("#" + Viostream.User.forgotpassword.email).val();
        Viostream.user.ForgotPassword(email);
    },
    changeLoginStatus : function(){
        /// <summary> Update the screen to reflect the changed login status </summary>
        var loginName = "logged in";
        if(Viostream.User.loginStatus.DisplayFields=="Alias"){
            loginName += " as " + Viostream.user.Alias;
        }else if(Viostream.User.loginStatus.DisplayFields=="FirstName"){
            loginName += " as " +  Viostream.user.FirstName;
        }else if(Viostream.User.loginStatus.DisplayFields=="LastName"){
            loginName += " as " +  Viostream.user.LastName;
        }else if(Viostream.User.loginStatus.DisplayFields=="Email"){
            loginName += " as " +  Viostream.user.EmailAddress;
        }else if(Viostream.User.loginStatus.DisplayFields=="FullName"){
            loginName += " as " +  Viostream.user.FirstName + " " + Viostream.user.LastName;
        }else if(Viostream.User.loginStatus.DisplayFields=="Nothing"){
            //nothing
        }
        //$("#" + Viostream.User.loginStatus.loginNameId).html( (Viostream.UserIsLoggedIn) ? "logged in as " + (Viostream.user.Alias == "" ? Viostream.user.EmailAddress : Viostream.user.Alias) : "not logged in" );
        $("#" + Viostream.User.loginStatus.loginNameId).html( (Viostream.UserIsLoggedIn) ? loginName : "not logged in" );
       
        if(Viostream.UserIsLoggedIn){
            $("#" + Viostream.User.loginStatus.panelId).show();
            $("#" + Viostream.User.Links.loginLink).hide();
            $("#" + Viostream.User.Links.registerLink).hide();
            /*if(typeof(Viostream.Comments) != "undefined")
                Viostream.Comments.ShowControls(true);*/
            
        }else{
            $("#" + Viostream.User.loginStatus.panelId).hide();
            $("#" + Viostream.User.Links.loginLink).show();
            $("#" + Viostream.User.Links.registerLink).show();
            /*if(typeof(Viostream.Comments) != "undefined")
                Viostream.Comments.ShowControls(false);*/
        }
        
    }
    
});

// viostream.user.login.js 
// version: 1.0
// requires:
//      - viostream.user.js

// Logging in

trace("viostream.user.login.js");

if (typeof (Viostream.User) == "undefined") {
    Viostream.User = function(){};
}

jQuery.extend(Viostream.User, {
    login: {
        /// <summary> The login object </summary>
        Init: function(o) {
            Viostream.Extend(this, o);

            // keydown event for password field
            $("#" + this.password).keydown(function(e) {
                if (e.keyCode == 13) {
                    Viostream.user.Login();
                    return false;
                }
            });
        }
    },
    forgotpassword: {
        /// <summary> The login object </summary>
        Init: function(o) {
            Viostream.Extend(this, o);

            // keydown event for email field
            $("#" + this.email).keydown(function(e) {
                if (e.keyCode == 13) {
                    Viostream.ForgotPassword();
                    return false;
                }
            });
        }
    },
    loginStatus: {
        /// <summary> The login object </summary>
        Init: function(o) {
            Viostream.Extend(this, o);
        }
    },
    Links:{
        Init: function(o) {
            Viostream.Extend(this, o);
        }
    }
    
});

jQuery.extend(Viostream.User.prototype,{

    Login : function(email, password) 
    {
        /// <summary> Login a user </summary>
        if (typeof (email) == "undefined") email = $("#" + Viostream.User.login.email).val();
        if (typeof (password) == "undefined") password = $gE(Viostream.User.login.password).value;
        var alertstr = "";
        if (email.length == 0) { alertstr += "please enter your registered email address in order to log in/n"; }
        if (password.length == 0) { alertstr += "please enter your registered password in order to log in"; }
        if (Viostream.key != null)
            password = encryptedString(Viostream.key, password); // encrypt
        if ($gE(Viostream.User.login.rememberMe) && $gE(Viostream.User.login.rememberMe).checked) {
            Viostream.Cookies.Create("ViostreamPortal", "email=" + email + "&password=" + password, 365);
        } else {
            Viostream.Cookies.Erase("ViostreamPortal");
        }

        if (alertstr.length == 0) {
            $.ajax({
                url: Viostream.UserWSUrl + "UserLogin",
                data: { email: email, password: password, sessionId: Viostream.SessionId },
                success: Viostream.user.LoginHandleSuccess
            });
        } else {
            notify("Could not log-in:\n" + alertstr);
        }

    },
    LoginHandleSuccess : function(o) 
    {
        /// <summary> Successful login, update the page </summary>
        if (!Viostream.AjaxObject.DisplayErrors(o, "Login")) {
            var item = $(o).find("Item");
            Viostream.user.PopulateUser(item.find("Id").text(), item.find("FirstName").text(), item.find("LastName").text(), item.find("EmailAddress").text(), item.find("Alias").text());

            if (document.location.href.toLowerCase().indexOf("upload.aspx") != -1) {
                document.location.reload();
            }
        }
    },
    Logout : function() 
    {
        /// <summary> Logs out the current user </summary>
        $.ajax({
            url: Viostream.UserWSUrl + "UserLogOut",
            data: { sessionId: Viostream.SessionId },
            success: Viostream.user.LogoutHandleSuccess
        });
    },

    LogoutHandleSuccess : function(o) 
    {
        /// <summary> Successful logout, update the page </summary>
        if (!Viostream.AjaxObject.DisplayErrors(o, "Logout")) {
            Viostream.user = new Viostream.User();
            Viostream.UserIsLoggedIn = false;
            if (document.location.href.toLowerCase().indexOf("upload.aspx") != -1) {
                document.location.reload();
            }
            Viostream.changeLoginStatus();
        }
    },

    ForgotPassword : function(email) 
    {
        /// <summary> Called to send a reminder to the user's email </summary>
        $.ajax({
            url: Viostream.UserWSUrl + "UserForgotPassword",
            data: { email: email, sessionId: Viostream.SessionId },
            success: Viostream.user.ForgotPasswordHandleSuccess
        });
    },

    ForgotPasswordHandleSuccess : function(o) 
    {
        /// <summary> Successful check for password, update the page </summary>
        if (!Viostream.AjaxObject.DisplayErrors(o, "UserForgotPassword")) {
            notify("An email has been sent to your registered address with a reminder of your password.");
            Viostream.ClosePassword();
        }
    }


});

// viostream.user.registration.js 
// version: 1.0
// requires:
//      - viostream.user.js
//      - viostream.user.login.js

trace("viostream.user.registration.js");

if (typeof (Viostream.User) == "undefined") {
    Viostream.User = function(){};
}

jQuery.extend(Viostream.User, {
    register: {
        /// <summary> The login object </summary>
        Init: function(o) {
            Viostream.Extend(this, o);

            $("input", "#" + this.panelId).keydown(function(e) {
		        if (e.keyCode == 13) {
			        setTimeout(Viostream.User.register.DoRegister, 10);
			        return false;
		        }
	        });
	        $("#" + this.buttonId).click(function() {
		        Viostream.User.register.DoRegister();
		        return false;
	        });
        },
        
        PreValidate : function(){
            /// <summary> Called prior to the validation process - useful if you need to change any hidden inputs </summary>
            $("#regRealState").val($("#regState").val());
        },

        PostValidate : function(o){
            /// <summary>
            /// If you want to do any other error checking or adjustments to what gets passed 
            /// to the register function, overload this and make changes to the object that 
            /// is passed into it.
            /// Must return true for the register function to be called.
            /// </summary>
            return true;
        },
        DoRegister : function(evt){
            /// <summary> Event called when someone presses the enter key in the regiester form </summary>
            var txtRegExp = /^([a-zA-Z-\']+,? ?)+$/;
            var dobRegExp = /^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-)([0-9]){4}$/;
            var emailRegExp = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid        
            var oParams = new Object();
            var alertstr = "";
           
            
            this.PreValidate();
            
            $.each(Viostream.formValidation, function(){
                switch(this.test){
                    case "check":                    
                        var val = $("#" + this.htmlCheck);
                        if(val.length > 0){
                            val = val[0].checked;
                        }else{
                            val = false;
                        }
                        if(this.required && !val){
                            alertstr += this.error + "\n";
                        } else {
                            oParams[this.id] = (typeof(val) == "undefined" ? this.defaultValue || false : val);
                        }
                        break;
                     case "option":
                        var val = $("[name=" + this.GroupName + "]:checked").val();
                        if(typeof(val) == "undefined"){
                            if(this.required)
                                alertstr += this.error + "\n";
                            else
                                oParams[this.id] = this.defaultValue || "";
                        } else {
                            oParams[this.id] = val;
                        }
                        break;
                    case "select":
                        var val = $("#" + this.DropDownListId + " option:selected").val();
                        if(typeof(val) == "undefined"){
                            if(this.required)
                                alertstr += this.error + "\n";
                            else
                                oParams[this.id] = this.defaultValue || "";
                        } else {
                            oParams[this.id] = val;
                        }
                        break;
                    case "string_":
                        var val = $("#" + this.htmlId).val() || "";
                        if(this.required && (val.length == 0)){
                            alertstr += this.error + "\n";
                        } else {
                            oParams[this.id] = (typeof(val) == "undefined" ? this.defaultValue || "" : val);
                        }
                        break;
                    case "text":
                        var val = $("#" + this.htmlId).val();
                        if(this.required && !txtRegExp.test(val) ){
                            alertstr += this.error + "\n";
                        } else {
                            oParams[this.id] = (typeof(val) == "undefined" ? this.defaultValue || "" : val);
                        }
                        break;
                    case "address":
                        var val = $("#" + this.htmlIdAddress1).val();
                        if(this.required && (val.length == 0) ){
                            alertstr += this.error + "\n";
                        } else {
                            oParams[this.id] = (typeof(val) == "undefined" ? this.defaultValue || "" : val);
                            val = $("#" + this.htmlIdAddress2).val();
                            if(typeof(val) != "undefined")
                                oParams[this.id] += " " + val;
                        }
                        break;
                     case "password":
                        var val = $("#" + this.htmlId).val();
                        var val2 = $("#" + this.htmlId2).val();
                        if(this.required && ((val != val2) || (val.length == 0)) ){
                            alertstr += this.error + "\n";
                        } else {
                            oParams[this.id] = (typeof(val) == "undefined" ? this.defaultValue || "" : val); // blank passwords are a bad thing!
                        }
                        break;
                    case "email":
                        var val = $("#" + this.htmlId).val();
                        if(this.required && !emailRegExp.test(val) ){
                            alertstr += this.error + "\n";
                        } else {
                            oParams[this.id] = (typeof(val) == "undefined" ? this.defaultValue || "" : val);
                        }
                        break;
                    case "dob":
                        var sDay = ($gE(this.htmlIdDay) ? $gE(this.htmlIdDay).value : "01");
                        var sMth = ($gE(this.htmlIdMonth) ? $gE(this.htmlIdMonth).value : "01");
                        var sYr = ($gE(this.htmlIdYear) ? $gE(this.htmlIdYear).value : "1901");
                        var datestr = (sYr.length == 0 ? "1901" : sYr)
                              + "-" + (sMth.length == 0 ? "01" : sMth)
                              + "-" + (sDay.length == 0 ? "01" : sDay);
                        trace("datestr = " + datestr)
                        if( this.required && !dobRegExp.test(datestr) ){
                            alertstr += this.error + "\n";
                        } else {
                            var d = new Date();                        
                            d.setISO8601( datestr );
                            oParams[this.id] =  d.getFormatDate();
                            trace("d.getFormatDate(); = " + d.getFormatDate());
                        }
                        break;
                }
                
                
                
            });
           
            if(alertstr.length == 0){
                if( Viostream.User.register.PostValidate(oParams) )
                    Viostream.user.Register(oParams);
            }
            else{
                alert("Please check the following fields\n" + alertstr);
            }

        }
        
    }
    

    
    
});

jQuery.extend(Viostream.User.prototype,{
    Register : function(oParams)
    {
        /// <summary> Called to register a new user </summary>    
        for(var a in oParams)
        {
            if(a.substring(0,1) == "_")
                delete oParams[a];
        }
        oParams["sessionId"] = Viostream.SessionId;
        
        var emailAddress = oParams["emailAddress"];
        var password = oParams["password"];
        
        if(Viostream.key != null)
        {
            oParams["password"] = encryptedString(Viostream.key, password); // encrypt
        }
        
        var regParams = {"parameters":[]};
        
        for(var a in oParams){
            regParams["parameters"].push({"question":a,"answer":oParams[a]});
        }
        regParams = $.toJSON(regParams);
        $.ajax(
        {
            url : Viostream.UserWSUrl + "UserRegisterParams",
            success : function(oXML){ Viostream.user.RegisterHandleSuccess(oXML, emailAddress, password); },
            data : { JSONData : regParams }
        });

    },
    RegisterHandleSuccess : function(o, emailAddress, password)
    {
        if(!Viostream.AjaxObject.DisplayErrors(o,"Registration")){
            Viostream.CloseRegistration();
            if(!Viostream.UserActivation)
            {
                notify("Congratulations - you have successfully registered.");
                Viostream.user.Login(emailAddress, password);
            }
            else
            {
                notify("Congratulations - you have successfully registered. An email has been sent to your registered email address. Follow the link in the email to confirm your email address and activate your account.");
            }
            return true;
        }else{
            return false;
        }
    }
});


//Viostream.User.prototype.Register = function(oParams)
//{
//    /// <summary> Called to register a new user </summary>    
//    for(var a in oParams)
//    {
//        if(a.substring(0,1) == "_")
//            delete oParams[a];
//    }
//    oParams["sessionId"] = Viostream.SessionId;
//    
//    var emailAddress = oParams["emailAddress"];
//    var password = oParams["password"];
//    
//    if(Viostream.key != null)
//    {
//        oParams["password"] = encryptedString(Viostream.key, password); // encrypt
//    }
//    
//    var regParams = {"parameters":[]};
//    
//    for(var a in oParams){
//        regParams["parameters"].push({"question":a,"answer":oParams[a]});
//    }
//    regParams = $.toJSON(regParams);
//    $.ajax(
//    {
//        url : Viostream.UserWSUrl + "UserRegisterParams",
//        success : function(oXML){ Viostream.user.RegisterHandleSuccess(oXML, emailAddress, password); },
//        data : { JSONData : regParams }
//    });

//};
//    
//Viostream.User.prototype.RegisterHandleSuccess = function(o, emailAddress, password)
//{
//    if(!Viostream.AjaxObject.DisplayErrors(o,"Registration")){
//            Viostream.CloseRegistration();
//            if(!Viostream.UserActivation)
//            {
//                notify("Congratulations - you have successfully registered.");
//                Viostream.user.Login(emailAddress, password);
//            }
//            else
//            {
//                notify("Congratulations - you have successfully registered. An email has been sent to your registered email address. Follow the link in the email to confirm your email address and activate your account.");
//            }
//            return true;
//    }else{
//        return false;
//    }
//};





/* HELPER FUNCTIONS */

trace("viostream.utils.js");

/*
http://www.JSON.org/json_parse.js
2009-05-31

Public Domain.

NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

This file creates a json_parse function.

json_parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = json_parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

This is a reference implementation. You are free to copy, modify, or
redistribute.

This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/

/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,
hasOwnProperty, message, n, name, push, r, t, text
*/

var json_parse = (function() {

    // This is a function that can parse a JSON text, producing a JavaScript
    // data structure. It is a simple, recursive descent parser. It does not use
    // eval or regular expressions, so it can be used as a model for implementing
    // a JSON parser in other languages.

    // We are defining the function inside of another function to avoid creating
    // global variables.

    var at,     // The index of the current character
        ch,     // The current character
        escapee = {
            '"': '"',
            '\\': '\\',
            '/': '/',
            b: '\b',
            f: '\f',
            n: '\n',
            r: '\r',
            t: '\t'
        },
        text,

        error = function(m) {

            // Call error when something is wrong.

            throw {
                name: 'SyntaxError',
                message: m,
                at: at,
                text: text
            };
        },

        next = function(c) {

            // If a c parameter is provided, verify that it matches the current character.

            if (c && c !== ch) {
                error("Expected '" + c + "' instead of '" + ch + "'");
            }

            // Get the next character. When there are no more characters,
            // return the empty string.

            ch = text.charAt(at);
            at += 1;
            return ch;
        },

        number = function() {

            // Parse a number value.

            var number,
                string = '';

            if (ch === '-') {
                string = '-';
                next('-');
            }
            while (ch >= '0' && ch <= '9') {
                string += ch;
                next();
            }
            if (ch === '.') {
                string += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    string += ch;
                }
            }
            if (ch === 'e' || ch === 'E') {
                string += ch;
                next();
                if (ch === '-' || ch === '+') {
                    string += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    string += ch;
                    next();
                }
            }
            number = +string;
            if (isNaN(number)) {
                error("Bad number");
            } else {
                return number;
            }
        },

        string = function() {

            // Parse a string value.

            var hex,
                i,
                string = '',
                uffff;

            // When parsing for string values, we must look for " and \ characters.

            if (ch === '"') {
                while (next()) {
                    if (ch === '"') {
                        next();
                        return string;
                    } else if (ch === '\\') {
                        next();
                        if (ch === 'u') {
                            uffff = 0;
                            for (i = 0; i < 4; i += 1) {
                                hex = parseInt(next(), 16);
                                if (!isFinite(hex)) {
                                    break;
                                }
                                uffff = uffff * 16 + hex;
                            }
                            string += String.fromCharCode(uffff);
                        } else if (typeof escapee[ch] === 'string') {
                            string += escapee[ch];
                        } else {
                            break;
                        }
                    } else {
                        string += ch;
                    }
                }
            }
            error("Bad string");
        },

        white = function() {

            // Skip whitespace.

            while (ch && ch <= ' ') {
                next();
            }
        },

        word = function() {

            // true, false, or null.

            switch (ch) {
                case 't':
                    next('t');
                    next('r');
                    next('u');
                    next('e');
                    return true;
                case 'f':
                    next('f');
                    next('a');
                    next('l');
                    next('s');
                    next('e');
                    return false;
                case 'n':
                    next('n');
                    next('u');
                    next('l');
                    next('l');
                    return null;
            }
            error("Unexpected '" + ch + "'");
        },

        value,  // Place holder for the value function.

        array = function() {

            // Parse an array value.

            var array = [];

            if (ch === '[') {
                next('[');
                white();
                if (ch === ']') {
                    next(']');
                    return array;   // empty array
                }
                while (ch) {
                    array.push(value());
                    white();
                    if (ch === ']') {
                        next(']');
                        return array;
                    }
                    next(',');
                    white();
                }
            }
            error("Bad array");
        },

        object = function() {

            // Parse an object value.

            var key,
                object = {};

            if (ch === '{') {
                next('{');
                white();
                if (ch === '}') {
                    next('}');
                    return object;   // empty object
                }
                while (ch) {
                    key = string();
                    white();
                    next(':');
                    if (Object.hasOwnProperty.call(object, key)) {
                        error('Duplicate key "' + key + '"');
                    }
                    object[key] = value();
                    white();
                    if (ch === '}') {
                        next('}');
                        return object;
                    }
                    next(',');
                    white();
                }
            }
            error("Bad object");
        };

    value = function() {

        // Parse a JSON value. It could be an object, an array, a string, a number,
        // or a word.

        white();
        switch (ch) {
            case '{':
                return object();
            case '[':
                return array();
            case '"':
                return string();
            case '-':
                return number();
            default:
                return ch >= '0' && ch <= '9' ? number() : word();
        }
    };

    // Return the json_parse function. It will have access to all of the above
    // functions and variables.

    return function(source, reviver) {
        var result;

        text = source;
        at = 0;
        ch = ' ';
        result = value();
        white();
        if (ch) {
            error("Syntax error");
        }

        // If there is a reviver function, we recursively walk the new structure,
        // passing each name/value pair to the reviver function for possible
        // transformation, starting with a temporary root object that holds the result
        // in an empty key. If there is not a reviver function, we simply return the
        // result.

        return typeof reviver === 'function' ? (function walk(holder, key) {
            var k, v, value = holder[key];
            if (value && typeof value === 'object') {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = walk(value, k);
                        if (v !== undefined) {
                            value[k] = v;
                        } else {
                            delete value[k];
                        }
                    }
                }
            }
            return reviver.call(holder, key, value);
        } ({ '': result }, '')) : result;
    };
} ());
// viostream.videoinfo.js 
// version: 5.0
// requires:
//      - viostream.js

trace("viostream.videoinfo.js");

if(typeof(Viostream) == "undefined"){
    Viostream = { };
}

if (typeof (Viostream.VideoInfo) == "undefined") {
    Viostream.VideoInfo = { };
}


Viostream.Extend(Viostream.VideoInfo, {
    Init: function(o) {
        Viostream.Extend(this, o);

        if (!$("#" + this.PanelId).data("isbound")) {
            $("#" + this.PanelId).bind("MediaChanged", this.MediaChangedCallback);
            $("#" + this.PanelId).bind("AddToPlayList", this.AddToPlayListCallback);
            $("#" + this.PanelId).data("isbound", true);
            trace("VideoInfo.PanelId.eventBinding");
        }
        trace("VideoInfo.Init");

    },
    AddToPlayListCallback: function(e, mb) {
        //trace("Viostream.VideoInfo.AddToPlayList");
        $(this).show();
       // Viostream.showLittleLoader("#" + Viostream.VideoInfo.Thumbnail);
    },
    MediaChangedCallback: function(e, mb) {

        trace('Viostream.VideoInfo.MediaChanged()');

        $("#" + Viostream.VideoInfo.Title).html(mb.MediaTitle);
        $("#" + Viostream.VideoInfo.Description).html(mb.MediaDescription);
        $("#" + Viostream.VideoInfo.DateAdded).html(mb.Created);
        $("#" + Viostream.VideoInfo.Views).html(mb.ViewCount);
        $("#" + Viostream.VideoInfo.Duration).html(Viostream.parseDuration(mb.Duration));
        $("#" + Viostream.VideoInfo.Thumbnail).attr("src", mb.ThumbnailURL);
        $("#" + Viostream.VideoInfo.Thumbnail).removeClass("vs-loading");
       
        if (typeof (Viostream.RateThis) == "function") {
        	var averageVote = (mb.AverageVotes == null || mb.AverageVotes == "") ? 0 : mb.AverageVotes;
		    Viostream.RateThis(averageVote);
        }

        if (typeof (mb.AuthorName) != undefined) {
            $("#" + Viostream.VideoInfo.Author).html(mb.Source);
        }

        return this;
    }

});


    
