// global flag
var isIE = false;

var autoplayfirstvideo = false;

var videolistloaded = false;
// 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();
	$("#theupbutton2").hide();
	//if($("#firstclip").html() == "Nada"){	
		$("#myplaylist a:last").remove();
		$("#myplaylist a:last").remove();
		$("#myplaylist a:last").remove();
		$("#myplaylist a:last").remove();
		//$("#myplaylist2 a:last").remove();
		//$("#myplaylist2 a:last").remove();
		//$("#myplaylist2 a:last").remove();
		//$("#myplaylist2 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);
			var currcount = parseInt($("#totalclips").html());
			$("#totalclips").html((currcount + 1));
			var currFirst = $("#firstclip").html()
			//if (currFirst.IsNullOrEmpty() == false) { 
//				if ((currFirst == "Nada") || (currFirst.indexOf(".mp3") > -1)){$("#firstclip").html(videourl);}
//			}
		}
		if (i == 0) { $("#myvideoplaylist").append("There are currently no videos available for this artist"); }
	} else {
		var currCollapse = 0;
		var isOpen = false;
		var divstring = "";
		for (var i = 0; i < items.length; i++) {
			var ProjectName = getElementTextNS("", "ProjectName", items[i], 0);
			if (ProjectName != "n/a") {
				// item is an album
				
				//figure out if we need to close a collapse...
				if (isOpen){
					divstring += "</div></div>";
					alert(divstring)
					$("#myplaylist2").append(divstring);
					divstring = "";
				}
				
				var CoverArt = getElementTextNS("", "ProjectImage1URL", items[i], 0);
				var ArtistID = getElementTextNS("", "Artist_Id", items[i], 0);
				var dlalbum = getElementTextNS("", "amazon_digital", items[i], 0);
				var buyalbum = getElementTextNS("", "amazon_id", items[i], 0);
				divstring += '<div class="albums"> <table width="100%"><tr><td> <img src="' + CoverArt + '"></td><td class="playlist_copy"><strong>' + ProjectName + '</strong>';
				
				if (buyalbum != "") { 
					divstring += "<br><img src='images/buynow.jpg' onclick=";
					divstring += '"window.open(';
					divstring +=  "'http://www.amazon.com/gp/product/" + buyalbum + "?ie=UTF8&tag=heitfi-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=" + buyalbum + "');";
					divstring += '" />';
				}
				if (dlalbum != "") { 
					divstring += "<br><img src='images/dlnow.jpg' onclick=";
					divstring += '"window.open(';
					divstring +=  "'http://www.amazon.com/gp/product/" + dlalbum + "?ie=UTF8&tag=heitfi-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=" + dlalbum + "');";
					divstring += '" />';
				}
				
				divstring +='</td></tr></table></div> ';
				//alert(divstring);
				//$("#myplaylist2").append(divstring);
				var currProjectname = ProjectName;
				var currCoverArt = CoverArt;
				//add in spry controls
				
				currCollapse++;
				
				divstring += "<div id='CollapsiblePanel" + currCollapse + "' class='CollapsiblePanel'><div class='CollapsiblePanelTab' tabindex='0'>View Tracks</div><div class='CollapsiblePanelContent'>";
				//alert(divstring);
				//$("#myplaylist2").append(divstring);
				isOpen = true;
				
			} else {
				//item is a track	
				var TrackName = getElementTextNS("", "TrackName", items[i], 0);
				var TrackPath = getElementTextNS("", "MP3URL2", items[i], 0);
				var dltrack = getElementTextNS("", "amazon_digital_track", items[i], 0);
				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);}
				
				divstring += '<a href="' + TrackPath + '" ><strong>' + TrackName +'</strong>';	
				if (dltrack != "") { 
					divstring += "<br><img src='images/dlnow.jpg' onclick=";
					divstring += '"window.open(';
					divstring +=  "'http://www.amazon.com/gp/product/" + dltrack + "?ie=UTF8&tag=heitfi-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=" + dltrack + "');";
					divstring += '" />';
				}
				divstring += "</a>";
				//alert(divstring);
				//$("#myplaylist2").append(divstring);	
				
				$("#mydata").append('<div class="stealthdiv" id="' + currclipname + '"  style="visibility:hidden;position:absolute;top:-5000px" title="' + currProjectname + ': ' + TrackName + '">' + currCoverArt + '</div>');
				var currcount = parseInt($("#totalclips").html());
				$("#totalclips").html((currcount + 1));
				if (i==2 &&  $("#SecondAudio").html() == "Nada") {
					//alert($("#totalclips").html());
					$("#SecondAudio").html($("#totalclips").html());
				};
			}
			
		
			var tracklist = $(items);
			
			//newEntry(ProjectName, TrackName, "", TrackPath, CoverArt);
			
			
		}
		divstring += "</div></div>";
		//alert(divstring);
		$("#myplaylist2").append(divstring);
	}

       videolistloaded = true;
  
   if (autoplayfirstvideo == true && $f("player").isLoaded() == false){
	   //alert($f("player").getVersion());
	   $f("player").load();
	   }
	
	if ($("#ctl00_ContentPlaceHolder1_discog_item_div").html() != "" && $f("player").isLoaded() == false) {
		 $f("player").load();
		 playalbum($("#ctl00_ContentPlaceHolder1_discog_item_div").html());
		 showtracks($("#ctl00_ContentPlaceHolder1_discog_item_div").html());
		 document.getElementById("CPC" + $("#ctl00_ContentPlaceHolder1_discog_item_div").html()).style.display = 'block';
	}
	
	if (pagestoload.length > 1) {
	//more XML to load
		pagestoload = pagestoload.slice(1);
		loadXMLDoc();
	}
}


/* plays the first video clip*/

function videoiconclick() {
	if ($f("player").isLoaded() == false){
	   //alert($f("player").getVersion());
	   $f("player").load();
	 } else {
		var currPL = $("#myvideoplaylist").children();
		if (currPL.length > 0) {
			var firsturl = currPL[0].attributes["href"].nodeValue;
			$f("player").play(firsturl); 
		}
	 }
}

/*opens the first dropdown and starts the first audio track*/

function audioiconclick() {
	
	document.getElementById("CPC0").style.display = 'block';
	var grabthetext = document.getElementById("CPE0").innerHTML;
	var hrefloc = grabthetext.indexOf("http:");
	var mp3loc = grabthetext.indexOf(".mp3");
	var currclipname = grabthetext.substring(hrefloc, mp3loc + 4);
	//alert(currclipname);
	$f("player").play(currclipname); 
	
}

function playalbum(curralbum) {
	var currbodname = "CPC" + 	curralbum;
	var grabthetext = document.getElementById(currbodname).innerHTML;
	var hrefloc = grabthetext.indexOf("http:");
	var mp3loc = grabthetext.indexOf(".mp3");
	var currclipname = grabthetext.substring(hrefloc, mp3loc + 4);
	$f("player").play(currclipname); 
}


/* adds new entry into playlist */
function newEntry(artistname, videoname, videodesc, videourl, videothumb) {
	// uses normal jQuery append method. no additional coding
	//alert("in new entry");
	var stringToAppend = '<a href="' + videourl + '">';
	//$("#myvideoplaylist").append('<a href="' + videourl + '">');
	//$("#myvideoplaylist").append('<table width="100%"><tr><td>');
	stringToAppend += '<table width="100%" height="100%"><tr><td valign="middle">';
	
	
	if (videothumb.lastIndexOf("vidego.multicastmedia.com") > 0) {
		//$("#myvideoplaylist").append('<img src="' + videothumb + '">');
		stringToAppend += '<img src="' + videothumb + '">';
	} else {
		//$("#myvideoplaylist").append('<img src="http://www.hearitfirst.com/images/uploads/music_videos/' + videothumb + '">');
		stringToAppend += '<img src="http://www.hearitfirst.com/images/uploads/music_videos/' + videothumb + '">';
	}
	
								 
	//$("#myvideoplaylist").append('</td><td class="playlist_copy">' + videoname + '</td></tr></table> </a>');	
	stringToAppend += '</td><td class="playlist_copy">' + videoname + '</td></tr></table> </a>';
	$("#myvideoplaylist").append(stringToAppend);
								 
	var tmp = videourl;
	var lastslash = tmp.lastIndexOf("/");
	var lastdot = tmp.lastIndexOf(".");
	var currclipname = tmp.substring(lastslash + 1, lastdot);
	//alert(currclipname);
	$("#ctl00_ContentPlaceHolder1_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 = $("#myplaylist").scrollable(); 
	api.movePage(1);
	var totalpages = api.getPageAmount()  - 1;
	if (api.getPageIndex() >= totalpages){
		$("#thedownbutton").hide();
	}
	$("#theupbutton").show();
}

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

function mydownbuttonhandler2() {
	var api = $("#pl3").scrollable(); 
	api.movePage(1);
	var totalpages = api.getPageAmount()  - 1;
	if (api.getPageIndex() >= totalpages){
		$("#thedownbutton2").hide();
	}
	$("#theupbutton2").show();
}

function myupbuttonhandler2() {
	var api = $("#pl3").scrollable(); 
	api.movePage(-1);
	if (api.getPageIndex() == 0 ){
		$("#theupbutton2").hide();
	}
	$("#thedownbutton2").show();
}

function myrightbuttonhandler() {
	var api = $("#photo_mask_layer").scrollable(); 
	api.movePage(1);
	var totalpages = api.getPageAmount()  - 1;
	if (api.getPageIndex() >= totalpages){
		$("#therightbutton").hide();
	}
	$("#theleftbutton").show();
}

function myleftbuttonhandler() {
	var api = $("#photo_mask_layer").scrollable(); 
	api.movePage(-1);
	if (api.getPageIndex() == 0 ){
		$("#theleftbutton").hide();
	}
	$("#therightbutton").show();
}

