  
var json;
var xmlFile = new Array();
var debugmode = false ; 
var podcastfile;
var targetPodcastIdx =0;
xmlFile[0] ="/feed/rss2/podcasts/whitepaper.xml";
xmlFile[1] = "/feed/rss2/podcasts/casestudy.xml";

//when the dom is loaded generate the page. currently loads the first xml file in the array
$(document).ready(function(){
		
	
		//categoryid = $.getURLParam("category");
		//podcastfile = $.getURLParam("pf");
		categoryid = $.url().param("category");
		podcastfile = $.url().param("pf");
		if (categoryid==null) {
			loadCategory(0);
		}
		else{		
			loadCategory(categoryid);
		}
		
		
		
});

//load the correct category
function loadCategory(id){
	//podcastArray = new Array();
	generateContent(xmlFile[id]);
	var tabs  = $('div#categories ul');	
	tabs.children().removeClass("selected");
	 $('div#categories ul li:eq(' + id + ')').addClass("selected");
	//newSelected.addClass("selected").end();
	
	
	
}


//TODO: refactor this function. place it in the utilities.js file -- similar function is used in the pres_xmlloader.s file	
//load the xml file, convert to json, create thecontent for the page.
function generateContent(xmlFile){
	$.ajax({
		  type: "GET",
		  url: xmlFile, 
		  dataType: "xml", 
 		error: function(xhr, status, errorThrow){
 				$('body').html("<!--Error Making Ajax Request:" + errorThrow + "-->");
                                //alert("Error Making Ajax Request:" + errorThrow );
                                },
		  complete: function(data) {
				json = $.xmlToJSON(data.responseXML); 
				createPodcastContent(json);
			}
		});
	}
	
//create each the html items required to display each podcast: title and date, Summary, Podcast, Download
//append each item to it one podcastContent Layer
//finally append each podcastContent Layer to the main Content layer
function createPodcastContent(json){
	var podcastArray = new Array();

	// get if we have to auto start any podcast
	var auto= "no" ;

	//get the content layer and empty current content
	var content  = $('div#pcontent');
	content.empty();
	//create the podcast layer
	var podcast = jQuery('<div></div>');
		podcast.addClass('podcast');		
	
	
	//navigate the JSON structure to the items node
	items = json.channel[0].item;
	//loop through all the items  to create each podcast
	 for(i=0;i<items.length;i++) {	
	 
		//PodCast Content div
		//Create podcast layer
		var podcastContent = jQuery('<div></div>');
		podcastContent.addClass('podcastContent');
					
		
		
		//title & Publish Date
		var publishDate = jQuery('<span>(' + generateDate(items[i].pubDate[0].Text) + ')</span>');
		var title;
		if (debugmode) {
			title = jQuery('<h3> (' + i + ") " + items[i].subtitle[0].Text + '</h3>');						
		}
		else {
			title = jQuery('<h3>' + items[i].subtitle[0].Text + '</h3>');						
		}

		title.appendTo(podcastContent);
		publishDate.appendTo(title);

	        

		//Summary						
		var summaryLink = jQuery('<div>Summary <!--&gt;&gt;--></div>');
		summaryLink.appendTo(podcastContent);
		summaryLink.addClass("summaryLink");
		//could not figure out a clean solution to attach the click events. i set the id of each summary link  and use the id to toggle the correct summary div.
		summaryLink.attr("id",i);
		summaryLink.click(function() {
			
			
			summaryid = '#summary' + $(this).attr("id")
			//$(summaryid).slideToggle('slow');	
			$(summaryid).slideToggle('slow');
			$(summaryid).prev().toggleClass('open');
			
		});
		
		var Summary = jQuery('<div>' + insertLink(items[i].summary[0].Text) + '</div>');
		Summary.addClass("summary");
		Summary.attr("id",'summary'+i);
		/* JS: commented out, so description is not clickable */
		/* Summary.click(function() {
			$(this).slideToggle('slow');
		});*/
		Summary.appendTo(podcastContent);

	
		
		//flash podcast
                // strip off http://www.telcordia.com so links work in different environments
                var link = items[i].guid[0].Text ;
                link = link.substr(24,link.length);

		// determine if this podcast needs to be auto start or no
		auto = "false" ;
		if ( podcastfile != "" ) {
			
			if ( link.indexOf(podcastfile) != -1 ) {
				podcastAnchor = podcastfile.replace(/\..*$/,'');
				podcastContent.prepend('<a name="'+podcastAnchor+'"></a>');		
				podcastfile = "";
				auto = "true" ;			
				
				//alert('Playing target podcast ' + targetPodcastIdx);
			}
		}
		// alert(auto);
		
		//duration
		var duration = items[i].duration[0].Text;
		if ( duration) {
			idx = duration.indexOf(':');
			seconds = parseInt(duration.substr(idx+1,duration.length));
			duration= duration.substr(0,idx);
			duration = parseInt(duration)*60+seconds;			
		} else { duration=1 }


		var flash =jQuery('<div></div>');
		var targetid ="flashcontent"+i;
		var thisplayer ="player"+i;
		flash.addClass("flashPodcast");
		
		flash.prepend('<div id="'+targetid+'"></div>');
		flash.appendTo(podcastContent);	
			
		 
		/*
		flash.flash(
			{
				src: '/flash/jwplayer/player-licensed.swf' ,
				width:200,
				height:24,
				name: i,
				id: i,
				wmode: 'transparent', 
				flashvars: { id: i, duration:duration, file: link, autostart: auto, config: '/flash/jwplayer/podcast/config.xml'}							
			}
		);*/
		
		
		//podcast download					
		// var fileLocation = jQuery('<a href="' +  items[i].guid[0].Text  + '">download mp3</a>');	
		var fileLocation = jQuery('<a  href="' +  link  + '">download mp3</a>');	
		fileLocation.addClass('downloadFile');		
			
		fileLocation.appendTo(podcastContent);	
		
		//send to a friend
		cid=0;
		if (typeof categoryid != 'undefined') {
			cid=categoryid
		}
		//pageURL = "http://" + window.location.hostname.toString() + ":" + window.location.port.toString() +"/podcasts/index.html?category%3D0%260&pf=";
		pageURL = "http://" + window.location.hostname.toString() + ":" + window.location.port.toString() +"/podcasts/index.html?category="+cid+"&pf=";	
		lastindex = link.lastIndexOf("/") + 1;		
		var podcastName = link.substr(lastindex,link.length);	
		pageURL= pageURL + podcastName;
		var subject = items[i].subtitle[0].Text;
		var sendToColleague = jQuery('<span  class="pc-toolbox addthis_toolbox addthis_default_style" addthis:url="'+pageURL+'" addthis:title="'+subject+'"><a class="addthis_button_email"></a> <a class="addthis_button_compact">Share</a></span>');
				
		//var sendToColleague = jQuery(' <a href="/webapps/siteapps/email_to_friend.jsp?' + 'page_title=' + escape(items[i].subtitle[0].Text)  + ' (Podcast)&page_url=' + escape(pageURL) + '&TB_iframe=true&height=475&width=410" class="thickbox"><img class="emailtofriend" src="/images/redesign09/wrap/iconEmail.gif" alt="Share This Podcast" title="Share This Podcast" width="19" height="15" style="vertical-align:middle;"></a>');			
		sendToColleague.appendTo(podcastContent);	
		
		
		//append to  Content Layer
		podcastContent.appendTo(podcast);
		podcast.appendTo(content);
		insertPodCastControl(targetid, thisplayer, link, "200", "24",duration,auto); 
		//force rending of newly added addthis links
		addthis.toolbox(".pc-toolbox");	
		//addthis.toolbox("#"+thisToolbox);	
		//podcastArray[i] = targetid +"|"+thisplayer+"|"+link+"|"+duration+"|"+auto;
		tb_init('a.thickbox, area.thickbox, input.thickbox');
		

	}
	
    //scroll to selected podcast
	if (typeof podcastAnchor != 'undefined') {
		var scroll2anchor = $('.podcastContent a[name='+podcastAnchor+']');		
		window.scrollTo(0,scroll2anchor.position().top);  
	}

}
// converts date string from xml file into a friendly date
function generateDate(publishdate){
	day = publishdate.substr(publishdate.length - 24,2);
	day = jQuery.trim(day);
	month = publishdate.substr(publishdate.length - 21 ,3);
	year =publishdate.substr(publishdate.length - 17,4);
	month = monthArray[month];//month array is in the utilities
	return month + ' ' + day + ', ' +year;
						
}

function insertLink(summarytext){
	summarytext = summarytext.replace(/Telcordia Granite Inventory/,"<a href=\"/products/inventory/index.html\">Telcordia Granite Inventory</a>");
	summarytext = summarytext.replace(/Telcordia Fulfillment Suite/,"<a href=\"/markets/fulfillment/index.html\">Telcordia Fulfillment Suite</a>");
	summarytext = summarytext.replace(/http:\/\/wiser.research.telcordia.com/	,"<a href=\"http://wiser.research.telcordia.com\" target=\"_new\">http://wiser.research.telcordia.com</a>");

	return summarytext ;
}

		 
function insertPodCastControl(divname, playerid, soundfile, width, height, duration,autostart)
{

		var flashvars = {
				width: width,
				height: height,
				file:  soundfile,
				duration: duration,
				config: "/flash/jwplayer/podcast/config.xml",			
				autostart: autostart
						
			};
			var params = {wmode:'opaque'};
			var attributes = { id: playerid, name: playerid };
			swfobject.embedSWF("/flash/jwplayer/player-licensed.swf", divname, width, height, "9", "", flashvars, params, attributes);

}



