var chan_idx;
var play_idx;
var start_location;
var paused; 
var randsg;
var myseq = new Array();
var id_arr = new Array();
var title_arr = new Array();
var search_arr = new Array();
var tagArr_2 = new Array();
var my_referrer;
var start_index = 0;
var search_query = "";
var progress_int;
var total_played;
var total_len;
var total_loaded;
var total_byt;
var NewState;
var err;
var myxmlhttp;
var channel;
var oldState;
var channel_script;
var search_script;
var searched = false;
var zoom_state;
var TimeToFade = 1000;
var longer = 0;


var menu_title = new Array();
var menu_creator = new Array();
var menu_location = new Array();
var menu_info = new Array();
var menu_image = new Array();

menu_title[0] = "barrygioportmorien1";
menu_creator[0] = "Barry";
menu_location[0] = "barrygioportmorien1";
menu_info[0] = "http://www.youtube.com/barrygioportmorien1";
menu_image[0] = "barrygioportmorien1.jpg";

menu_title[1] = "Brent441";
menu_creator[1] = "Brent441";
menu_location[1] = "Brent441";
menu_info[1] = "http://www.youtube.com/Brent441";
menu_image[1] = "Brent441.jpg";

menu_title[2] = "dowopper51";
menu_creator[2] = "dowopper51";
menu_location[2] = "dowopper51";
menu_info[2] = "http://www.youtube.com/dowopper51";
menu_image[2] = "dowopper51.jpg";

menu_title[3] = "Una ventana al campo";
menu_creator[3] = "masanmar";
menu_location[3] = "masanmar";
menu_info[3] = "http://www.youtube.com/masanmar";
menu_image[3] = "masanmar.jpg";

menu_title[4] = "draadnagels";
menu_creator[4] = "Gerrie";
menu_location[4] = "draadnagels";
menu_info[4] = "http://www.youtube.com/draadnagels";
menu_image[4] = "draadnagels.jpg";

menu_title[5] = "gerrienails";
menu_creator[5] = "Gerrie";
menu_location[5] = "gerrienails";
menu_info[5] = "http://www.youtube.com/gerrienails";
menu_image[5] = "gerrienails.jpg";

menu_title[6] = "Christmas";
menu_creator[6] = "Santa";
menu_location[6] = "37D2886839FE4BD2";
menu_info[6] = "http://www.youtube.com/draadnagels";
menu_image[6] = "37D2886839FE4BD2.jpg";

menu_title[7] = "grandprix1963";
menu_creator[7] = "Anders";
menu_location[7] = "grandprix1963";
menu_info[7] = "http://www.youtube.com/grandprix1963";
menu_image[7] = "grandprix1963.jpg";

menu_title[8] = "loupi52";
menu_creator[8] = "loupi52";
menu_location[8] = "loupi52";
menu_info[8] = "http://www.youtube.com/loupi52";
menu_image[8] = "loupi52.jpg";

menu_title[9] = "ricknelson69";
menu_creator[9] = "ricknelson69";
menu_location[9] = "ricknelson69";
menu_info[9] = "http://www.youtube.com/ricknelson69";
menu_image[9] = "ricknelson69.jpg";

menu_title[10] = "Grandkids";
menu_creator[10] = "Mariska";
menu_location[10] = "kabouterspillebeen";
menu_info[10] = "http://www.youtube.com/kabouterspillebeen";
menu_image[10] = "kabouterspillebeen_1.jpg";

menu_title[11] = "Fats Domino";
menu_creator[11] = "Fats Domino";
menu_location[11] = "078C96EB9C6839F4";
menu_info[11] = "http://www.youtube.com/draadnagels";
menu_image[11] = "078C96EB9C6839F4.jpg";

menu_title[12] = "Jim Reeves";
menu_creator[12] = "Jim Reeves";
menu_location[12] = "4409522E149B8B9A";
menu_info[12] = "http://www.youtube.com/draadnagels";
menu_image[12] = "4409522E149B8B9A.jpg";

menu_title[13] = "Roy Orbison";
menu_creator[13] = "Roy Orbison";
menu_location[13] = "8EC41C3C279111AF";
menu_info[13] = "http://www.youtube.com/draadnagels";
menu_image[13] = "8EC41C3C279111AF.jpg";

menu_title[14] = "Swedish Chef";
menu_creator[14] = "Muppets";
menu_location[14] = "SwedishChefVideos";
menu_info[14] = "http://www.youtube.com/SwedishChefVideos";
menu_image[14] = "SwedishChefVideos.jpg";

menu_title[15] = "Tossa De Mar";
menu_creator[15] = "Draadnagel";
menu_location[15] = "417E29835AD38487";
menu_info[15] = "http://www.youtube.com/draadnagels";
menu_image[15] = "417E29835AD38487.jpg";

menu_title[16] = "Birds";
menu_creator[16] = "Draadnagel";
menu_location[16] = "775D6C4D199FEE89";
menu_info[16] = "http://www.youtube.com/draadnagels";
menu_image[16] = "775D6C4D199FEE89.jpg";

menu_title[17] = "Kijk Op Oisterwijk";
menu_creator[17] = "Jeroen";
menu_location[17] = "kijkopoisterwijk";
menu_info[17] = "http://www.youtube.com/kijkopoisterwijk";
menu_image[17] = "kijkopoisterwijk.jpg";

//menu_title[18] = "Philips museum";
//menu_creator[18] = "Philips";
//menu_location[18] = "51333B6CACEB85A3";
//menu_info[18] = "http://www.philipsmuseum.nl";
//menu_image[18] = "philipsmuseum.jpg";

//var el = document.createElement("iframe");
//el.setAttribute('id', 'ifrm');
//document.body.appendChild(el);
//el.setAttribute('src', 'http://www.google.com');

function URLEncode(decodedstring)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = decodedstring;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
			if (ch == " ") {
				encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
				encoded += ch;
		} else {
				var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
					alert( "Unicode Character '" 
												+ ch 
												+ "' cannot be encoded using standard URL encoding.\n" +
									"(URL encoding only supports 8-bit characters.)\n" +
							"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	 return	encoded;
}

function URLDecode(encodedstring)
{
	 // Replace + with ' '
	 // Replace %xx with equivalent character
	 // Put [ERROR] in output if %xx is invalid.
	 var HEXCHARS = "0123456789ABCDEFabcdef"; 
	 var encoded = encodedstring;
	 var plaintext = "";
	 var i = 0;
	 while (i < encoded.length) {
			 var ch = encoded.charAt(i);
		 if (ch == "+") {
				 plaintext += " ";
			 i++;
		 } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
			 plaintext += ch;
			 i++;
		}
	} // while
	 return plaintext;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function searchChannel(){
         //stop_yt();
         search_query = search_input.value;
         var invalids = "!@#$%^&*()-~,'<.>/?;:\|+ ";
         var search_len = search_query.length;
         for(k = 0; k < search_len; k++) {
              for(i = 0; i < invalids.length; i++) {
                  if (search_query.indexOf(invalids.charAt(i)) >= 0 ) {
                  search_query = search_query.replace(invalids.charAt(i), "");
                  }  
              }
         }
         for(i = 0; i < search_query.length; i++) {
             search_query = search_query.replace("\"", "");
         } 
         search_query = search_query.substring(0,20);
         if (search_query.length > 1){
             channel_script = document.createElement('script');
             channel_script.setAttribute('src', "http://gdata.youtube.com/feeds/users/" + search_query + "/uploads?format=5&alt=json-in-script&callback=channel_result&start-index=1&max-results=1");
             channel_script.setAttribute('id', 'mychannels');
             channel_script.setAttribute('type', 'text/javascript');
             document.documentElement.firstChild.appendChild(channel_script);
         }
}

function channel_result(data) {
         var feed = data.feed;
         var total_videos = feed.openSearch$totalResults.$t;
         channel = false;
         if (total_videos > 0) {
         //    channel = true;
         }
         setTimeout("searchVideos_start()",50);
}

function searchVideos_start(){
         search_query = search_input.value;
         var invalids = "!@#$%^&*()~,'<.>/?;:\|";
         var search_len = search_query.length;
         for(k = 0; k < search_len; k++) {
              for(i = 0; i < invalids.length; i++) {
                  if (search_query.indexOf(invalids.charAt(i)) >= 0 ) {
                  search_query = search_query.replace(invalids.charAt(i), "");
                  }  
              }
         }
         search_query = URLEncode(search_query);
         if (search_query.length > 1){
             search_arr.length = 0;
             start_index = 1;
             document.getElementById('info').style.visibility = "visible";
             document.getElementById('txtinfo').style.visibility = "visible";
             switch(channel){
             case true:
              for(i = 0; i < search_query.length; i++) {
                  search_query = search_query.replace("\"", "");
              } 
              break;
             case false:
              for(i = 0; i < search_query.length; i++) {
                  search_query = search_query.replace("\"", "%22");
              }
              break;
             }             
             searchVideos();
         }    
}

function search_result(data) {
         var feed = data.feed;
         var total_videos = feed.openSearch$totalResults.$t;
         var entries = feed.entry || [];
         for (var i = 0; i < entries.length; i++) {
              var entry = entries[i];
              var title = entry.title.$t;
              var tmp_len = entry.link.length;
              for (var k = 0; k < tmp_len; k++) {
	               if (entry.link[k].rel == 'alternate') {
	                   url = entry.link[k].href;
	                   break;
	               }
	          }
              var match = url.lastIndexOf('?v=');
              id = url.substring(match+3,match+14);
	          var already = false;
              il = search_arr.length;
              for (var n=0; n<il; n++) {
	               if (title+id == search_arr[n]){
                       already = true;
                       break;
	               }
	          }
              if (already == false){
                  search_arr.push(title + id);
                  }
         }
         if (entries.length == 50){
             start_index = start_index + 50; 
             searchVideos();
         }    
         if (entries.length != 50){
             if (search_arr.length > 0) {
                 search_arr.sort();
                 searched = true;
                 id_arr.length = 0;
                 title_arr.length = 0;
                 il = search_arr.length;
                 var p = 0;
                 for (var k=0; k<il; k++) {
                      p = search_arr[k].length-11; 
                      title_arr.push(search_arr[k].substring(0,p));
                      id_arr.push(search_arr[k].substring(p));
                 }
                 
                 showTags_2();
                 myseq.length = 0;         
                 choose_random_video();
             }    
             if (search_arr.length == 0) {
                 alert("No search results");
             } 
         }    
}

function searchVideos(){
         if (search_query.length > 1){
             search_script = document.createElement('script');
             switch(channel){
             case true:
              var tmp_url = 'http://gdata.youtube.com/feeds/users/' + search_query + '/uploads?prettyprint=true&format=5&alt=json-in-script&callback=search_result&start-index='+start_index+'&max-results=50';
              search_script.setAttribute('src', tmp_url);
              break;
             case false:
              var tmp_url = 'http://gdata.youtube.com/feeds/videos?q=' + search_query + '&prettyprint=true&format=5&alt=json-in-script&callback=search_result&start-index='+start_index+'&max-results=50';
              search_script.setAttribute('src', tmp_url);
              break;
             }             
             search_script.setAttribute('id', 'jsonScript');
             search_script.setAttribute('type', 'text/javascript');
             document.documentElement.firstChild.appendChild(search_script);
         }
}

function load_xml(start_up,my_ref) {
         BrowserDetect.init();
         if (BrowserDetect.browser != "Explorer"){
             longer = 2;
             main.className = 'main_';
             playlistbox.className = 'playlistbox_';
//           ytapiplayer.className = 'ytapiplayer_';
             listroot.className = 'listroot_';
             listhandle.className = 'listhandle_';
             ctrl_listroot.className = 'ctrl_listroot_';
             songs_listroot.className = 'songs_listroot_';
             play_bar.className = 'play_bar_';
             byte_bar.className = 'byte_bar_';
             bar_1.className = 'bar_1_';
             bar_2.className = 'bar_2_';
             search_box.className = 'search_box_';
             search_input.className = 'search_input_';
             search_button.className = 'search_button_';
         }
         my_referrer = my_ref;
         start_location = start_up;
         chan_idx = -1;
         searched = false;
         show_Channels();
         if (start_location == "random") {
             randsg = Math.floor(Math.random()*(menu_title.length-1));
         }
         if (start_location != "random") {
             il = menu_title.length;
             for (i=0; i<il; i++) { 
                  if (menu_location[i] == start_location){
                     randsg = i;
                     break;
                 }
             }
         }
         chan_idx = randsg;
         document.getElementById(chan_idx).className = "playlistnow"
         document.getElementById(chan_idx).scrollIntoView(true);
         setTimeout("create_apiplayer()",50);
  //     importXML("tubebox");
}

function checkEnter(e){ //e is event object passed from function invocation
         var characterCode;

         if(e && e.which){ //if which property of event object is supported (NN4)
            e = e
            characterCode = e.which //character code is contained in NN4's which property
         }
         else{
         e = event
         characterCode = e.keyCode //character code is contained in IE's keyCode property
         }

         if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
            searchChannel();

           return false 
         }
         else{
         return true 
         }
}

function loadTXTDoc(url){
         myxmlhttp=null;
         if (window.XMLHttpRequest){
             myxmlhttp=new XMLHttpRequest();
         }
        else if (window.ActiveXObject){
         myxmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (myxmlhttp!=null){
            myxmlhttp.onreadystatechange = state_Change;
            myxmlhttp.open("GET",url + '.txt',true);
            myxmlhttp.send(null);
        }
         else{
          alert("Your browser does not support XMLHTTP.");
        }
}

function state_Change(){
         if (myxmlhttp.readyState==4){
             if (myxmlhttp.status==200){
                 arr_videos = myxmlhttp.responseText.split("\r\n");
                 id_arr.length = 0;
                 title_arr.length = 0;
                 il = arr_videos.length-1;
                 var p = 0;
                 for (var k=0; k<il; k++) {
                      p = arr_videos[k].length-11; 
                      title_arr.push(arr_videos[k].substring(0,p));
                      id_arr.push(arr_videos[k].substring(p));
                 }
                 arr_videos.length = 0;
                 showTags_2();
                 myseq.length = 0;
                 choose_random_video();
             }
             else{
             alert("Problem retrieving data:" + myxmlhttp.statusText);
             }
         }
}

function load_xml_2(xml_url) {
         loadTXTDoc(xml_url)         
    //   importXML(xml_url);
}

function choose_random_video() {
         var ran = 0;
         if(myseq.length == 0) {
            var il = id_arr.length; 
            var tmpseq_1 = new Array();
            var tmpseq_2 = new Array();
            for (var k=0; k<il; k++) {
	            tmpseq_1.push(k);
		    }
            for (var k=0; k<il; k++) {
                ran = Math.floor(Math.random()*(tmpseq_1.length-1));
	            tmpseq_2.push(tmpseq_1[ran]);
	            tmpseq_1.splice(ran,1);
            }
            for (var k=0; k<il; k++) {
                ran = Math.floor(Math.random()*(tmpseq_2.length-1));
                myseq.push(tmpseq_2[ran]);
                tmpseq_2.splice(ran,1);
            }
            tmpseq_1.length = 0;
            tmpseq_2.length = 0;
	     } 
         if (start_location != "draadnagels") {
            my_referrer = ""; 
         }
         if (my_referrer != '') {
         //     var my_pos = my_referrer.indexOf("/watch?v=");
         //     my_referrer = my_referrer.substring(my_pos + 9,my_pos + 20);
            for (var k=0, il=id_arr.length; k<il; k++) {
                 if (id_arr[k] == my_referrer) {
                     play_idx = k;
                     break;
                 }
		    }
         //    if (my_pos == -1) {
         //        ran = Math.round(Math.floor(Math.random()*((myseq.length-1) *128))/128);
	     //        play_idx = myseq[ran];
		 //        myseq.splice(ran,1);
         //    }
         }
         if (my_referrer == '') {
           ran = Math.round(Math.floor(Math.random()*((myseq.length-1) *128))/128);
           play_idx = myseq[ran];
           myseq.splice(ran,1);
         }
         play_video(play_idx);
}

function play_video(idx) {
         play_idx = idx;
         if (play_idx != undefined){
             document.getElementById('s_' + play_idx).className = "songlistnow";
             document.getElementById('s_' + play_idx).scrollIntoView(true);
             try{
              ytplayer.clearVideo;   
              ytplayer.loadVideoById(id_arr[play_idx],0,"large");
             } catch (err){} 
         }
         if (play_idx == undefined){
             try{
              ytplayer.loadVideoById(my_referrer,0,"large");
             } catch (err){} 
             
         }
         my_referrer = ""; 
}

function trim(value) {
         value = value.replace(/^\s+/,''); 
         value = value.replace(/\s+$/,'');
         return value;
}

function xmlDocReady() {
    if (tagArr.length != 0) { 
        tagArr_2.length = 0;
        storeTags_2();
        id_arr.length = 0;
        title_arr.length = 0;
        var il = tagArr_2.length;
        for (var k=0; k<il; k++) {
             id_arr.push(tagArr_2[k][0]);
             title_arr.push(tagArr_2[k][1]);
             }
        showTags_2();
        myseq.length = 0;
        choose_random_video();
    }
    if (tagArr.length == 0) {	
      	storeTags_1();
    	show_Channels();
    	if (start_location == "random") {
            randsg = Math.floor(Math.random()*(tagArr.length-1));
        }
        if (start_location != "random") {
            il = tagArr.length;
  	     	for (i=0; i<il; i++) { 
  		        if (tagArr[i][0] == start_location){
                    randsg = i;
    		            break;
    		    }
    		}
        }
        chan_idx = randsg;
        document.getElementById(chan_idx).className = "playlistnow"
        document.getElementById(chan_idx).scrollIntoView(true);
        setTimeout("create_apiplayer()",50);
  	}
}

function onmouse_out(idx,this_1) {
         this_1.className = "playlistlo"    
         if (idx == chan_idx) {
             this_1.className = "playlistnow";
         }   
}

function onmouse_out_2(idx,this_1) {
        this_1.className = "songlistlo";
        if (idx == play_idx) {
            this_1.className = "songlistnow";
        }   
}

function asImage(url, w, h, b, txt, i) { 
    var tmp = "<img src=\"" + url + "\""; 
        tmp += " style=cursor:pointer width=\"" + w + "\"";
        tmp += " height=\"" + h + "\"";
        tmp += " border=\"" + b + "\"";
        tmp += " alt=\"" + txt + "\"";
        tmp += " onclick=\"" + 'change(' + i + ');' + "\"";
        tmp += ">"; 
    return(tmp);
}

function asCell(txt) { 
    var tmp = "<td nowrap>" + txt + "</td>";
    return(tmp);
}

function asLink(url, trgt, txt) { 
    var tmp = "<a href=\"" + url + "\"";
        tmp += "target=\"" + trgt + "\">"; 
        tmp += txt + "</a>"; 
    return(tmp);
}

function show_Channels() {
         var arLen = menu_title.length;
         var txt='<table style="cursor:default" cellPadding="0" align="left">';     
         for (var i=0; i<arLen; i++) {
              if (menu_title[i] != "Christmas"){
                  txt+='<tr><td><table width="220" ';
                  txt+='class="playlistlo" id="' + i + '" onmouseover="this.className = \'playlisthi\';" onmouseout="onmouse_out(' + i +',this);">';
                  txt+='<tr>' + asCell(asImage(menu_image[i], "85", "68", "1", "Click on picture to play", i));
                  txt+='<td width="135" valign=middle><b>';
                  txt+='&nbsp;' + menu_title[i] + '<br>';
                  txt+='&nbsp;by: ' + menu_creator[i] + '<br>';
                  txt+='&nbsp;' + asLink(menu_info[i], "_blank", "more info");
                  txt+='</b></td></tr></table></td></tr>';
              }
         }
         txt+='</table>';
         document.getElementById("playlistbox").innerHTML=txt;    
}


function showTags_2() {
         var parent = document.getElementById("songs_writeroot");
         while(parent.hasChildNodes()){
               parent.removeChild(parent.firstChild);
         }
         var width_bar = 698 + longer;
         var arLen = title_arr.length;
         if (arLen < 3){
             width_bar = 714 + longer;
         }         
         var txt='<div style="cursor:default">';
         for (var i=0; i<arLen; i++) {
              txt+='<tr><td><table width="' + width_bar + '" height="22" ';
              txt+='class="songlistlo" id="s_' + i + '" onmouseover="this.className = \'songlisthi\';" onmouseout="onmouse_out_2(' + i +',this);">';
              txt+='<tr><td onclick="play_video(' + i + ')" width="' + (width_bar-100) + '"><b>' + title_arr[i].replace('\\u0026','&') + '</b>'; 
              txt+='</td><td onclick="play_video(' + i + ')"><b>click to play</b></td></tr></table></td></tr>';
         }
         txt+='</div>';         
         document.getElementById("songs_writeroot").innerHTML=txt;
         document.getElementById('info').style.visibility = "hidden";
         document.getElementById('txtinfo').style.visibility = "hidden";
}

function change(idx) {
         if (idx != chan_idx || searched == true){
             searched = false;
             document.getElementById(chan_idx).className = "playlistlo"
             chan_idx = idx;
             document.getElementById(chan_idx).className = "playlistnow"
             clearInterval(progress_int);
  	    	 stop_yt();
             document.getElementById('info').style.visibility = "visible";
             document.getElementById('txtinfo').style.visibility = "visible";
             tagArr_2.length = 0;          
             var f = function() {load_xml_2(menu_location[idx]);};
             setTimeout(f, 50);
  	     }
}

function delayed_choose_random_video(){
         choose_random_video();
}

function onPlayerError(errorCode) {
      // alert(errorCode);
         setTimeout("delayed_choose_random_video()",2000);
}

function onytplayerStateChange(newState) {
         if (newState != oldState){
             if (newState == 2) {
                 document.getElementById('vcr_play').style.visibility = 'visible';
                 document.getElementById('vcr_pause').style.visibility = 'hidden';
             }
             if (newState == 1) {
                 progress_int = setInterval(updateytplayerInfo, 500);
                 document.getElementById('vcr_play').style.visibility = 'hidden';
                 document.getElementById('vcr_pause').style.visibility = 'visible';
             }
             if (newState == 0) {
                 document.getElementById('vcr_play').style.visibility = 'visible';
                 document.getElementById('vcr_pause').style.visibility = 'hidden';
                 document.getElementById('bar_1').style.width = 0 + 'px';
                 document.getElementById('bar_2').style.width = 0 + 'px';
                 clearInterval(progress_int);
                 choose_random_video();
                 }
         }
         oldState = newState;
}

function fade(eid)
{
  var element = document.getElementById(eid);
  if(element == null)
    return;
   
  if(element.FadeState == null)
  {
    if(element.style.opacity == null 
        || element.style.opacity == '' 
        || element.style.opacity == '1')
    {
      element.FadeState = 2;
    }
    else
    {
      element.FadeState = -2;
    }
  }
    
  if(element.FadeState == 1 || element.FadeState == -1)
  {
    element.FadeState = element.FadeState == 1 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
  }
  else
  {
    element.FadeState = element.FadeState == 2 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade;
    setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
  }  
}

function animateFade(lastTick, eid)
{  
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;
  
  var element = document.getElementById(eid);
 
  if(element.FadeTimeLeft <= elapsedTicks)
  {
    element.style.opacity = element.FadeState == 1 ? '1' : '0';
    element.style.filter = 'alpha(opacity = ' 
        + (element.FadeState == 1 ? '100' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    return;
  }
 
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;

  element.style.opacity = newOpVal;
  element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
  
  setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}


function onYouTubePlayerReady(playerId) {
         if (playerId == "ytplayer") {
             document.getElementById('merryxmas').style.visibility = "hidden";
             document.getElementById('ytapiplayer').style.visibility = "visible";
             ytplayer = document.getElementById("ytapiplayer"); 
             ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
             ytplayer.addEventListener("onError", "onPlayerError");
             unMute();
             setVolume(100);
             document.getElementById('info').style.visibility = "visible";
             document.getElementById('txtinfo').style.visibility = "visible";
             var f = function() {load_xml_2(menu_location[randsg]);};
             setTimeout(f, 50);
       	 }
}

function create_apiplayer() {
         var params = { allowScriptAccess: "always",bgcolor: "#000000"};
         var atts   = { id: "ytapiplayer"};
         var vars   = { el: ""};
         swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer","ytapiplayer",
                             "100%", "100%", "9", null, null, params, atts);
}

function getPlayerState() {
         if (ytplayer) {
            return ytplayer.getPlayerState();
         }
}

function dbl_click(){
        // document.getElementById('s_' + play_idx).scrollIntoView(true);
         ytplayer.loadVideoById("MP0gnfmTVl0",0,"large");
}

function dbl_click_zoom(){
         alert(ytplayer.getAvailableQualityLevels()); 
}

function setytplayerState(newState) {
//
}
        
function updateytplayerInfo() {
         total_byt = parseInt(getBytesTotal());
         if (total_byt > 0) {
             total_loaded = parseInt(getBytesLoaded()/(total_byt/100)*6.5);
             if (total_loaded >= 649) {
                 total_loaded = 650;
             }
         document.getElementById('bar_2').style.width = total_loaded + 'px';
         }   
         total_len = parseInt(get_Duration());
         if (total_len > 0) {
             total_played = parseInt(getCurrentTime()/(total_len/100)*6.5);
             if (total_played >= 649) {
                 total_played = 650;
                 return
             }
         document.getElementById('bar_1').style.width = total_played + 'px';
         }
}

function play_yt() {
         if (ytplayer) {
             if (paused == false){
                 play_video(play_idx); 
             }
             if (paused == true){
                 paused = false;
                 ytplayer.playVideo();
             }
         }
}

function pause_yt() {
         if (ytplayer) {
             paused = true;
             ytplayer.pauseVideo();
             }
}

function stop_yt() {
         if (ytplayer) {
             paused = false;
             ytplayer.stopVideo();
         }
}

function rewind_yt() {
          if (ytplayer) {
              play_idx--;
              if (play_idx < 0){
                  play_idx = (id_arr.length-1);
                  }
              play_video(play_idx);    
          }
}

function forward_yt() {
          if (ytplayer) {
              play_idx++;
              if (play_idx > (id_arr.length-1)){
                  play_idx = 0;
                  }
              play_video(play_idx);    
           }
}

function getBytesLoaded() {
          if (ytplayer) {
            return ytplayer.getVideoBytesLoaded();
          }
}

function getBytesTotal() {
          if (ytplayer) {
            return ytplayer.getVideoBytesTotal();
          }
}

function getCurrentTime() {
          if (ytplayer) {
            return ytplayer.getCurrentTime();
          }
}

function get_Duration() {
          if (ytplayer) {
            return ytplayer.getDuration();
          }
}

function getStartBytes() {
          if (ytplayer) {
            return ytplayer.getVideoStartBytes();
          }
}

function mute() {
          if (ytplayer) {
            ytplayer.mute();
          }
}

function unMute() {
          if (ytplayer) {
            ytplayer.unMute();
          }
}
        
function getEmbedCode() {
          alert(ytplayer.getVideoEmbedCode());
}

function getVideoUrl() {
          alert(ytplayer.getVideoUrl());
}
        
function setVolume(newVolume) {
          if (ytplayer) {
            ytplayer.setVolume(newVolume);
          }
}

function getVolume() {
          if (ytplayer) {
            return ytplayer.getVolume();
          }
}

function clearVideo() {
          if (ytplayer) {
            ytplayer.clearVideo();
          }
}

function seekTo(seconds) {
          if (ytplayer) {
            ytplayer.seekTo(seconds, true);
          }
}
