// viostream.mediabase.js 
// version: 1.0
// requires:
//      - viostream.js
//      - viostream.playlist.js

Viostream.MediaBase = function(oXML){
    ///Prop
    this.MediaId = "";
    this.MediaType = "";
    this.Created = "";
    this.Url = "";
    this.MediaTitle = "";
    this.MediaDescription = "";
    this.Duration = "";
    this.ThumbnailURL = "";
    this.rating = 0;
    this.Album = new Array();
    this.Keywords = new Array();        
    
    ///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.ThumbnailURL = Viostream.GetThumbnailData(itemXML, Viostream.targetThumbNailWidth, Viostream.targetThumbNailHeight);
            
            this.AverageVotes = parseFloat($xml.find("AverageVotes").text());
            this.rating = Math.round(this.AverageVotes*2);
            
            var mediaLength = parseInt($xml.find("MediaLength").text());
            
            var round = function(num, dec) { return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); }
            
            if (mediaLength > 0)
            {
                if (mediaLength < 60000) // measured in seconds
                {
                    this.Duration = Math.round(mediaLength / 1000) + " secs.";
                }
                else if (mb.MediaLength < 3600000) // measured in minutes
                {
                    var roundedTime = round(mediaLength / 60000, 2);
                    this.Duration = roundedTime + " mins.";
                }
                else // we have hours!
                {
                    var roundedTime = round(mediaLength / 3600000, 2);
                    this.Duration = roundedTime + " hours";
                }
            }else{
                this.Duration = "";
            }
            
            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.redrawMedia = function(responseXML, wrapper){

    var mediaBaseElements = $(responseXML).find("MediaBase");
        
    ///Clear all existing elements in the container item
    $(wrapper).empty();
       
    ///Loop each media base item xml data
    mediaBaseElements.each(function(){
        var mb = new Viostream.MediaBase(this);
        mb.Draw(wrapper);
    });
    
    return mediaBaseElements.length;
};

Viostream.MediaBase.prototype.AddToPlayList = function(evt, PlayNow){
    /// <summary> 
    /// Adds this media item to the current playlist. If there is
    /// no playlist, it will create one and then add the item to it.
    /// </summary>
    try
    {
        if(typeof(evt) == "undefined")
            var mb = this;
        else
            var mb = evt.data.mb;
        
        if(typeof(PlayNow) == "undefined") PlayNow = false;
        
        Viostream.PlayList.ClientSidePlaylist[mb.MediaId] = mb;
        var txtPlayListId   = ($gE("txtPlayListId") == null) ? document.forms[0].eval("txtPlayListId") : $gE("txtPlayListId");
        //var portalId        = ($gE("PortalId") == null) ? document.forms[0].eval("PortalId").value : $gE("PortalId").value;
        var portalId = Viostream.PortalId;
        
        var playListId = txtPlayListId.value;
        
        //no current playlist
        if(playListId.length == 0)
        {
            ///Create a new playlist
            Viostream.PlayList.Create(portalId, mb.MediaId, txtPlayListId, PlayNow);
        }else{
            //add mediId GUID to playlist
            Viostream.PlayList.AddMedia(txtPlayListId.value, mb.MediaId, PlayNow);
        }
        
        var plWrapper = $gE("ulMediaPlaylistWrapper");
        if(plWrapper){
            mb.Draw(plWrapper, true);
        }
        
    }
    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;
        
        mb.AddToPlayList(evt, true);

//        Viostream.PlayList.ClientSidePlaylist[mb.MediaId] = mb;
//        
//        updateMedia(mb.Url,"mediaURL");
//        //update currently playing
//        currentlyPlaying(mb.MediaTitle, 0, mb.MediaDescription, mb.Created, mb.MediaId, mb.AverageVotes)
    }
    catch(e)
    {
        notify("PlayNow(playGUID) " + e.message, true);
    }
};


Viostream.MediaBase.prototype.Draw = function(wrapper) {
    /// <summary> Builds a media item on the screen </summary>
    var mb = this;
    try {

        var oFrag = Viostream.Templates.MediaItem.cloneNode(true);
        var $Frag = $(oFrag.childNodes);

        $Frag.find(".video-card").addClass(this.MediaType);

        mb.MediaDescription = (mb.MediaDescription != null) ? mb.MediaDescription : "";
        var descId = "desc_" + Math.floor((Math.random() * Math.random() * 100));
        
        $Frag.find(".video-description")
            .each(function() { this.id = descId; })
            .html(mb.MediaDescription);

        $Frag.find(".video-title-text")
            .bind("click", { mb: this }, this.PlayNow)
            .mouseover(function() { window.status = ""; return false; })
            .each(function() { this.rel = "#" + descId; this.title = mb.MediaTitle; })
            .html(mb.MediaTitle);


        $Frag.find(".video-thumb")
                .width(Viostream.targetThumbNailWidth)
                .height(Viostream.targetThumbNailHeight)
                .attr("src", mb.ThumbnailURL);

        $Frag.find(".video-date").html(mb.Created);
        $Frag.find(".video-duration").html(mb.Duration);


        if (Viostream.UseShadowBox && mb.MediaType == "Album") {
            var oPlaylistAdd = $Frag.find(".playlist-add, .play-now").bind("click", { mb: this }, function(e) {
                var _mb = e.data.mb;
                Shadowbox.open({
                    title: _mb.MediaTitle,
                    type: 'img',
                    content: _mb.Album[0].Url,
                    gallery: _mb.MediaId
                });
                return false;
            });

            for (var i = 1; i < this.Album.length; i++) {
                var imglink = $cE("a");
                imglink.className = "sboxGall";
                imglink.href = this.Album[i].Url;
                imglink.innerHTML = "piclink"
                imglink.title = this.Album[i].Title + " : " + this.Album[i].Description;
                imglink.alt = this.Album[i].Description;
                imglink.rel = 'shadowbox[' + this.MediaId + ']';
                oPlaylistAdd.append(imglink);
            }
            if (this.Album.length > 1) {
                Shadowbox.setup(oPlaylistAdd.find("a.sboxGall"), { gallery: this.MediaId });
            }

        } else {
            $Frag.find(".playlist-add").bind("click", { mb: this }, this.AddToPlayList);
            $Frag.find(".play-now").bind("click", { mb: this }, this.PlayNow);
        }
        $Frag[0].mediaId = this.MediaId;
        wrapper.appendChild(oFrag);
    }
    catch (e) {
        notify("BuildMediaItemElement(mb) " + e.message, true);
    }
};

