// global flag
var isIE = false;

var autoplayfirstvideo = true;


// global request and XML document objects
var req;
var pagestoload;

// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadXMLDoc() {
	//kludge to deal with player issues
	$("#theupbutton").hide();
	if($("#firstclip").html() == "Nada"){	
		$("#myplaylist a:last").remove();
		$("#myplaylist a:last").remove();
		$("#myplaylist a:last").remove();
		$("#myplaylist a:last").remove();
	}
	url = pagestoload[0];
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

// handle onreadystatechange event of req object
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            //clearTopicList();
            buildTopicList();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }
}



// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method 
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided 
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
           if (result.childNodes.length > 0) {
            	return result.firstChild.nodeValue;
			} else {
				return "";
			}    		
        }
    } else {
        return "n/a";
    }
}



// fill Topics select list with items from
// the current XML document
function buildTopicList() {
	var thecontainer = req.responseXML.getElementsByTagName("container");
	var XMLfeedtype = $(thecontainer).attr('name');
	
    var items = req.responseXML.getElementsByTagName("item");
	
    // loop through <item> elements, and add each nested
    // <title> element to Topics select element	
	if(XMLfeedtype != "Discography") {
    	for (var i = 0; i < items.length; i++) {
			var artistname = getElementTextNS("", "video_artist_name", items[i], 0);
			var videoname = getElementTextNS("", "item_nme", items[i], 0);
			var videodesc = getElementTextNS("", "video_description", items[i], 0);
			var videourl = getElementTextNS("", "vidego_flv", items[i], 0);
			var videothumb = getElementTextNS("", "video_still_img", items[i], 0);
			newEntry(artistname, videoname, videodesc, videourl, videothumb);
			if ((i==0) && ($("#firstclip").html() == "Nada")){$("#firstclip").html(videourl);}
		}
	} else {
		var ProjectName = getElementTextNS("", "ProjectName", items[0], 0);
		var CoverArt = getElementTextNS("", "ProjectImage1URL", items[0], 0);
		var ArtistID = getElementTextNS("", "Artist_Id", items[0], 0);
		var tracklist = $(items);
		for (var i = 1; i < items.length; i++) {
			var TrackName = getElementTextNS("", "TrackName", items[i], 0);
			var TrackPath = getElementTextNS("", "MP3URL2", items[i], 0);
			//newEntry(ProjectName, TrackName, "", TrackPath, CoverArt);
			var tmp = TrackPath;
			var lastslash = tmp.lastIndexOf("/");
			var lastdot = tmp.lastIndexOf(".");
			var currclipname = tmp.substring(lastslash + 1, lastdot);
			if (i==1 && $("#firstclip").html() == "Nada"){$("#firstclip").html(TrackPath);}
			$("#myplaylist").append('<a href="' + TrackPath + '"> <img src="' + CoverArt + '"><strong>' + ProjectName + ': ' + TrackName +'</strong> </a>');	
			$("#mydata").append('<div class="stealthdiv" id="' + currclipname + '"  style="visibility:hidden;position:absolute;top:-5000px" title="' + ProjectName + ': ' + TrackName + '">' + CoverArt + '</div>');
			
		}
	}

       
	  
	   if (autoplayfirstvideo == true && $f("player").isLoaded() == false){
		   //alert($f("player").getVersion());
		   $f("player").load();
		   }
	if (pagestoload.length > 1) {
	//more XML to load
		pagestoload = pagestoload.slice(1);
		loadXMLDoc();
	}
}

/* adds new entry into playlist */
function newEntry(artistname, videoname, videodesc, videourl, videothumb) {
	// uses normal jQuery append method. no additional coding
	$("#myplaylist").append('<a href="' + videourl + '"> <img src="' + videothumb + '"><strong>' + videoname + '</strong> </a>');	
	var tmp = videourl;
	var lastslash = tmp.lastIndexOf("/");
	var lastdot = tmp.lastIndexOf(".");
	var currclipname = tmp.substring(lastslash + 1, lastdot);
	//alert(currclipname);
	$("#mydata").append('<div class="stealthdiv" id="' + currclipname + '"  style="visibility:hidden;position:absolute;top:-5000px" title="' + videoname + '">' + videodesc + '</div>');

		
}



// display details retrieved from XML document
function showDetail(evt) {
    evt = (evt) ? evt : ((window.event) ? window.event : null);
    var item, content, div;
    if (evt) {
        var select = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if (select && select.options.length > 1) {
            // copy <content:encoded> element text for
            // the selected item
            item = req.responseXML.getElementsByTagName("item")[select.value];
            content = getElementTextNS("content", "encoded", item, 0);
            div = document.getElementById("details");
            div.innerHTML = "";
            // blast new HTML content into "details" <div>
            div.innerHTML = content;
        }
    }
}


function mydownbuttonhandler() {
	var api = $("#pl").scrollable(); 
	api.movePage(1);
	//since I am cheating the scroll function to handle the double row, the calc below gives how many pages there really are
	var totalpages = ((api.getPageAmount() * 2)/8) - 1;
	if (api.getPageIndex() >= totalpages){
		$("#thedownbutton").hide();
	}
	$("#theupbutton").show();
}

function myupbuttonhandler() {
	var api = $("#pl").scrollable(); 
	api.movePage(-1);
	if (api.getPageIndex() == 0 ){
		$("#theupbutton").hide();
	}
	$("#thedownbutton").show();
}





