/* ********* Tour Dates */
/* Sets the maximum number of tour dates to be shown with in the module.*/
var tourDateMaxItems = 5; 

/*This is the View All Link of the Tour Date module.*/
var tdViewAllLink="/tour/"; 

/* Text that is displayed when no shows are available */
var tdNoShowsText="No shows scheduled. Check again later";


var monthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",
			"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");


renderRSSModule = function(data,format, div) {

	/* Cellstream details page: Div id of Cellstream Details section */
	if ($(div).attr("id") == "rss_content-366838") {				
		div.empty();
		// ciscoeos.com?someparam=name&otherparam=8&id=6
		var selectedID = $.urlParam('id');		
		var isInputParam=false;				
		
		/* If the param - id is not null */
		if (selectedID != 0) {			
			isInputParam=true;	
			csDetailsWrapper=csDetailsBuildStructure(data,selectedID,isInputParam);
			div.append(csDetailsWrapper);		
		}		
		else {				
			/* Param id is blank */
			isInputParam=false;	
			csDetailsWrapper=csDetailsBuildStructure(data,selectedID,isInputParam);
			div.append(csDetailsWrapper);
		}
	}	
	/* International feed ***/
	else if (div.attr("id") == "rss_in-798497" ||
		 div.attr("id") == "rss_content-798274" ||
		 div.attr("id") == "rss_content-798275" ||
		 div.attr("id") == "rss_content-798273"){		 
		 var feed = new InternationalFeed(div.attr("id"), div, data, 5);
		 feed.showNextPage();
		
	}
	/* Home page: Div id of Cellstream section */	
	else if($(div).attr("id") == "rss_content-367007") {
		$(document).ready(function(){
		/* Empty the container div */
		div.empty();
		
		/*cellStreamWrapper=cellstreamBuildStructure(data);
		div.append(cellStreamWrapper);
	
		cellStreamOptions.pageNumber = 0;
		/* Setting the previous and next buttons */
		//setPreviousNextButtons(div);
		
		/* Display the first page */
	//	showCSPage(0);
		//registerHover();
		initCellstream(div, data);
		//$("#rss_content-367007 .fullText a").attr("target", "_new");
		});
	}
	
/*
	else if($(div).attr("id") == "rss_in-998205"){
	
		div.empty();
		
		initCellstream(div, data);
	}
*/
	
	
	/* Concerts page: Div id of Tour dates module */
	else if (div.attr("id") == "rss_content-327532") {
		
		div.empty();
		if ($("body").is("#home")) {
			/* This is tours module in the home page. In this module a maximum of 
		   	 * above set tour dates are displayed.
		   	 * The tdAllFlag is set to false, so that it displays only the set number of tour dates in the module.
		 	 */
			tdAllFlag = false;
		} else {
			/* This is tours module in the concerts landing page module. In this module 
			 * all the tour dates are displayed.The tdAllFlag is set to true, so that 
			 * it displays all the tour dates.
		 	 */
			tdAllFlag = true;
		}
		tourDatesWrapper = tourDatesBuildStructure(tdAllFlag,data);
		div.append(tourDatesWrapper);		
	}
	/* Default RSS Ingester module functionality */
	else { //if this isn't the cellstream RSS module then use the EOS default copied and pasted below
		renderRSSModuleEOS(data, format, div);
		/* Make links in twitter feed open in a new window */
		$("#rss_content-340498 h3 a").text("Follow [Artist Name]");
		$("#rss_content-340498 a").attr("target", "_new");
	}
}


renderRSSModuleEOS=function(c,a,b){jQuery.getFeed({xml:c,success:function(g){jQuery(b).append('<h3><a href="'+g.link+'">'+g.title+"</a></h3>");var e="";for(var d=0;d<g.items.length&&d<5;d++){var f=g.items[d];e+="<h4>";if(f.link.length>0){e+='<a href="'+f.link+'">'+f.title+"</a>"}else{e+=f.title}e+="</h4>";e+='<div class="updated">'+f.updated+"</div>";e+="<div>"+f.description+"</div>";if(f.image){e+='<div class="image"><img src="'+f.image+'"></div>'}}jQuery(b).append(e)}})};

/* Convert the timestamp to text format */
function simpleDate(timestamp) {

	currentDate = new Date();
	postedDate = new Date(timestamp);
	
	offset = currentDate.getTime() - postedDate.getTime();
	
	/*display full timestamp if posted Date is in the future or more than 10 days ago*/
	if(offset < 0 || offset > 10 * 24 * 60 * 60 * 1000) {
		return postedDate.getMonth() + '/' + postedDate.getDate() + '/' + (postedDate.getYear() + 1900)
	}
	
	//display mins if less then an hour ago
	if(offset < 60 * 60 * 1000) {
		mins = Math.round(offset / (60 * 1000));
		return  mins + ' min' + (mins > 1 ? 's' : '') + ' ago';
	}
	
	//display hours if less than a day ago
	if(offset < 24 * 60 * 60 * 1000) {
		hrs = Math.round(offset / (60 * 60 * 1000));
		return  hrs + ' hr' + (hrs > 1 ? 's' : '') + ' ago';
	}

	//display days
	days = Math.round(offset / (24 * 60 * 60 * 1000));
	return days + ' day' + (days > 1 ? 's' : '') + ' ago';
}


$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return 0;
	}
	else {
		return results[1];
	}
}

function createTourDateUnit(title, venueName,venueCountry,venueState,venueCity,venueLocation,buyLink, appearingWith){
		
	tourDatesUnit = document.createElement('div');
	$(tourDatesUnit).attr("class","tourDatesUnit");
	
	//create tour date unit
	tdDateUnit = document.createElement('div');
	$(tdDateUnit).attr("class","tdDateField");
	var dateInTitle = "" + title.match(/\d{1,2}\/\d{1,2}/);
	var dateString = "";
	var monthString = "";
	if(dateInTitle != null ) {
		var dateArray = dateInTitle.split("\/");
		monthString =  eval(dateArray[0])<10 ? ("0" + dateArray[0]) : dateArray[0];
		dateString = eval(dateArray[1])<10 ? ("0" + dateArray[1]) : dateArray[1];
	}
	$(tdDateUnit).append(monthString +'/'+ dateString);
		
	//create tourVenueBuyWrapper	
	tourVenueBuyWrapper = document.createElement('div');
	$(tourVenueBuyWrapper).attr("class","tourVenueBuyWrapper");

	//create tour venue unit
	tdVenueField = document.createElement('div');
	$(tdVenueField).attr("class","tdVenueField");
	
	
	venueString="<span>";
	if ($.trim(venueLocation) != "" ){venueString += $.trim(venueLocation)}
	else if(($.trim(venueCity)!="") && ($.trim(venueState) != "")){
		venueString+=$.trim(venueCity)+"," + venueState;
	}
	else if(($.trim(venueCity)!="") && ($.trim(venueCountry) != "")){
		venueString+=$.trim(venueCity)+"," + venueCountry;
	}
	venueString += "</span>";
	$(tdVenueField).append('<div class="tdVenue">' + venueString + '</div>' + venueName);
		
	if (appearingWith.replace(/\s/g,"") != ""){
		$(tdVenueField).append('<div class="tdArtistName">'+ "Appearing with " + appearingWith +'</div>');
	}
	
	$(tourVenueBuyWrapper).append(tdDateUnit);
	$(tourVenueBuyWrapper).append(tdVenueField);
	
	/*
$(tourVenueBuyWrapper).append('<div class="clear"></div>');
*/
	
	//create purchase tickets unit
	if (buyLink != ""){
		tdBuyLinksField = document.createElement('div');
		$(tdBuyLinksField).attr("class","tdBuyLinksField");
		$(tdBuyLinksField).append('<div class="tdBuyLinks"><a target="_blank" href="'+ buyLink +'">Purchase Tickets</a></div>');
		$(tourVenueBuyWrapper).append(tdBuyLinksField);
		$(tourVenueBuyWrapper).append('<div class="clear"></div>');		
	}
	

	$(tourDatesUnit).append(tourVenueBuyWrapper);
	$(tourDatesUnit).append('<div class="clear"></div>');
	return tourDatesUnit;
}

function tourDatesBuildStructure(tdAllFlag,data){
	tourDateCount = 0;
	
	//Load into XML DOM
	xmlDom = getXMLDOM(data);
	tourDatesWrapper = document.createElement('div');
	$(tourDatesWrapper).attr("class","tourDatesWrapper");
	totalTourItems = ($(xmlDom).find('item').length);
	tourDateLimit = tdAllFlag ? totalTourItems : tourDateMaxItems;


	var itemLen=$(xmlDom).find('item').length;
	var titleText=($(xmlDom).find('item').children("title").text());
	var title;
	

	if (!(itemLen == 1 && (jQuery.trim(titleText).indexOf("Sorry",0)!=-1))) {
		$(xmlDom).find('item').each(function(){

			title = $(this).children("title").text();			
			venueName = $(this).children("venueName").text();
			venueCountry = $(this).children("venueCountry").text();
			venueCity = $(this).children("venueCity").text();
			venueLocation = $(this).children("venueLocation").text();
			venueState = $(this).children("venueState").text();
			buyLink = $(this).children("buylink").text();
			appearingWith = $(this).children("appearingWith").text();

			tourDatesUnit = createTourDateUnit(title, venueName, venueCountry,venueState,venueCity, venueLocation, buyLink, appearingWith);
			$(tourDatesWrapper).append(tourDatesUnit);
			tourDateCount++;
			if (tourDateCount == tourDateLimit) {
				return false;
			}
		})
	}

	if ($(xmlDom).find('item').length <= 0){
		$(tourDatesWrapper).append('<span class="tdErrorText">'+ tdNoShowsText + '</span>');
	}else if (jQuery.trim(titleText).indexOf("Sorry",0)!=-1) {
			writeToConsole("Not able to get feed");
			$(tourDatesWrapper).append('<span class="tdErrorText">'+ tdNoShowsText + '</span>');
	}else {
		if(!tdAllFlag && totalTourItems > tourDateLimit) {
			$(tourDatesWrapper).append('<div id="tdViewAll"><a href="' + tdViewAllLink + '">VIEW MORE</a></div');
		}
		if(tdAllFlag) {
			$(tourDatesUnit).addClass("lastUnit");
		}
	}
	return tourDatesWrapper;
}

function getXMLDOM(xml){
    if( window.ActiveXObject && window.GetObject ) {
        var dom = new ActiveXObject( 'Microsoft.XMLDOM' );
        dom.loadXML( xml );
        return dom;
    }
    if( window.DOMParser )
        return new DOMParser().parseFromString( xml, 'text/xml' );
    throw new Error( 'No XML parser available' );
}

function writeToConsole(obj){
	if(window.console && window.console.log){
		switch(typeof obj){
			case 'string': case 'integer':
				window.console.log('Eos > '+obj); break;
			default:
				window.console.log(obj); break;
		}
	}
};

