var TRUNCATION_STRING = "...";
var videos;

var youTubeFeeds = new Array();
youTubeFeeds.push(new Array("Top Rated", "http://gdata.youtube.com/feeds/api/users/xsimbanner/favorites?v=2"));



function init(){
    // attach "powered by Google" branding
    GSearch.getBranding(document.getElementById("yt-branding"), GSearch.HORIZONTAL_BRANDING, "http://www.youtube.com");

    ytselect = document.createElement("select");
    ytselect.onchange= function(){showList(); fetchFeed(this.options[this.selectedIndex].value);}

    for(i=0;i<youTubeFeeds.length;i++){
    	ytOption=document.createElement("option");
        ytText=document.createTextNode(youTubeFeeds[i][0]);
        ytOption.setAttribute("value",youTubeFeeds[i][1]);
        ytOption.appendChild(ytText);
        ytselect.appendChild(ytOption);
    }

    document.getElementById("yt-youtubefeeds").appendChild(ytselect);
    fetchFeed(youTubeFeeds[0][1]);
}

function counti(){
	//var p = p + i;
	var i = i + 4;
	setTimeout("counti()", 100);
	//return "test";
}


function fetchFeed(url, pc1){
//function fetchFeed(url){

//return time;

/*if (pc == 0) {
var  pc = 0;
}else{
var pc = pc + 4;
}*/



    var feed = new google.feeds.Feed(url);
    feed.setNumEntries(100);
    feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
    feed.load(function(result) {
        if (!result.error) {
            videos = new Array();
			//var timing = setTimeout("i + 4", 100); //RHE ne timeer function for linear mode
            //for (var i = 0; i < result.feed.entries.length; i++) {
			//pc = pc1;
			for (i = 0; i < result.feed.entries.length; i++) {
                var video = new Object();
                var entry = result.feed.entries[i];
                var content = google.feeds.getElementsByTagNameNS(entry.xmlNode, "http://search.yahoo.com/mrss/", "content")[0];					    
                var thumbnail = google.feeds.getElementsByTagNameNS(entry.xmlNode, "http://search.yahoo.com/mrss/", "thumbnail")[0];
                var title = entry.xmlNode.getElementsByTagName("title")[0];
                var duration = google.feeds.getElementsByTagNameNS(entry.xmlNode, "http://gdata.youtube.com/schemas/2007", "duration")[0];

                if(content) {
                    var cUrl = content.getAttribute("url");
                    video.swf = cUrl;
                }	
                if (thumbnail) {
                    var tUrl = thumbnail.getAttribute("url");
                    video.thumbnail = tUrl;
                }
                if (title) {
                    video.title = getXmlNodeText(title);
                }
                if (duration) {
                    video.duration = duration.getAttribute("seconds");
                }
                videos.push(video);
            }
            var searchresults = document.getElementById("yt-searchresults");
            clearElement(searchresults);
            for (i = 0; i < videos.length; i++) {
                video = videos[i];

                var thumb = document.createElement("img");
                thumb.className = "thumb";
                thumb.src = video.thumbnail;
                thumb.title = video.title;

                var span = document.createElement("span");
                span.className = "thumbSpan";
                span.appendChild(thumb);

                var titleDiv = document.createElement("div");
                title = document.createTextNode(truncate(video.title, 15));
                titleDiv.className = "browseitemtitle";
                titleDiv.appendChild(title);

                var durationDiv = document.createElement("div");
                duration = document.createTextNode("" + renderDuration(video.duration));
                durationDiv.className = "browseitemduration";
                durationDiv.appendChild(duration);

                var link = document.createElement("a");
                link.setAttribute("href","javascript:void(0)");
                link.onclick = playfunction(i);
                link.appendChild(span);

                var slot = document.createElement("div");
                if (i%4000 == 0){
                    slot.className = "slot end";
		} else {
                    slot.className = "slot";
		}
                slot.appendChild(link);
                /*slot.appendChild(titleDiv);*/
                /*slot.appendChild(durationDiv);*/

                searchresults.appendChild(slot);
            }
            new Pager('yt-searchresults', 5, 'slot', 'div' ,'yt-pageNavPosition');
	    showList();            
        }
    });
	
		/*if (!pc) {
		pc1 = 0;
		}else{
		pc1 = pc + 6;
		}*/
		
	    //pc1 = pc1 + 4;
		//setTimeout("fetchFeed('http://gdata.youtube.com/feeds/api/users/xsimbanner/favorites?v=2', pc1)", 2000); //RHE neue timer function for linear mode
}

function clearElement(el) {
    while(el.firstChild) {
        el.removeChild(el.firstChild);
    }
}

// approximate char width, based on code used in AdWords (awCreateAdUtil)
function charWidth(ch) {
    if (ch <= '\u04f9' ||
        ch == '\u05be' ||
        (ch >= '\u05d0' && ch <= '\u05ea') ||
        ch == '\u05F3' ||
        ch == '\u05f4' ||
        (ch >= '\u0e00' && ch <= '\u0e7f') ||
        (ch >= '\u1e00' && ch <= '\u20af') ||
        (ch >= '\u2100' && ch <= '\u213a') ||
        (ch >= '\uff61' && ch <= '\uffdc')) {
        return 1;
    }
    return 2;
}

function truncateByWidth(string, maxLen) {
    var count = 0;
    var truncated = "";
    for (var i = 0; i < string.length && count < maxLen; i++) {
        var character = string.substr(i, 1);
        truncated += character;
        count += charWidth(character);
    }
    return truncated;
}

// Truncate string to maxLen, in number of half-width (latin) characters.
//   CJK and other languages include characters that are wider
//   than standard latin characters, so we need to take this into account.
function truncate(string, maxLen) {
    if (displayLength(string) > maxLen) {
        string = truncateByWidth(string, maxLen - TRUNCATION_STRING.length);
        string += TRUNCATION_STRING;
    }
    return string;
}

function displayLength(string) {
    var count = 0;
    for (var i = 0; i < string.length; i++) {
        var character = string.substr(i, 1);
        count += charWidth(character);
    }
    return count;
}

function renderDuration(duration) {
    minutes = Math.floor(duration / 60);
    seconds = (duration % 60) + "";
    seconds = seconds.substr(0, 2);
    if (seconds.length == 0) {
        seconds = "00";
    } else if (seconds.length == 1) {
        seconds = "0" + seconds;
    }
    return minutes + ":" + seconds;
}

// XML DOM helper
function getXmlNodeText(node) {
    if (node.text) {
        // ie
        return node.text;
    } else if (node.textContent) {
        // firefox
        return node.textContent;
    } else if (node.firstChild && node.firstChild.nodeValue) {
        // safari
        return node.firstChild.nodeValue;
    } else {
        return "";
    }
}

function playfunction(idx){
    return function () {
	play(idx);
    }
}

function play(idx){
    hideList();        
    if (idx < 0) {
        idx = videos.length - 1;
    } else {
        idx = idx % videos.length;
    }
    document.getElementById("yt-videoP").onclick = function(){play( idx-1 )};
    document.getElementById("yt-videoN").onclick = function(){play( idx+1 )};	
    var videoDetails = document.getElementById("yt-videoDetails");		
    clearElement(videoDetails);
    
    var b1 = document.createElement("b");
    b1.appendChild(document.createTextNode("Title: " + videos[idx].title));
    var b2 = document.createElement("b");
    b2.appendChild(document.createTextNode("Time: " + renderDuration(videos[idx].duration)));
	
    videoDetails.appendChild(b1);
    videoDetails.appendChild(document.createElement("br"));
    videoDetails.appendChild(b2);			

    var params = { allowScriptAccess: "always" };
    var atts = { id: "yt-player" };
    swfobject.embedSWF(videos[idx].swf, 
    "yt-player", "499px", "344px", "8", null, null, params, atts);
}

function hideList(){
    document.getElementById("yt-selectioncontainer").style.display = "none";
    document.getElementById("yt-backNav").style.display = "block";
    document.getElementById("yt-playercontainer").style.display = "block";        
}

function showList(){
    document.getElementById("yt-selectioncontainer").style.display = "block";
    document.getElementById("yt-backNav").style.display = "none";
    document.getElementById("yt-playercontainer").style.display = "none";        
}

google.load("search", "1");
google.load("feeds", "1");
GSearch.setOnLoadCallback(init);

