/**
 *******************************************
 * $Id: videoCollection.js 242 2007-10-17 01:14:26Z gregbrown $
 * REVVER
 * Copyright 2006 REVVER, Inc.
 *
 * Author: Greg Brown, greg@onfocus.net
 * 
 * Description:
 *  The video collection is the main
 *  object that is used to draw thumbnails
 *  and show the videos to the users.
 *******************************************
 */

/**
 *  We need an array to contain a reference to all the divs
 *  that we have on the page that are videoCollections
 *  This array is used so we can correctly process data
 *  that is returned from a call to the revver webservice.
 */
REVVER.widget.videoCollections = [];
REVVER.widget.videoIntervals = []; //hack for IE

/**
 *  The next var is the default values styles, search 
 *  criteria, etc. for the videoCollection widget.
 */
REVVER.widget.videoCollectionDefaults = {
    "display" : {
        "rows": 3,
        "cols": 1,
        "title": "Revver Videos",
        "searchText": "customize",
        "noResultsMsg": "No videos match your search criteria.",
        "styleRules": {
            // Style for the containing div
            "video-collection" : [{ "border" : "1px solid #ccc", "padding" : "5px 10px 0px 10px", "background-color" : "#fff" }],
            // Style for title at top of thumb strip
            "video-collection-title" : [{ "color": "#000", "font-family" : "tahoma", "font-size" : "19px", "margin" : "0px", "padding" : "0px", "text-align" : "center" }],
            // Style for td that contains the logo
            "logo-area" : [{ }],
            // Style for the div that contains all components in a thumbnail (title, image, other text)
            "thumb-div" : [{ "background-color" : "#fff", "margin" : "5px", "border-right": "1px solid #ccc", "border-bottom" : "1px solid #ccc", "padding" : "5px 10px 10px 10px" }],
            // Style for the thumbnail image itself
            "thumb-img" : [{ "border": "1px solid #fff", "margin" : "0px", "padding" : "0px" }],
            // Style for all text in a thumbnail except the title
            "thumb-text" : [{ "display" : "none" }],
            // Style for the thumbnail title
            "thumb-title" : [{ "color": "#666", "font-family" : "tahoma", "font-size" : "13px", "margin" : "0px 0px 5px 0px", "padding" : "0px" }],
            // Style for the "customize" link
            "customize-link" : [{ "color": "#02A0C3", "font-family" : "tahoma", "font-size" : "11px", "margin" : "0px", "padding" : "2px" }],
            // Style for the count line, eg. '1-3 of 2350'
            "count-text" : [{ "font-family" : "tahoma", "font-size" : "11px", "margin-top" : "0px", "text-align" : "center" }],
            // styles the revver logo
            "logo-image" : [{ "border" : "none" }],
            // styles the rss link
            "rss-image" : [{ "margin-right" : "10px", "border" : "none" }],
            // Style for lightbox title
            "lb-title" : [{ "font-family" : "tahoma", "font-size" : "19px", "text-align" : "left"}],
            // Style for lightbox close icon and possible text ( a span)
            "lb-close" : [{ "font-family" : "tahoma", "font-size" : "11px" }],
            // Style for normal lightbox text
            "lb-text" : [{ "font-family" : "tahoma", "font-size" : "13px", "margin-top" : "0px", "line-height" : "15px", "text-align" : "left" }],
            // Style for owner name in lightbox
            "lb-owner" : [{ "font-family" : "tahoma", "font-size" : "13px", "color" : "#ff3300" }],
            // Style for keyword list in lightbox
            "lb-keywords" : [{ "font-family" : "tahoma", "font-size" : "13px", "color" : "#00A0C8" }],
            // Style for the description of the movie in the lightbox
            "lb-description" : [{ "font-family" : "tahoma", "font-size" : "13px", "line-height" : "15px", "text-align" : "left" }],
            // Style for error messages
            "err-msg" : [{ "font-family" : "tahoma", "font-size" : "11px", "color": "red" }],                        
            // Customize-box styles
            "revver-searchBox-form" : [{ "font-family" : "tahoma", "font-size" : "13px"  }],
            "revver-searchBox-Label" : [{ "color": "#333", "font-family" : "tahoma", "font-size" : "17px" }],
            "searchBoxField" : [{ "font-family" : "tahoma", "font-size" : "13px", "padding" : "2px"  }],
            "radio-button" : [{  }],
            "searchBoxBtn" : [{ "font-size" : "11px", "width": "80px" }],
            "revver-searchBox-optionLabel" : [{ "font-family" : "tahoma", "font-size" : "13px" }],
            // Styles for the navigation arrow TD's
            "up-arrow-cell" : [{ "cursor": "pointer", "vertical-align" : "middle" }],
            "down-arrow-cell" : [{ "cursor": "pointer", "vertical-align" : "middle" }],
            "fwd-arrow-cell" : [{ "cursor": "pointer", "vertical-align" : "middle" }],
            "back-arrow-cell" : [{ "cursor": "pointer", "vertical-align" : "middle" }],
            // Style for disabled next/prev images
            "nextPrev-disabled" : [{ "-moz-opacity": "0.4", "cursor": "default" }]
        },
        "backarrow": REVVER.jsApiURL + "widget/back.gif",
        "fwdarrow": REVVER.jsApiURL + "widget/forward.gif",
        "uparrow": REVVER.jsApiURL + "widget/up.gif",
        "downarrow": REVVER.jsApiURL + "widget/down.gif",
        "logo": REVVER.jsApiURL + "widget/revver.gif",
        "logoLink": "http://www.revver.com/",
        "biglogo": REVVER.jsApiURL + "widget/revver-big.gif",
        "rsslogo": REVVER.jsApiURL + "widget/rss.gif",
        "closebutton": REVVER.jsApiURL + "widget/close.gif",
        "thumbWidth": 120,
        "thumbHeight": 90,
        "thumbTitleMaxLen": 16
    }
};

// define the class for the VideoCollection object
REVVER.widget.VideoCollection = Class.create();
REVVER.widget.VideoCollection.prototype = {

    // this method is called automatically when you say new VideoCollection()
    initialize:function(initParams)
    {
        // first we need to write a div and give it an id.
        var divId = "revverVC" + (new Date()).getTime() + Math.floor(Math.random()*20000);
        document.write('<table border="0" align="center"><tr><td><div id="' + divId + '" class="video-collection"></div></td></tr></table>');
        var element = $(divId);

        /**
         *  the callBack is very important.  this function must be able to 
         *  find the correct object to call with the json object.  the function
         *  itself should accept two parameters, json and elementId.
         *  the callBack will call the array item named array[elementId].processData
         */
        REVVER.widget.videoCollections[element.id] = this;

        this.methodName = "open.video.find";
        this.callBack = "REVVER.widget.videoCollections['" + element.id + "'].processData";
        this.elementId = element.id || null; // an elementId is required
        this.mainDiv = element; // the main HTML container (probably a div)
        this.json = initParams; // The JSON data containing the query and other params

        this.vidArray = [];     // starts out blank
        this.count = true;      // we always want the count back
        this.resultsCount = 0;  // starts out as 0 -- no request has been made yet
        this.rawParams = "";
        
        // setup the display and criteria from the defaults if it's not passed in.
        this.json.display =  this.json.display || REVVER.widget.videoCollectionDefaults.display;
        this.json.criteria =  this.json.criteria || {};

        // Set up some convenience values
        this.rows = this.json.display.rows || REVVER.widget.videoCollectionDefaults.display.rows;
        this.cols = this.json.display.cols || REVVER.widget.videoCollectionDefaults.display.cols;
        this.orientation = "vertical";
        if (this.rows <= this.cols) {
            this.orientation = "horizontal";
        }
        
        this.limit = this.rows * this.cols; // number of items to bring back in a gulp
        this.currOffset = 0; // Current offset for prev/next buttons

        // reset the customize style if we're using a collection
        // we cannot allow searching/sorting if a collection is being used
        if ( this.json.collection ) {
            // use the default styles if we don't have any passed in
            this.styles = this.json.display.styleRules || REVVER.widget.videoCollectionDefaults.display.styleRules;
            this.styles["customize-link"] = [{ "display" : "none" }];
        } else {
            // use the default styles if we don't have any passed in
            this.styles = this.json.display.styleRules || REVVER.widget.videoCollectionDefaults.display.styleRules;
        }
        
        // make sure we have a style set for each element
        var availableStyles = ['video-collection','video-collection-title','logo-area','thumb-div','thumb-img','thumb-text','thumb-title','customize-link','count-text','logo-image','rss-image','lb-title','lb-close','lb-text','lb-owner','lb-keywords','lb-description','err-msg','revver-searchBox-form','revver-searchBox-Label','searchBoxField','radio-button','searchBoxBtn','revver-searchBox-optionLabel','up-arrow-cell','down-arrow-cell','fwd-arrow-cell','back-arrow-cell','nextPrev-disabled'];
        for (var i=0; i<availableStyles.length;i++) {
            try {
                this.json.display.styleRules[availableStyles[i]] = this.json.display.styleRules[availableStyles[i]] || REVVER.widget.videoCollectionDefaults.display.styleRules[availableStyles[i]];
            }
            catch (e) {
            }
        }
        
        // now create the style manager with the final set of styles
        this.styleManager = new REVVER.util.StyleManager(this.styles);

        // set the default images if no images are passed in
        this.backarrow = this.json.display.backarrow || REVVER.widget.videoCollectionDefaults.display.backarrow;
        this.fwdarrow = this.json.display.fwdarrow || REVVER.widget.videoCollectionDefaults.display.fwdarrow;
        this.uparrow = this.json.display.uparrow || REVVER.widget.videoCollectionDefaults.display.uparrow;
        this.downarrow = this.json.display.downarrow || REVVER.widget.videoCollectionDefaults.display.downarrow;
        this.logo = this.json.display.logo || REVVER.widget.videoCollectionDefaults.display.logo;
        this.logoLink = this.json.display.logoLink || REVVER.widget.videoCollectionDefaults.display.logoLink;
        this.bigLogo = this.json.display.biglogo || REVVER.widget.videoCollectionDefaults.display.biglogo;
        this.rssLogo = this.json.display.rsslogo || REVVER.widget.videoCollectionDefaults.display.rsslogo;
        this.closeButton = this.json.display.closebutton || REVVER.widget.videoCollectionDefaults.display.closebutton;

        // set the title of the widget
        this.json.display.title = this.json.display.title || REVVER.widget.videoCollectionDefaults.display.title;
        
        // set the search text of the widget
        this.json.display.searchText = this.json.display.searchText || REVVER.widget.videoCollectionDefaults.display.searchText;

        // set the no results message.  this shows when the api call results on no videos found.
        this.json.display.noResultsMsg = this.json.display.noResultsMsg || REVVER.widget.videoCollectionDefaults.display.noResultsMsg;
        
        // setup the width of the thumbnails and the arrow controls
        this.thumbWidth = this.json.display.thumbWidth || REVVER.widget.videoCollectionDefaults.display.thumbWidth;
        this.thumbHeight = this.json.display.thumbHeight || REVVER.widget.videoCollectionDefaults.display.thumbHeight;
        this.thumbTitleMaxLen = this.json.display.thumbTitleMaxLen || REVVER.widget.videoCollectionDefaults.display.thumbTitleMaxLen;
        this.upDownButtonWidth = this.json.display.upDownButtonWidth || false;
        this.upDownButtonHeight = this.json.display.upDownButtonHeight || false;
        this.lrButtonWidth = this.json.display.lrButtonWidth || false;
        this.lrButtonHeight = this.json.display.lrButtonHeight || false;
        
        // this.verbosity will now be represented as an array of strings called returnFields
        // in addition to the fields we are also passing in some advanced options on the 'thumbnailUrl'
        // field so we can have revver resize the thumbnails per the params pushed into this widget.
        this.verbosity = ['id','title','owner','author','status','ageRestriction','publicationDate','modifiedDate','url','quicktimeMediaUrl','description','keywords','duration','size','credits','views','affiliateId'];
        this.verbosity[this.verbosity.length] = ['thumbnailUrl', {'width' : parseInt(this.thumbWidth), 'height' : parseInt(this.thumbHeight)}];
        
        // set the criteria and collection params
        this.setCriteria(this.json.criteria, false);
        this.setCollection(this.json.collection, false);

        // establish an array for the thumnail objects
        this.thumbs = [];   // Collection of individual thumbnail objects I contain

        // we have to make a request right away to fill the element with data
        this.requestData();
        
        return this;
    },
    
    setCriteria:function(criteria) {
        this.json.criteria = criteria;
        if ( criteria ) {
            this.methodName = "open.video.find";
            if (criteria.minAgeRestriction) {
                this.minAgeRestriction = criteria.minAgeRestriction;
            }
            this.json.query = [ criteria, this.verbosity, { "offset": 0, "limit": this.limit, "count": this.count, "affiliate": this.json.affiliate } ];

            // redo the request if we have a second argument and its value is true
            if (arguments[1]) this.requestData();
        }
    },
    
    setCollection:function(collection) {
        this.json.collection = collection;
        if ( collection ) {
            this.methodName = "open.collection.collect";
            this.json.query = [ this.json.collection, this.verbosity, { "offset": 0, "limit": this.limit, "count": this.count, "affiliate": this.json.affiliate } ];
            this.styleManager.setStyleSelectorValue("customize-link", "display", "none");
            
            try {
                if ( this.isHorizontal() ) {
                    if (!this.json.display.styleRules["rss-image"]) {
                        this.styleManager.setStyleSelectorValue("rss-image", "display", "block");
                        this.styleManager.setStyleSelectorValue("rss-image", "margin-right", "10px");
                        this.styleManager.setStyleSelectorValue("rss-image", "border", "none");
                    }
                } else {
                    if (!this.json.display.styleRules["rss-image"]) {
                        this.styleManager.setStyleSelectorValue("rss-image", "display", "block");
                        this.styleManager.setStyleSelectorValue("rss-image", "margin-right", "5px");
                        this.styleManager.setStyleSelectorValue("rss-image", "border", "none");
                    }
                }
            }
            catch (e) {
            }
        } else {
            this.styleManager.setStyleSelectorValue("rss-image", "display", "none");
            this.json.query = [ this.json.criteria, this.verbosity, { "offset": 0, "limit": this.limit, "count": this.count, "affiliate": this.json.affiliate } ];
        }
        // redo the request if we have a second argument and its value is true
        if (arguments[1]) this.requestData();
    },
    
    getCollectionRssLink:function() {
        var affiliate = "";
        if (this.json.affiliate) affiliate = "?affiliate=" + this.json.affiliate;
        return "http://feeds.revver.com/2.0/mrss/flash/collection/" + this.json.collection + affiliate;
    },
    
    isUsingCollection:function() {
        if ( this.json.collection ) return true;
        return false;
    },
    
    setRows:function(rows) {
        this.rows = rows;
        if (this.rows <= this.cols) {
            this.orientation = "horizontal";
        } else {
            this.orientation = "vertical";
        }
        this.limit = this.rows * this.cols; // number of items to bring back in a gulp
        this.currOffset = 0; // Current offset for prev/next buttons
    },
    
    setCols:function(cols) {
        this.cols = cols;
        if (this.rows <= this.cols) {
            this.orientation = "horizontal";
        } else {
            this.orientation = "vertical";
        }
        this.limit = this.rows * this.cols; // number of items to bring back in a gulp
        this.currOffset = 0; // Current offset for prev/next buttons
    },
    
    isHorizontal:function() {
        if ( this.orientation == "horizontal" ) return true;
        return false;
    },
    
    emptyOuterDiv:function()
    {
        // Clear out any previous contents of main container
        var thisID = "";
        thisID = "mainTable-" + this.elementId;
        var elem = $(thisID);
        if (elem)
            elem.parentNode.removeChild(elem);
    },

    createOuterContainer:function()
    {
        // Create a table to wrap everything in the div.
        this.outerTable = this.createTag(this.mainDiv, "table", "mainTable", null);
        //this.outerTable.setAttribute("border", "1");
        
        this.outerTbody = this.createTag(this.outerTable, "tbody", "mainTbody", null);
        
        // Create a row at the top to display title
        this.headerRow = this.createTag(this.outerTbody, "tr", "titleRow", "video-collection-title");
        this.titleCell = this.createTag(this.headerRow, "td", "titleCell", "video-collection-title");
        var title = document.createTextNode(this.json.display.title);
        this.titleCell.appendChild(title); 

        this.contentsRow = this.createTag(this.outerTbody, "tr", "contentsRow", null);
        this.contentsCell = this.createTag(this.contentsRow, "td", "contentsCell", null); 
        this.contentsCell.setAttribute("align", "center");

        // Make a table to contain all the contents
        this.contentTable = this.createTag(this.contentsCell, "table", "contentTable", null);        
        this.contentTbody = this.createTag(this.contentTable, "tbody", "contentTbody", null);
        
        // Create a new row at bottom to contain the logos etc.
        this.bottomRow = this.createTag(this.outerTbody, "tr", "bottomRow", null);
        this.bottomCell = this.createTag(this.bottomRow, "td", "bottomCell", null);
        // Make a table to contain bottom row information
        this.bottomTable = this.createTag(this.bottomCell, "table", "bottomTable", null);      
        this.bottomTable.setAttribute("width", "100%");
          
        this.bottomTbody = this.createTag(this.bottomTable, "tbody", "bottomTbody", null);
        
    },
    
    createBottomLine:function()
    {
        // Vertical and horizontal orientation have different bottom layouts
        if (this.orientation == "vertical") {
            // Vertical: 2 rows of 2 columns
            this.bottomRow_1 = this.createTag(this.bottomTbody, "tr", "bottomRow1", null);
            
            this.bottomCellLeft1 = this.createTag(this.bottomRow_1, "td", "bottomCellLeft1", "count-text");
            this.bottomCellLeft1.setAttribute("align", "center");
            this.bottomCellLeft1.setAttribute("colSpan", 2);
            var countText = document.createTextNode(this.makeCountLine());
            this.bottomCellLeft1.appendChild(countText);
          
            this.bottomCellRight1 = this.createTag(this.bottomRow_1, "td", "bottomCellRight1", null);
            this.bottomCellRight1.setAttribute("align", "right");            
            var anch = this.createTag (this.bottomCellRight1, "a", "custA", "customize-link");
            anch.setAttribute("href", "#");
            anch.setAttribute("rel", "lightbox");
            anch.setAttribute("render", "REVVER.widget.videoCollections['" + this.elementId + "'].renderForm()");
            
            var anchText = document.createTextNode(this.json.display.searchText);
            anch.appendChild(anchText);
            
            this.bottomRow_2 = this.createTag(this.bottomTbody, "tr", "bottomRow2", null);
            this.bottomCellLeft2 = this.createTag(this.bottomRow_2, "td", "bottomCellLeft2", null);
            this.bottomCellLeft2.setAttribute("align", "left");      
            
            var iconCell = this.createTag(this.bottomCellLeft2, "td", "revverLogoTd", null);
        	var logoLink = this.createTag(iconCell, "a", "revverLogoLink", null);
        	logoLink.setAttribute('href',this.logoLink);
        	logoLink.setAttribute('target','_blank');
        	logoLink.setAttribute('title',this.logoLink);
            var logo = this.createTag (logoLink, "img", "revverLogoImg", "logo-image");
            logo.setAttribute("src", this.logo);
            
            var rssCell = this.createTag(this.bottomRow_2, "td", "bottomCellRight2", null);
            rssCell.setAttribute("align", "right");
        	var rssLink = this.createTag(rssCell, "a", "revverRssLink", null);
        	rssLink.setAttribute('href', this.getCollectionRssLink());
        	rssLink.setAttribute('target', '_blank');

            var rss = this.createTag (rssLink, "img", "rssLogo", "rss-image");
            rss.setAttribute("src", this.rssLogo);

        }
        else {
            // Horizontal: One row of 5 cols. The outer 2 cols are spacers for alignment
            this.bottomRow_1 = this.createTag(this.bottomTbody, "tr", "bottomRow1", null);
            
            this.bottomCell1 = this.createTag(this.bottomRow_1, "td", "bottomCell1", null);
            this.bottomCell1.setAttribute("width", this.lrButtonWidth);
            var clear = this.createTag (this.bottomCell1, "img", "clear1", null);
            clear.setAttribute("src", REVVER.jsApiURL + "clear.gif");
            clear.setAttribute("width", this.lrButtonWidth);
            
            this.bottomCell2 = this.createTag(this.bottomRow_1, "td", "bottomCell2", null);
            this.bottomCell2.setAttribute("align", "left");
            this.bottomCell2.setAttribute("width", "20%");

        	var logoLink = this.createTag(this.bottomCell2, "a", "logoLink", null);
        	logoLink.setAttribute('href',this.logoLink);
        	logoLink.setAttribute('target','_blank');
        	logoLink.setAttribute('title',this.logoLink);
            var logo = this.createTag (logoLink, "img", "logo", "logo-image");
            logo.setAttribute("src", this.logo);
                  
            this.bottomCell3 = this.createTag(this.bottomRow_1, "td", "bottomCell3", null);
            this.bottomCell3.setAttribute("align", "center");
            var para = this.createTag (this.bottomCell3, "p", "pstuff", "count-text");
            var countText = document.createTextNode(this.makeCountLine());
            para.appendChild(countText); 
            var br1 = this.createTag (para, "br", "br1", null);
            var anch = this.createTag (para, "a", "custA", "customize-link");
            anch.setAttribute("href", "#");
            anch.setAttribute("rel", "lightbox");
            anch.setAttribute("render", "REVVER.widget.videoCollections['" + this.elementId + "'].renderForm()");
            anch.setAttribute("lightBoxWidth", 550);
            anch.setAttribute("lightBoxHeight", 270);
            var anchText = document.createTextNode(this.json.display.searchText);
            anch.appendChild(anchText);
            
            var rssCell = this.createTag(this.bottomRow_1, "td", "bottomCell4", null);
            rssCell.setAttribute("width", "20%");
            rssCell.setAttribute("align", "right");
        	var rssLink = this.createTag(rssCell, "a", "revverRssLink", null);
        	rssLink.setAttribute('href', this.getCollectionRssLink());
        	rssLink.setAttribute('target', '_blank');
            var rss = this.createTag (rssLink, "img", "rssLogo", "rss-image");
            rss.setAttribute("src", this.rssLogo);
            
            this.bottomCell5 = this.createTag(this.bottomRow_1, "td", "bottomCell5", null);
            this.bottomCell5.setAttribute("width", this.lrButtonWidth);
            clear = this.createTag (this.bottomCell5, "img", "clear2", null);
            clear.setAttribute("src", REVVER.jsApiURL + "clear.gif");
            clear.setAttribute("width", this.lrButtonWidth);
        }
    },
    
    makeCountLine:function()
    {
        var start = this.currOffset + 1;
        var total = this.resultsCount; //this.vidArray.length + start - 1;
        var end = this.vidArray.length + start - 1;
        if (end > total) end = total;
        var text = start.toString() + '-' + end.toString() + ' of ' + total.toString();
        return text;
    },
    
    /**
     * Uses contentTbody, thumbContainer, ros, cols to se up the outer div.
     * MUST instantiate thumbContainer, so the rest of the obj will work.
     */
    setupOuterDiv:function()
    {
        
        this.createOuterContainer();

        // Vertical orientation: back/forward buttons on top/bottom.
        // Horizontal orientation: back/forward buttons on left/right.
       
        var thisID = "";    // Work area for building ID strings
        
        // set the arrows to display: none if the this.resultsCount is <= this.limit
        if (this.resultsCount <= this.limit) {
            this.styleManager.setStyleSelectorValue("up-arrow-cell", "display", "none");
            this.styleManager.setStyleSelectorValue("down-arrow-cell", "display", "none");
            this.styleManager.setStyleSelectorValue("back-arrow-cell", "display", "none");
            this.styleManager.setStyleSelectorValue("fwd-arrow-cell", "display", "none");
        } else {
            this.styleManager.setStyleSelectorValue("up-arrow-cell", "display", "");
            this.styleManager.setStyleSelectorValue("down-arrow-cell", "display", "");
            this.styleManager.setStyleSelectorValue("back-arrow-cell", "display", "");
            this.styleManager.setStyleSelectorValue("fwd-arrow-cell", "display", "");
        }
        
        if (this.orientation == "vertical") {
            // VERTICAL
            // Set the style of the main video collection div
            Element.setStyle(this.elementId, this.styleManager.getStyle("video-collection"));
            
            this.prevArrowRow = this.createTag(this.contentTbody, "tr", "prevArrowRow", null);
            this.prevArrowCell = this.createTag(this.prevArrowRow, "td", "prevArrowDiv", "up-arrow-cell");
            this.prevArrowCell.setAttribute("align", "center");
            this.prevArrowCell.setAttribute("vAlign", "middle");

            if (this.currOffset > 0) {
                // Show prev arrow, only if there are previous contents.
                this.prevArrowCell.setAttribute("title", "Go to previous set");  
                this.prevArrowCell.onclick = this.onPrevClick.bindAsEventListener(this);
                var prevImg = this.createTag (this.prevArrowCell, "img", "up-img", null);
                prevImg.setAttribute("src", this.uparrow);
            }
            else {
                this.prevArrowCell.setAttribute("class", "up-arrow-cell");
                var prevClear = this.createTag (this.prevArrowCell, "img", "pclear-img", null);
                prevClear.setAttribute("src", this.uparrow);
                Element.setStyle(prevClear, this.styleManager.getStyle("nextPrev-disabled"));
                prevClear.style['filter'] = "alpha(opacity=40)"; // because IE blows
                this.upDownButtonHeight = prevClear.height;
                this.upDownButtonWidth = prevClear.width;
            }
            // Create the cell that contains the array of thumbnails
            this.thumbTr = this.createTag(this.contentTbody, "tr", "thumb-container-tr", null);
            this.thumbContainer = this.createTag(this.thumbTr, "td", "thumb-container-td", null);
            
            // Create the cell that contains the Next arrow
            this.nextArrowRow = this.createTag(this.contentTbody, "tr", "nextArrowRow", null);
            this.nextArrowCell = this.createTag(this.nextArrowRow, "td", "nextArrowDiv", "down-arrow-cell");
            this.nextArrowCell.setAttribute("align", "center");
            this.nextArrowCell.setAttribute("vAlign", "middle");
            
            if ((this.currOffset + this.limit) < this.resultsCount) {
                this.nextArrowCell.onclick = this.onNextClick.bindAsEventListener(this);
                this.nextArrowCell.setAttribute("title", "Go to next set");  
                var nextImg = this.createTag (this.nextArrowCell, "img", "down-img", null);
                nextImg.setAttribute("src", this.downarrow);
            }
            else {
                this.nextArrowCell.setAttribute("class", "down-arrow-cell");    
                var nextClear = this.createTag (this.nextArrowCell, "img", "nclear-img", null);
                nextClear.setAttribute("src", this.downarrow);
                Element.setStyle(nextClear, this.styleManager.getStyle("nextPrev-disabled"));
                nextClear.style['filter'] = "alpha(opacity=40)"; // because IE blows
                this.upDownButtonHeight = nextClear.height;
                this.upDownButtonWidth = nextClear.width;
            }
        }
        else {
            // HORIZONTAL
            Element.setStyle(this.elementId, this.styleManager.getStyle("video-collection"));
            // All are in one row, so create that row
            this.outerRow = this.createTag(this.contentTbody, "tr", "outerRow", null);

            this.prevArrowCell = this.createTag(this.outerRow, "td", "prevArrowDiv", "back-arrow-cell");
            this.prevArrowCell.setAttribute("align", "center");
            this.prevArrowCell.setAttribute("vAlign", "middle");
            if (this.currOffset > 0) {
                // Show prev arrow, only if there are previous contents.
                this.prevArrowCell.setAttribute("title", "Go to previous set");  
                this.prevArrowCell.onclick = this.onPrevClick.bindAsEventListener(this);
                var prevImg = this.createTag (this.prevArrowCell, "img", "back-img", null);
                prevImg.setAttribute("src", this.backarrow);            
            }
            else {
                this.prevArrowCell.setAttribute("class", "back-arrow-cell");
                var prevClear = this.createTag (this.prevArrowCell, "img", "pclear-img", null);
                prevClear.setAttribute("src", this.backarrow);
                Element.setStyle(prevClear, this.styleManager.getStyle("nextPrev-disabled"));
                prevClear.style['filter'] = "alpha(opacity=40)"; // because IE blows
                this.lrButtonHeight = prevClear.height;
                this.lrButtonWidth = prevClear.width;
            }
            
            // Create the cell that contains the array of thumbnails
            this.thumbContainer = this.createTag(this.outerRow, "td", "thumb-container-td", null);
            
            // Create the cell that contains the Next arrow
            this.nextArrowCell = this.createTag(this.outerRow, "td", "nextArrowDiv", "fwd-arrow-cell");
            this.nextArrowCell.setAttribute("align", "center");
            this.nextArrowCell.setAttribute("vAlign", "middle");
            
            if ((this.currOffset + this.limit) < this.resultsCount) {
                this.nextArrowCell.onclick = this.onNextClick.bindAsEventListener(this);
                this.nextArrowCell.setAttribute("title", "Go to next set");  
                var nextImg = this.createTag (this.nextArrowCell, "img", "fwd-img", null);
                nextImg.setAttribute("src", this.fwdarrow);
            }
            else {
                this.nextArrowCell.setAttribute("class", "fwd-arrow-cell");    
                var nextClear = this.createTag (this.nextArrowCell, "img", "nclear-img", null);
                nextClear.setAttribute("src", this.fwdarrow);
                Element.setStyle(nextClear, this.styleManager.getStyle("nextPrev-disabled"));
                nextClear.style['filter'] = "alpha(opacity=40)"; // because IE blows
                this.lrButtonHeight = nextClear.height;
                this.lrButtonWidth = nextClear.width;
                
            }
        }

        this.createBottomLine();
    },
 
    createTag:function (myParent, tagType, idPrefix, className)
    {
        var tag = document.createElement(tagType);
        var thisID = idPrefix;  // Keep IDs distinct by main elementID
        if (this.elementId) {
            thisID += "-" + this.elementId;
        }
        tag.setAttribute("id", thisID);
        tag.setAttribute("class", className);
        if (myParent) {
            myParent.appendChild(tag);
        }
        
        if (className != null) {
            try {
                var thisStyle = this.styleManager.getStyle(className) || {};
                if (thisStyle) {
                    Element.setStyle(thisID, thisStyle);
                }
            }
            catch (e) {
                // alert(thisID + " : " + REVVER.util.toJSONString.object(thisStyle));
                // alert(REVVER.util.toJSONString.object(this.styleManager.styleList));
                // alert(REVVER.util.toJSONString(e));
            }
        }
        
        return tag;
    },
    
    createTag2:function (myParent, tagType, idPrefix, className)
    {
        var tag = document.createElement(tagType);
        var thisID = idPrefix;  // Keep IDs distinct by main elementID
        if (this.elementId) {
            thisID += "-" + this.elementId;
        }
        tag.setAttribute("id", thisID);
        tag.setAttribute("class", className);
        if (myParent) {
            myParent.appendChild(tag);
        }
        if (className != null) {
            var thisStyle = this.styleManager.getStyle(className);
            if (thisStyle) {
                Element.setStyle(tag, thisStyle);
            }
        }
        
        return tag;
    },
        
    createRadioButton:function(myParent, id, thisName, className) {
        
        var rdo = "";
        try {
            // Microsoft version:
            var str = "<input type=\"radio\" name=\"" + thisName + "\" >";
            rdo = document.createElement(str);
            rdo.setAttribute("id", id + '-' + this.elementId);
            if (myParent) {
                myParent.appendChild(rdo);
            }
            if (className != null) {
                rdo.setAttribute("class", className);
                var thisStyle = this.styleManager.getStyle(className);
                if (thisStyle) {
                    Element.setStyle(rdo, thisStyle);
                }
            }
        }
        catch (e) {
            // Perfectly normal version:
            rdo = this.createTag2(myParent, "input", id, className);
            rdo.setAttribute('type', 'radio');
            rdo.setAttribute('name', thisName);
        }

        return rdo;
    },
    
    /**
     *  Converts this.json.query to a string.
     *  replaces the need for the json.js
     */
    getQueryAsJSONString:function () {
        return REVVER.util.toJSONString.object(this.json.query);
    },
    
    /**
     *  This calls the revver webservice api via the REVVER.util.jsonRequest object.
     *  (see connection/jsonRequest.js)
     */
    requestData:function()
    {
        this.params = "method=" + this.methodName;
        this.params += "&callback=" + escape(this.callBack);
        this.params += "&params=" + escape(this.getQueryAsJSONString());

        var jsonRequestObj = new REVVER.util.jsonRequest(this);

        jsonRequestObj.send();
        jsonRequestObj = null;
    },

    /**
     *  After the json request occurs it will route data to this method.
     *  the actual processing of the information and creation of the widget 
     *  items starts here.
     *  Returned struct (array)
     *      Element 0 is the total count of items matching the query
     *      Element 1 is the returned collection
     *          Each thumb is an array element (from 0)
     */
    processData:function(json)
    {
        if ( $("fault-error-" + this.elementId) ) $("fault-error-" + this.elementId).innerHTML = "";
        if (json.faultString) {
            var container = this.thumbContainer || this.mainDiv;
            container.innerHTML = "";
            var errMsg = this.createTag (container, "span", "fault-error", "err-msg");
            var text = document.createTextNode("Error returned from server: " + json.faultString);
            REVVER.log(text);
            errMsg.appendChild(text);
            return;
        }

        if ( $("noresults-error-" + this.elementId) ) $("noresults-error-" + this.elementId).innerHTML = "";
        if ((!json) || !(json[0]) || json[0] == 0 || json[1].length == 0) {
            var container = this.thumbContainer || this.mainDiv;
            container.innerHTML = "";
            var errMsg = this.createTag (container, "span", "noresults-error", "err-msg");
            var text = document.createTextNode(this.json.display.noResultsMsg);
            REVVER.log(text);
            errMsg.appendChild(text);
            return;
        }
        
        this.vidArray = json[1]; // this json data may be needed more than once so i'm setting it into the object
        this.resultsCount = json[0];

        // Clear out any previous contents of main container
        this.emptyOuterDiv();
        // Create the outer container
        this.setupOuterDiv();
        
        this.thumbTable = this.createTag(this.thumbContainer, "table", "thumb-table", null);
        this.thumbTbody = this.createTag(this.thumbTable, "tbody", "thumb-tbody", null);
        
        var rowNum = 0;
        var rowMax = this.rows;
        var colNum = 0;
        var colMax = this.cols;
        var i = 0;
        var item = "";
        
        for (rowNum = 0; rowNum < rowMax; rowNum++) {
            var idStr = "thumb-tr-" + rowNum;
            var thumbRow = this.createTag(this.thumbTbody, "tr", idStr, null);
            for (colNum = 0; colNum < colMax; colNum++) {
                if (i >= this.vidArray.length) break;
                var tdId = "thumb-td-" + colNum + "-" + rowNum;
                var thumbCol = this.createTag(thumbRow, "td", tdId, null);
                thumbCol.setAttribute("vAlign", "top");            
                
                this.addThumb(this.vidArray[i], thumbCol);
                i++;
            }
            if (i >= this.vidArray.length) break;
        }
        // Lightbox is the stuff that comes up when a thumb is selected.
        initLightbox();
    },
        
    /**
     *  Make a single thumbnail object here that can be inserted 
     *  into a container on the page.
     */
    addThumb:function(thumbData, thumbTd)
    {
        var thisThumb = new REVVER.widget.Thumbnail(thumbData, this, thumbTd);
        this.thumbs.push(thisThumb);
    },
    
    /*
     * Event handler for when the user clicks the "Previous set" button
     */
    onPrevClick:function()
    {
       if (this.currOffset > 0) {
           this.currOffset -= this.limit;
           this.json.query[2].offset = this.currOffset;
           this.requestData();
       }
    },
    
    /*
     * Event handler for when the user clicks the "Next set" button
     */
    onNextClick:function()
    {
        if ((this.currOffset + this.limit) < this.resultsCount) {
            this.currOffset += this.limit;
            this.json.query[2].offset = this.currOffset;
            this.requestData();
        }
    },

    renderMovie:function(parentId, thumbnailId, id, affiliateId)
    {
    
        var parent = $(parentId);
        var thumb = $(thumbnailId);

        // Remove this table if it currently exists
        var outerTableID = "outerTable-" + this.elementId;
        var testForTable = $(outerTableID);
        if (testForTable) {
            testForTable.parentNode.removeChild(testForTable);
        }

        // Make a table to contain all the contents
        var outerTable = this.createTag(null, "table", "outerTable", null);
        var outerTbody = this.createTag(outerTable, "tbody", "outerTbody", null);

        var titleRow = this.createTag(outerTbody, "tr", "titleRow", null);
        var titleCell = this.createTag2(titleRow, "td", "titleCellX", "lb-title");
        var titleText = document.createTextNode(thumb.getAttribute("caption"));
        titleCell.appendChild(titleText);

        var closeCell = this.createTag2(titleRow, "td", "closeCellX", "lb-close");
        closeCell.setAttribute('align','right');
    	var alink = this.createTag2(closeCell, "a", "closeLinkX", 'lb-close');
    	alink.setAttribute('href','#');
    	alink.setAttribute('title','Click to close');
    	alink.onclick = function () {hideLightbox(); return false;}
    	var closeButton = this.createTag (alink, "img", "closeButton", "close-button");
        closeButton.setAttribute("src", this.closeButton);

        var movieRow = this.createTag(outerTbody, "tr", "movieRow", null);
        var movieCell = this.createTag(movieRow, "td", "movieCell", null);
        movieCell.setAttribute('colSpan','2');

        var movieTable = this.createTag(movieCell, "table", "movieTable", null);
        var movieTbody = this.createTag(movieTable, "tbody", "movieTbody", null);

        var mr1 = this.createTag(movieTbody, "tr", "mr1", null);
        var videoCell = this.createTag(mr1, "td", "videoCell", null);
        videoCell.setAttribute('vAlign','top');
        videoCell.setAttribute('width',480);

        // create a div to house the video.  this is needed so the UFO object has a place to 
        // put the video obj after it's created
        var divId = "videoContainer-" + (new Date()).getTime() + Math.floor(Math.random()*20000);
        var videoContainer = this.createTag(videoCell, "div", divId, null);

        var divId = divId + "-" + this.elementId;
        var flashParams = this.json.flashPlayerParams || {};
        flashParams.divId = divId;
        flashParams.mediaId = id;
        flashParams.affiliateId = affiliateId;
        flashParams.autoStart = true;

        REVVER.widget.videoIntervals[divId] = setInterval(function() {
            revverVideo.embed(flashParams);
            clearInterval(REVVER.widget.videoIntervals[divId]);
		}, 1000);

        var textTd = this.createTag(mr1, "td", "textCell", null);
        textTd.setAttribute('vAlign','top');
        
        var textTable = this.createTag(textTd, "table", "textTable", null);
        textTable.setAttribute('height', 400);
        var textTbody = this.createTag(textTable, "tbody", "textTbody", null);

        var textRow = this.createTag(textTbody, "tr", "textRow", null);
        var textCell = this.createTag(textRow, "td", "textCell", null);
        textCell.setAttribute('vAlign', 'top');
        
        var textContainer = this.createTag(textCell, "div", "textContainer", null);
        textContainer.style.height = "350px";
        textContainer.style.overflow = "auto";
       
        var uploadP = this.createTag2(textContainer, "p", "uploadP", "lb-text");        
        var thisOwner = thumb.getAttribute("owner");
        if (thisOwner) {
            var uploadedBy = document.createTextNode("Uploaded by: ");
            uploadP.appendChild(uploadedBy);
            var ownerSpan = this.createTag2(uploadP, "span", "uploadSpan", "lb-owner");
            var ownerText = document.createTextNode(thisOwner);
            ownerSpan.appendChild(ownerText);
        }
        var thisCredits = thumb.getAttribute("credits");
        if (thisCredits) {
            var creditP = this.createTag2(uploadP, "br", "creditP", "lb-text");        
            var creditText = document.createTextNode("Credits: " + thisCredits);
            uploadP.appendChild(creditText);
        }

        var thisKeywords = thumb.getAttribute("keywords");
        if (thisKeywords) {
            var kwdP = this.createTag2(textContainer, "p", "kwdP", "lb-text");        
            var tagText = document.createTextNode("Tags: ");
            kwdP.appendChild(tagText);
            var kwdSpan = this.createTag2(kwdP, "span", "kwdSpan", "lb-keywords");
            
            var withSpaces = thisKeywords.toString().split(",").join(", ");
            var kwdText = document.createTextNode(withSpaces);
            kwdSpan.appendChild(kwdText);
        }

        var thisDesc = thumb.getAttribute("description");
        if (thisDesc) {
            var descP = this.createTag2(textContainer, "p", "descP", "lb-description");        
            var descText = document.createTextNode("Description: " + thisDesc);
            descP.appendChild(descText);
        }
        var statsP = this.createTag2(textContainer, "p", "statsP", "lb-text");        
        var thisRating = thumb.getAttribute("rating");
        if (thisRating) {
            var ratingText = document.createTextNode("Rating: " + thisRating);
            statsP.appendChild(ratingText);
            var ratingBr = this.createTag2(statsP, "br", "ratingBr", null);        
            var agetText = document.createTextNode("Age Rating: " + thisRating);
            uploadP.appendChild(creditText);
        }
        var thisAgeRating = thumb.getAttribute("minagerestriction");
        if (thisAgeRating) {
            var ratingBr2 = this.createTag2(statsP, "br", "ratingBr2", null);        
            var agetText = document.createTextNode("Age Rating: " + this.getAgeRating(thisAgeRating));
            statsP.appendChild(agetText);
        }
        var thisViews = thumb.getAttribute("views");
        if (thisViews) {
            var ratingBr3 = this.createTag2(statsP, "br", "ratingBr3", null);        
            var thisViews = document.createTextNode("Views: " + thisViews);
            statsP.appendChild(thisViews);
        }
        
        //--------------
        var iconRow = this.createTag(textTbody, "tr", "iconRow", null);
        var iconCell = this.createTag(iconRow, "td", "iconCell", null);
    	var logoLink = this.createTag2(iconCell, "a", "logoLinkX", null);
    	logoLink.setAttribute('href',this.logoLink);
    	logoLink.setAttribute('target','_blank');
    	logoLink.setAttribute('title',this.logoLink);
        var logo = this.createTag (logoLink, "img", "logo", "biglogo");
        logo.setAttribute("src", this.bigLogo);            
        logo.setAttribute('align','right');
        logo.setAttribute('vAlign','bottom');
        
        return outerTable;
    },
    
    renderForm:function () {
        var formContainer = this.createTag(null, "div", "formContainer", null);
        var titleTable = this.createTag(formContainer, "table", "titleTable", null);
        titleTable.setAttribute('width', '100%');
        titleTable.setAttribute('cellpadding', '0');
        var titleTbody = this.createTag(titleTable, "tbody", "titleTbody", null);
        
        var titleRow = this.createTag(titleTbody, "tr", "titleRow", null);
        var titleCell = this.createTag2(titleRow, "td", "titleCellY", "lb-title");
        var titleText = document.createTextNode(this.json.display.title);
        titleCell.appendChild(titleText);
        var titleCloseCell = this.createTag2(titleRow, "td", "titleCloseCellY", "lb-title");
        titleCloseCell.setAttribute('align', 'right');
        
    	var alink = this.createTag2(titleCloseCell, "a", "closeLinkY", 'lb-close');
    	alink.setAttribute('href','#');
    	alink.setAttribute('title','Click to close');
    	alink.onclick = function () {hideLightbox(); return false;}
        
        var closeButton = this.createTag2 (alink, "img", "closeButtonImg", "lb-close");
        closeButton.setAttribute("src", this.closeButton);
        //-------
        this.createTag2(formContainer, "br", "titleCloseCellY", null);
        var formForm = this.createTag(formContainer, "form", "revver-searchBox-form", null);
        formForm.setAttribute('action', '#');
        formForm.setAttribute('method', 'get');
        //--------
        var formTable = this.createTag(formContainer, "table", "formTable", null);
        formTable.setAttribute('align', 'center');
        formTable.setAttribute('cellpadding', '5');
        formTable.setAttribute('border', '0');
        var formTbody = this.createTag(formTable, "tbody", "formTbody", null);
        //--------
        var searchRow = this.createTag(formTbody, "tr", "searchRow", null);
        var searchLabelCell = this.createTag2(searchRow, "td", "searchLabelCell", null);
        var searchLabel = this.createTag2(searchLabelCell, "label", "searchLabel", "revver-searchBox-Label");
        searchLabel.setAttribute('for', 'revver-widget-keywords-'+this.elementId);
        var titleText = document.createTextNode("Search:");
        searchLabel.appendChild(titleText);
        var searchInputCell = this.createTag2(searchRow, "td", "searchInputCell", null);
        var searchInput = this.createTag2(searchInputCell, "input", "revver-widget-keywords", "searchBoxField");
        searchInput.setAttribute('type', 'text');
        searchInput.setAttribute('name', 'keywords');
        searchInput.setAttribute('maxlength', '100');
        searchInput.setAttribute('size', '35');
        searchInput.value = this.json.query[0].search || "";
        //--------
        var orderLabelRow = this.createTag(formTbody, "tr", "orderLabelRow", null);
        var orderLabelCell = this.createTag2(orderLabelRow, "td", "orderLabelCell", null);
        orderLabelCell.setAttribute('vAlign', 'top');
        var orderLabel = this.createTag2(orderLabelCell, "label", "orderLabel", "revver-searchBox-Label");
        var orderText = document.createTextNode("Order By:");
        orderLabel.appendChild(orderText);
        //--------
        var optionsCell = this.createTag2(orderLabelRow, "td", "optionsCell", null);

        var optionsTable = this.createTag(optionsCell, "table", "optionsTable", null);
        optionsTable.setAttribute('cellspacing', '0');
        optionsTable.setAttribute('cellpadding', '0');
        optionsTable.setAttribute('border', '0');
        var optionsTbody = this.createTag(optionsTable, "tbody", "optionsTbody", null);

        var optionslRow = this.createTag(optionsTbody, "tr", "optionslRow", null);
        var optionsLeftCell = this.createTag2(optionslRow, "td", "optionsLeftCell", null);
        optionsLeftCell.setAttribute('vAlign', 'top');
        //--------

        var radio1 = this.createRadioButton(optionsLeftCell, 'revver-widget-modifiedDate', 'revver-widget-orderBy', "radio-button"); 
        radio1.setAttribute('value', 'radio1val');        
        var radio1Label = this.createTag2(optionsLeftCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio1Label.htmlFor = 'revver-widget-modifiedDate-'+this.elementId;
        var radio1LabelText = document.createTextNode("Modified Date");
        radio1Label.appendChild(radio1LabelText);
        this.createTag2(optionsLeftCell, "br", null, null);

        var radio2 = this.createRadioButton(optionsLeftCell, 'revver-widget-publicationDate', 'revver-widget-orderBy', "radio-button"); 
        radio2.setAttribute('value', 'radio2val');
        var radio2Label = this.createTag2(optionsLeftCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio2Label.htmlFor = 'revver-widget-publicationDate-'+this.elementId;
        var radio2LabelText = document.createTextNode("Publication Date");
        radio2Label.appendChild(radio2LabelText);
        this.createTag2(optionsLeftCell, "br", null, null);

        var radio3 = this.createRadioButton(optionsLeftCell, 'revver-widget-author', 'revver-widget-orderBy', "radio-button"); 
        radio3.setAttribute('value', 'radio3val');
        var radio3Label = this.createTag2(optionsLeftCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio3Label.htmlFor = 'revver-widget-author-'+this.elementId;
        var radio3LabelText = document.createTextNode("Author");
        radio3Label.appendChild(radio3LabelText);
        this.createTag2(optionsLeftCell, "br", null, null);

        var radio4 = this.createRadioButton(optionsLeftCell, 'revver-widget-title', 'revver-widget-orderBy', "radio-button"); 
        radio4.setAttribute('value', 'radio4val');
        var radio4Label = this.createTag2(optionsLeftCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio4Label.htmlFor = 'revver-widget-title-'+this.elementId;
        var radio4LabelText = document.createTextNode("Title");
        radio4Label.appendChild(radio4LabelText);
        this.createTag2(optionsLeftCell, "br", null, null);

        var radio5 = this.createRadioButton(optionsLeftCell, 'revver-widget-views', 'revver-widget-orderBy', "radio-button"); 
        radio5.setAttribute('value', 'radio5val');
        var radio5Label = this.createTag2(optionsLeftCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio5Label.htmlFor = 'revver-widget-views-'+this.elementId;
        var radio5LabelText = document.createTextNode("Views");
        radio5Label.appendChild(radio5LabelText);
        this.createTag2(optionsLeftCell, "br", null, null);

        var radio6 = this.createRadioButton(optionsLeftCell, 'revver-widget-averageRating', 'revver-widget-orderBy', "radio-button"); 
        radio6.setAttribute('value', 'radio6val');
        var radio6Label = this.createTag2(optionsLeftCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio6Label.htmlFor = 'revver-widget-averageRating-'+this.elementId;
        var radio6LabelText = document.createTextNode("Average Rating");
        radio6Label.appendChild(radio6LabelText);
        this.createTag2(optionsLeftCell, "br", null, null);
        
        var spacesCell = this.createTag2(optionslRow, "td", "optionsLeftCell", null);
        spacesCell.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

        var optionsRightCell = this.createTag2(optionslRow, "td", "optionsRightCell", null);
        optionsRightCell.setAttribute('vAlign', 'top');
        
        var radio7 = this.createRadioButton(optionsRightCell, 'revver-widget-asc', 'revver-widget-ascDesc', "radio-button"); 
        //radio7.defaultChecked = true;
        radio7.setAttribute('value', 'radio7val');
        var radio7Label = this.createTag2(optionsRightCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio7Label.htmlFor = 'revver-widget-asc-'+this.elementId;
        var radio7LabelText = document.createTextNode("Ascending");
        radio7Label.appendChild(radio7LabelText);
        this.createTag2(optionsRightCell, "br", null, null);

        var radio8 = this.createRadioButton(optionsRightCell, 'revver-widget-desc', 'revver-widget-ascDesc', "radio-button"); 
        radio8.setAttribute('value', 'radio8val');
        var radio8Label = this.createTag2(optionsRightCell, "label", "orderLabel", "revver-searchBox-optionLabel");
        radio8Label.htmlFor = 'revver-widget-desc-'+this.elementId;
        var radio8LabelText = document.createTextNode("Descending");
        radio8Label.appendChild(radio8LabelText);
        this.createTag2(optionsRightCell, "br", null, null);

        var submitRow = this.createTag2(formTbody, "tr", "submitRow", null);
        var submitCell = this.createTag2(submitRow, "td", "submitCell", null);
        submitCell.setAttribute('align', 'right');
        submitCell.setAttribute('colSpan', '2');

        var cancelButton = this.createTag2 (submitCell, "button", "cancelButton", "searchBoxBtn");
        cancelButton.setAttribute("name", "revver-widget-cancelBtn");
        var cancelButtonText = document.createTextNode("Cancel");
        cancelButton.appendChild(cancelButtonText);
    	cancelButton.onclick = function () {hideLightbox(); return false;}

        var submitButton = this.createTag2 (submitCell, "button", "submitButton", "searchBoxBtn");
        submitButton.setAttribute("name", "revver-widget-submitBtn");
        var submitButtonText = document.createTextNode("Apply");
        submitButton.appendChild(submitButtonText);
    	submitButton.onclick = this.formSubmit.bindAsEventListener(this);

        return formContainer;
        
    },
    
    formSubmit:function() {
        var keyStr = "";
        var ordbool = true;
	    var kwds = $("revver-widget-keywords-" + this.elementId); // Keywords property
	    var modDate = $("revver-widget-modifiedDate-" + this.elementId);
	    var pubDate = $("revver-widget-publicationDate-" + this.elementId);
	    var author = $("revver-widget-author-" + this.elementId);
	    var title = $("revver-widget-title-" + this.elementId);
	    var views = $("revver-widget-views-" + this.elementId);
	    var avgRating = $("revver-widget-averageRating-" + this.elementId);
	    var asc = $("revver-widget-asc-" + this.elementId);
	    var desc = $("revver-widget-desc-" + this.elementId);
	    
	    if (modDate.checked) keyStr = "modifiedDate";
	    else if(pubDate.checked) keyStr = "publicationDate";
	    else if(author.checked) keyStr = "author";
	    else if (title.checked) keyStr = "title";
	    else if (views.checked) keyStr = "views";
	    else if (avgRating.checked) keyStr = "ratingAverage";
	    else keyStr = "none";

        // Make an array of strings from the input text
        if (kwds.value) {
            this.json.query[0].search = kwds.value.split(',');
        } else {
            this.json.query[0].search = [''];
        }
        
        if (keyStr != "none") {
            if (desc.checked) ordbool = false;
            if (!this.json.query[0].orderBy) {
                this.json.query[0].orderBy = [];
            }
            this.json.query[0].orderBy[0] = keyStr;
            this.json.query[0].orderBy[1] = ordbool;
        }

        // reset the offset
        this.json.query[2].offset = 0;
        this.currOffset = 0;

        this.requestData();
        hideLightbox();
        return false;
    },
    
    getAgeRating:function (rating)
    {
        switch (rating) {
            case "1":
                return "All Audiences";
            case "2":
                return "PG";
            case "3":
                return "PG13";
            case "4":
                return "R";
            case "5":
                return "NC17";
            default:
                return "Unknown";
        }
    }
};

/**
 *  This is the thumbnail class.  We'll create a new 
 *  object from the VideoCollection for each thumbnail 
 *  we find.  At this point this will likely have a 
 *  container itself so house the image, title, minutes, etc.
 */
REVVER.widget.Thumbnail = Class.create();
REVVER.widget.Thumbnail.prototype = {

    /*
     * This method is called automatically when you say new Thumbnail(thumbData).
     * thumbData is a branch of the incoming JSON response struct that contains
     * the data associated with one thumbnail.
     * myParent is the VideoCollection object that contains this thumbnail.
     */
    initialize:function(thumbData, myParent, parentTd)
    {
        this.parentContainer = myParent;    // This is a VideoCollection object.
        this.thumbData = thumbData;         // JSON data of one returned thumbnail
        this.styleManager = myParent.styleManager;
        this.orientation = myParent.orientation;
        this.parentTd = parentTd;
        this.parentId = myParent.elementId;
        this.render(thumbData);
    },
    
    getMovieType: function (url)
    {
        var dotPos = url.lastIndexOf('.');
        var ext = 'unk';
        if (dotPos != -1) {
            ext = url.substr(dotPos+1);
        }
        return ext;
    },
    
    onShowMovie: function ()
    {
        this.parentContainer.json.onShowMovie(this.thumbData, this.affiliateId);
        return false;
    },
    
    /**
     * Set up and display one thumbnail container, given the source data in
     * item. Item is a branch of the incoming JSON response struct that contains
     * the data associated with one thumbnail.
     * 
     */    
     render:function (item)
     {
        if (!item.id) return;   // No movie, no showee -- now no id no showee
        
        var affiliateId = item.affiliateId || 0;
        if (isNaN(affiliateId)) affiliateId = 0;
        this.affiliateId = affiliateId;

        var thisThumb = document.createElement("div");
        this.parentTd.appendChild(thisThumb);
        // Create the outer div for this thumb
        var thisID = "vthumb-" + item.id;
        // since the same video might came back in a search we 
        // need to ensure each one has a unique Id.
        if ($(thisID)) thisID += (new Date()).getTime() + Math.floor(Math.random()*10000);
        thisThumb.setAttribute("id", thisID);
        thisThumb.setAttribute("class", "thumb-div");
        Element.setStyle(thisID, this.styleManager.getStyle("thumb-div"));

        // Make span inside the para
        if (item.title) {
            // Make a new para, sibling to pimage.
            var pTitle = this.createTag (item, thisThumb, "p", "vpic-ptitle", "thumb-title");
            var clipTitle = this.clipString(item.title);
            var titleText = document.createTextNode(clipTitle);
            pTitle.appendChild(titleText);
        }
        
        // Create an A tag to have an href. This A tag will be accessed by the lightbox
        // widget, so we populate it with all the text it needs, by setting custom attributes.
        this.anchor = this.createTag (item, thisThumb, "a", "vpic-a", null);
        this.anchor.setAttribute("href", item.id);

        // LightBox:
        if ( typeof(this.parentContainer.json.onShowMovie) != "function" ) {
            this.anchor.setAttribute("rel", "lightbox");
        }
        this.anchor.setAttribute("caption", item.title);

        // Make the image tag and put it inside the A-tag.
        var paImage = this.createTag (item, this.anchor, "img", "vpic-img", "thumb-img");
        if (item.thumbnailUrl) {
            paImage.setAttribute("src", item.thumbnailUrl);
            paImage.setAttribute("title", item.title);
        }
        else {
            paImage.setAttribute("src", REVVER.jsApiURL + "clear.gif");
        }
        
        // if we have a custom function for the showMovie then don't use the lightbox handler
        if ( typeof(this.parentContainer.json.onShowMovie) != "function" ) {
            // Pass some other data items via the a tag
            this.anchor.setAttribute("render", "REVVER.widget.videoCollections['" + this.parentId + "'].renderMovie('" + this.parentId + "','" + this.anchor.id + "'," + item.id + "," + affiliateId + ")");
        } else {
        	this.anchor.onclick = this.onShowMovie.bindAsEventListener(this);
        }

        if (item.owner) this.anchor.setAttribute("owner", item.owner);
        if (item.credits) this.anchor.setAttribute("credits", item.credits);
        if (item.keywords) this.anchor.setAttribute("keywords", item.keywords);
        if (item.description) this.anchor.setAttribute("description", item.description);
        if (item.rating && item.rating.average) this.anchor.setAttribute("rating", item.item.rating.average);
        if (item.views) this.anchor.setAttribute("views", item.views);
        if (this.parentContainer.json.query[0].minAgeRestriction) this.anchor.setAttribute("minAgeRestriction", this.parentContainer.json.query[0].minAgeRestriction);
        var movieWidth = 680;
        var movieHeight = 445;
        if (this.parentContainer.json.display.videoWidth) movieWidth = this.parentContainer.json.display.videoWidth;
        if (this.parentContainer.json.display.videoHeight) movieHeight = this.parentContainer.json.display.videoHeight;
        this.anchor.setAttribute("lightBoxWidth", movieWidth);
        this.anchor.setAttribute("lightBoxHeight", movieHeight);
        paImage.setAttribute("width", this.parentContainer.thumbWidth);
        paImage.setAttribute("height", this.parentContainer.thumbHeight);
        
        // Make a new para, sibling to pimage, to hold author
        if (item.author) {
            this.anchor.setAttribute("author", item.author);
            // Make a new para, sibling to pimage.
            var pAuthor = this.createTag (item, thisThumb, "p", "vpic-pauth", "thumb-text");
            var clipAuthor = this.clipString("by " + item.author);
            var authorText = document.createTextNode(clipAuthor);
            pAuthor.appendChild(authorText);
        }

        // Make a new para, sibling to pimage, to hold publication date/time
        if (item.publicationDate) {
            this.anchor.setAttribute("publicationDate", item.publicationDate);
            var pPDate = this.createTag (item, thisThumb, "p", "vpic-pdate", "thumb-text");
            var clipPdate = this.clipString(item.publicationDate);
            var pdateText = document.createTextNode(clipPdate);
            pPDate.appendChild(pdateText);
        }
        var ratingLine = "";
        if (item.views) {
            this.anchor.setAttribute("views", item.views);
            ratingLine += "Views: " + item.views + " ";
        }
        /* not available with this version of the api.  must be an authed user to get this data.
        if (item.rating.average) {
            this.anchor.setAttribute("average", item.average);
            ratingLine += "Rating: " + item.rating.average + " ";
        }
        */
        if (item.views) { //        if (item.views || item.rating.average) {
            var pRLine = this.createTag (item, thisThumb, "p", "vpic-prline", "thumb-text");
            var clipRline = this.clipString(ratingLine);
            var ratingText = document.createTextNode(clipRline);
            pRLine.appendChild(ratingText);
        }
        if (item.duration) {
            this.anchor.setAttribute("duration", item.duration);
            var pDLine = this.createTag (item, thisThumb, "p", "vpic-pdurline", "thumb-text");
            var durLine = this.clipString("Runtime: " + this.makeTimeString(item.duration));
            var durText = document.createTextNode(durLine);
            pDLine.appendChild(durText); 
        }
    },
    
    // Assuming tahoma x-small
    clipString: function(str)
    {
        var outstr = "";
        if (str.length > this.parentContainer.thumbTitleMaxLen) {
            outstr = str.substr(0, this.parentContainer.thumbTitleMaxLen);
            outstr += "...";
        }
        else {
            outstr = str;
        }
        return outstr;
    },
    
    /*
     * Converts seconds into a string in the form H:MM:SS
     */
    makeTimeString: function(secs)
    {
        var hrs = Math.floor(secs / 3600);
        var mins = Math.floor(secs / 60);
        mins -= (hrs * 60);
        var rem = secs - ((hrs * 3600) + (mins * 60));
        var outStr = "";
        if (hrs > 0) outStr += hrs + ":";
        var minStr = "";
        if (mins < 10) minStr = "0";
        minStr += mins.toString();
        var secStr = "";
        if (rem < 10) secStr = "0";
        secStr += rem.toString();
        outStr += minStr + ":" + secStr;
        return outStr;
    },
    
    createTag:function (item, myParent, tagType, idPrefix, className)
    {
        var tag = document.createElement(tagType);
        var thisID = idPrefix + "-" + item.id;

        // since the same video might came back in a search we 
        // need to ensure each one has a unique Id.
        if ($(thisID)) thisID += (new Date()).getTime() + Math.floor(Math.random()*10000);

        tag.setAttribute("id", thisID);
        tag.setAttribute("class", className);
        if (myParent) {
            myParent.appendChild(tag);
        }
        
        if (className != null) {
            var thisStyle = this.styleManager.getStyle(className);
            if (thisStyle) {
                Element.setStyle(thisID, thisStyle);
            }
        }
        
        return tag;
    },

    
    createTag2:function (item, myParent, tagType, idPrefix, className)
    {
        var tag = document.createElement(tagType);
        var thisID = thisID = idPrefix + "-" + item.id;

        // since the same video might came back in a search we 
        // need to ensure each one has a unique Id.
        if ($(thisID)) thisID += (new Date()).getTime() + Math.floor(Math.random()*10000);

        tag.setAttribute("id", thisID);
        tag.setAttribute("class", className);
        if (myParent) {
            myParent.appendChild(tag);
        }
        
        if (className != null) {
            var thisStyle = this.styleManager.getStyle(className);
            if (thisStyle) {
                Element.setStyle(tag, thisStyle);
            }
        }
        
        return tag;
    }
};