var videoTabs = {   nav1: "videos",
                    nav2: "most-viewed",
                    nav3: "highest-rated",
                    nav4: "most-emailed",
                    nav5: "most-commented"  };

var VA_CHANNELS = "channels";
var VA_VIDEOS = "videos";
var VA_FEED = "feed-videos";
var all_channels = null;
var toggledNode = null;
var view_ad = "";

function changeArchiveTab(elem){
    var parentNode = getFirstParentByTagAndClassName(elem, "li");
    var newId = getNodeAttribute(parentNode, "id");
    var feedNode = getElement(VA_FEED);
    var nodeToToggle = videoTabs[newId];
	view_ad = videoTabs[newId];
	
    if(newId == "nav1"){
        showElement(VA_CHANNELS);
    }
    else{
        replaceChildNodes(feedNode, null);
        hideElement(VA_CHANNELS);
        
        //try to get an element with name in videoTabs[newId]
        //if it exists, toggle it, otherwise get video JSON feed
        //with name in videoTabs[newId]
        if( !getElement(videoTabs[newId]) ) {
            nodeToToggle = VA_FEED
            getVideos(videoTabs[newId], feedNode, "More Videos");
        }
    }

    toggleTab(newId, nodeToToggle);
}

function changePage(page, channel, title, q){
    var section_info = {"title":title, "channel":channel};
    var qs = {"q":q, "json":"yes", "page":page};

    getVideos(getElement(VA_VIDEOS), section_info, qs);
}

function changeChannel(elem, channel, title){
    var section_info = {"title":title, "channel":channel};
    var qs = {"json":"yes", "page":0};
    toggleSubMenu(elem);
    getVideos(getElement(VA_VIDEOS), section_info, qs);
}

function doSearch(form) {
    var section_info = {"title":"Search results for " + form.q.value, "channel":"search"};
    var qs = {"q":form.q.value, "page":0, "json":"yes"};
    getVideos(getElement(VA_VIDEOS), section_info, qs);
    toggleTab("nav1", videoTabs["nav1"]);
}

function getVideos(node, section_info, qs){
    var vFeedUrl = "/videos/" + section_info.channel;
    var vFeedData = loadJSONDoc(vFeedUrl, qs);
    

    var parseVideos = function(vData){
        var pagination_opts = vData.pop();
        var adData = getElementsByTagAndClassName("li", "bigboxad", node);
        replaceChildNodes(node, makeTitleListItem(section_info, pagination_opts));
        appendChildNodes(node, adData);
        
        if(vData.length != 0)
            appendChildNodes(node, map(makeVideoListItem, vData));
        else
            failVideos(null);

        appendChildNodes(node, makeTitleListItemBottom(section_info, pagination_opts));
    };

    var failVideos = function(err){
        replaceChildNodes(node, [  LI({"class": "message"}, document.createTextNode("No videos were found for this channel"))/*,
                                        LI({"class": "message"}, document.createTextNode(err))*/  ] );
    };
    vFeedData.addCallbacks(parseVideos, failVideos);
}

function toggleTab(elem, container){
    var wrapperNode = getFirstParentByTagAndClassName(elem, "div");
    setNodeAttribute(wrapperNode, "class", elem);
    toggleNode(container);
}

function toggleSubMenu(elem){
    var liNode = getFirstParentByTagAndClassName(elem, "li");
    var parentNode = null;

    try {
        parentNode = getFirstParentByTagAndClassName(liNode, "li");
    }
    catch(err) {
        parentNode = liNode;
    }

    if(parentNode == undefined)
        parentNode = liNode;

    var childUlNode = getFirstElementByTagAndClassName("ul", null, liNode);

    if( !all_channels )
        all_channels = getElementsByTagAndClassName("li", null, VA_CHANNELS);

    //toogle all other channels
    for(var i in all_channels) {
        if( parentNode != toggledNode ){
            removeElementClass(all_channels[i], "hot");
            removeElementClass(all_channels[i], "arrowDown");
        }
    }

    if( liNode ) {
        toggledNode = parentNode;

        addElementClass(liNode, "hot");
        if(childUlNode) {
            addElementClass(liNode, "arrowDown");
        }
    }
}

function toggleNode(elem){
    var parentNode = getFirstParentByTagAndClassName(elem, "div");
    var others = getElementsByTagAndClassName("ul", "videosList", parentNode);

    for(var i in others)
        addElementClass(others[i], "invisible");

    removeElementClass(elem, "invisible");
}

function makeTitleListItem(section_info, page_opts){
    return LI( {"class":"message va_pagination"},
               [ makePaginationObject(section_info, page_opts),
                 SPAN( {"class":"video_channel"}, document.createTextNode(section_info.title) )]
           );
}

function makeTitleListItemBottom(section_info, page_opts){
    return LI( {"class":"message va_pagination bottom"}, [makePaginationObject(section_info, page_opts)] );
}

function makePaginationObject(section_info, page_opts){
    var section_url = "/videos/" + section_info.channel + "/";
    var pagination_obj = SPAN( {"class":"pagination"}, "Page " + (page_opts.page+1) + " of " + page_opts.pages + " " );

    var next_link = A({"href":section_url + "?" + queryString(["q", "page"], [page_opts.q, page_opts.page+1, "yes"])}, "Next");
    next_link.setAttribute("onClick", "changePage("+ (page_opts.page+1) +", '"+ section_info.channel +"', '"+ section_info.title +"', '" + page_opts.q + "');return false;");

    var prev_link = A({"href":section_url + "?" + queryString(["q", "page"], [page_opts.q, page_opts.page-1, "yes"])}, "Previous");
    prev_link.setAttribute("onClick", "changePage("+ (page_opts.page-1) +", '"+ section_info.channel +"', '"+ section_info.title +"', '" + page_opts.q + "');return false;");

    if(page_opts.has_previous)
        appendChildNodes(pagination_obj, prev_link);

    if(page_opts.has_next)
        appendChildNodes(pagination_obj, next_link);

    return pagination_obj
}



function makeVideoListItem(objData){
    var ratingNode = makeRatingNode(objData.rating, true);
    var viewsNode = null;
    
    //if we have views count, push it into a span that's added to our return object
    if(objData.views)
        viewsNode = SPAN({"class":"viewed"}, document.createTextNode(" (" + objData.views + " views)"));

    if(objData.thumbnail_url){
        thumbUrl = objData.thumbnail_url;
    }
    else
        thumbUrl = "http://media.scrippsnewspapers.com/corp_assets/assets/images/reel_large.png";

    return LI(null, [
        A({href: objData.content_url}, [
            IMG({src: thumbUrl, width: 156, height:90, border: 0}),
            BR(null),
            document.createTextNode(objData.label)
        ]),
        [SPAN(null, document.createTextNode(truncate_words(objData.description, 7)))],
        [BR(null), ratingNode]
    ]);
}

/*function makeVideoListItemTest(objData){
    var ratingNode = makeRatingNode(objData.rating, true);
    var viewsNode = null;
    
    //if we have views count, push it into a span that's added to our return object
    if(objData.views)
        viewsNode = SPAN({"class":"viewed"}, document.createTextNode(" (" + objData.views + " views)"));

    if(objData.thumbnail_url){
        thumbUrl = objData.thumbnail_url.split('.');
	    l = thumbUrl.length
        thumbUrl[l-2] = thumbUrl[l-2] + "_t160";
        thumbUrl = thumbUrl.join('.');
    }
    else
        thumbUrl = "http://media.scrippsnewspapers.com/corp_assets/assets/images/reel_large.png";

    return LI(null, [
        A({href: objData.content_url}, [
            IMG({src: thumbUrl, width: 156, height: 90, border: 0}),
            BR(null),
            document.createTextNode(objData.label)
        ]),
        [SPAN(null, document.createTextNode(truncate_words(objData.description, 7)))],
        [BR(null), ratingNode, viewsNode]
    ]);
}*/

function makeRatingNode(rating, objmode){
    if(!rating)
        rating = 0;

    if(rating > 5)
        rating = 5;

    //loop and push as many star img tags as we need.
    var ratingNode = null;
    var ratingstars = [];
    if(rating != null) {
        for(var i=0; i<rating; ++i) {
            if(rating-i == 0.5)  //we have a half rating, push half a star this time
                ratingstars.push(IMG({src: "http://media.scrippsnewspapers.com/corp_assets/assets/images/half_star.gif"}));
            else  //else push a whole star since we're still counting up to total score
                ratingstars.push(IMG({src: "http://media.scrippsnewspapers.com/corp_assets/assets/images/full_star.gif"}));
        }

        for(var i=0; i<5-Math.ceil(rating); ++i) {
            ratingstars.push(IMG({src: "http://media.scrippsnewspapers.com/corp_assets/assets/images/grey_star.gif"}));
        }
        
        ratingNode = SPAN({"class":"rating"}, ratingstars);
    }

    if(objmode)
        return ratingNode;                          //return the actual object created
    else
        return DIV(null,ratingNode).innerHTML;      //return HTML if not in objectMode,usefulin document.write situations
}

/**********************
for comments section
author: shawn therrien
***********************/
function toggleComments(self, elem) {
    toggleElementClass("invisible", elem);

    var titlebar = getFirstParentByTagAndClassName(self, "div", "titlebar");
    var h4tag = getFirstElementByTagAndClassName("h4", null, titlebar);
    var links = getElementsByTagAndClassName("a", null, titlebar);
    var commentText = h4tag.innerHTML.split(" ");    
    
    if( hasElementClass(elem, "invisible") ) {
        replaceChildNodes(links[1], "[+]");
        commentText[1] = "comment";
    }
    else {
        replaceChildNodes(links[1], "[-]");
        commentText[1] = "comments";
    }
    
    replaceChildNodes(h4tag, commentText.join(" "));

}

function toggleElementVisibility(elm){
    toggleElementClass("invisible", elm);
}

function get_rating(form, video_id) {
    for(var i=0; i<5; i++) {
        if(form.rating[i].checked) {
            var rating_value = form.rating[i].value;
        }
    }   
    var domain = document.location.hostname;
    var rate_url = "http://"+domain+"/metrics/rate/media/videos/"+ video_id +"/"+rating_value+"/";
    var req = doXHR(rate_url);
    req.addCallback(function(){
        alert("You rated this video: "+rating_value);
    });
    req.addErrback(function(err){
        if(err.req.status == 403) {
            //in case the ratings block doesn't get hidden, give a useful message
            alert("You'll need to be logged in to rate a video.");
        }
        else {
            //otherwise something is funkdafied
            alert("Experiencing technical difficulties, please try again later."); 
        }
    });
}

function truncate_words(str, words) {
    var split_str = str.split(" ");
    var new_str = [];

    for(var i = 0; i < words; i++)
        new_str.push(split_str[i]);

    if(split_str.length > words)
        return new_str.join(" ") + "...";
    else
        return str;
}

//possibly not needed anymore.  whole number rating calculated in ellington
/*function calculateRating(rcount, rtotal){
    var retVal = null;

    if(rcount && rtotal){
        var rAvg = Math.floor(rtotal / rcount);
        var rHalf = Math.ceil(((rtotal % rcount) / rcount) * 100);
        if(rHalf >= 40 && rHalf <= 60) rAvg += 0.5;
        if(rHalf >= 80) rAvg += 1;
        retVal = rAvg;
    }

    return retVal;
}*/
