/* ********* Tour Dates */
/* Sets the maximum number of tour dates to be shown with in the module.*/
var tourDateMaxItems =6; 
var photoItemsLimit = 5;
/*This is the View All Link of the Tour Date module.*/
var tdViewAllLink="/tour-dates/"; 

/*This is the current page value .*/
var tdPageNameNo=1; 
/* Text that is displayed when no shows are available */
var tdNoShowsText="No shows scheduled. Check again later";

var viewmoretour=true;

/* Dom structure */
var xmlDom;

var monthNames = new Array("January", "Febuary", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December");
/*Associative array of module id's and corresponding XML DOM*/
var rssModuleArray = new Object();


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 SS 1: Div id of Cellstream section */	
	else if($(div).attr("id") == "rss_content-367007") {
		$(document).ready(function(){
		/* Empty the container div */
		div.empty();	
		//initCellstream(div, data);
		var itemsPerPage = 3;
		var csOrdinates = {
		  "active": {
		            "left": [0, 175, 350],
		            "top": [-35, -35, -35],
		            "height": "312",
			    	"width":"255"
		        },
				
			"normal": {
		             "left": [23, 217, 411],
		             "top": [0, 0, 0],
		             "height": "210",
			     	"width":"169"
		        }
		    };
		csObj = new CellStream(csOrdinates, div, data, itemsPerPage);
		csObj.csItem();
		});
	}
	/* Home page SS 3: Div id of Cellstream section */	
	else if($(div).attr("id") == "rss_content-1056734") {
		/* Empty the container div */
		$(document).ready(function(){
			div.empty();	
			var itemsPerPage = 3;
			var csOrdinates = {
				  "active": {
				            "left": [0, 0, 0],			            
				            "height": "265",
					    	"width":"225",
							"top": [-5, 160, 332]
				        },
						
					"normal": {
				             "left": [0, 0, 0],			             
				             "height": "193",
					     	 "width":"125",
							 "top": [0, 203, 406]
				        }
				    };
			//initCellstream(div, data);
			csObj = new CellStream(csOrdinates, div, data, itemsPerPage);
			csObj.csItem();	
		});	
	}
	/* Home page SS 4: Div id of Cellstream section */	
	else if($(div).attr("id") == "rss_content-1056735") {
		/* Empty the container div */
		$(document).ready(function(){
		div.empty();
		//initCellstream(div, data);
		var itemsPerPage = 5;

		var csOrdinates = {
			  "active": {
			            "left": [0, 75, 164, 275, 400],
			            "top": [-38, -38, -38, -38, -38],
			            "height": "248",
				    	"width":"225"
			        },
					
				"normal": {
			             "left": [2, 126, 250, 374, 498],
			             "top": [0, 0, 0, 0, 0],
			             "height": "180",
				     	"width":"115"
			        }
			    };
				
		csObj = new CellStream(csOrdinates, div, data, itemsPerPage);
		csObj.csItem();
		});
	}
	
	/* Concerts page: Div id of Tour dates module  */

	else if ((div.attr("id") == "rss_content-327532") ) {
		var rssContentId = div.attr("id");
		div.empty();
		if ($("body").is("#home") || $("body").is("#video") || $("body").is("#photo") || $("body").is("#homepage_ss4")) {
			/* 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.
		 	 */
			viewmoretour=true;
			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.
		 	 */
			viewmoretour=false;
			tdAllFlag = true;
		}
		xmlDom = getXMLDOM(data);
		rssModuleArray[rssContentId] = xmlDom;
		var divObj = $(div).parents('.module').parent().attr("id");
		divObj = "#" + divObj;
		tourDatesWrapper = tourDatesBuildStructure(tdAllFlag,divObj,rssContentId);
		div.append(tourDatesWrapper);		
	}
	else if ((div.attr("id") == "rss_content-5436338")) {
	    div.empty();
        photoWrapper = photoStructure(data);
		div.append(photoWrapper);
     
	}
	
	/* 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){
	writeToConsole(title + "venuename" +  venueName + "venuecountry" + venueCountry + "venuestate" + venueState + "venuecity" + venueCity + "venueloc" + venueLocation + "buy" + buyLink + "appearing" + appearingWith);	
	tourDatesUnit = document.createElement('div');
	$(tourDatesUnit).attr("class","tourDatesUnit");
	
	//create tour date unit
	tdDateUnit = document.createElement('div');
	$(tdDateUnit).attr("class","tdDateField");
	if ($("body").is("#homepage_ss2")){ // For SS2 Homepage
	var day;
	var dateInTitle = "" + title.match(/\d{1,2}\/\d{1,2}/);	
	var unFormatDay ="" +title.match(/- \w{3}/);	
	if(unFormatDay != null){
		day=unFormatDay.substring(2,5);
	}	
	var dateString = "";
	var monthString = "";
	if(dateInTitle != null ) {
		var dateArray = dateInTitle.split("\/");		
		monthString = monthNames[dateArray[0]-1];
		dateString = dateArray[1];		
	}
	$(tdDateUnit).append('<div class="tdDay">'+ day +'</div><div class="tdDM">'+ dateInTitle +'</div>');
		
	}else{
	var dateInTitle = "" + title.match(/\d{1,2}\/\d{1,2}/);
	var dateString = "";
	var monthString = "";
	if(dateInTitle != null ) {
		var dateArray = dateInTitle.split("\/");
		monthString = monthNames[dateArray[0]-1];
		dateString = dateArray[1];		
	}
	$(tdDateUnit).append('<div class="tdMonth">'+ monthString + '</div><div class="tdDD">'+ dateString +'</div>');		
	}	
	
	//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)}
	venueString += "</span>"
	$(tdVenueField).append('<div class="tdVenue">' + venueName + '</div>' );
	if ($.trim(venueState) != "" ){
		$(tdVenueField).append('<div class="tdCity">' + venueCity + ', ' + venueState + ', ' +'</div>'+ '<div class="tdCountry">' + venueCountry + '</div>');
	}else{
		$(tdVenueField).append('<div class="tdCity">' + venueCity +', '+ '</div>' + '<div class="tdCountry">' + venueCountry + '</div>');
	}
	
	
	
	$(tourVenueBuyWrapper).append(tdVenueField);

	//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(tdDateUnit);
	$(tourDatesUnit).append(tourVenueBuyWrapper);
	$(tourDatesUnit).append('<div class="clear"></div>');
	return tourDatesUnit;
}



function tourDatesBuildStructure(tdAllFlag,divObj,rssContentId){
	writeToConsole($(divObj));
	if (viewmoretour == false){
		tourDateMaxItems=50;
	}
	var tourDateCount = 0;
	xmlDom = rssModuleArray[rssContentId];
	var tourDatesWrapper = document.createElement('div');
	$(tourDatesWrapper).attr("class","tourDatesWrapper");
	var totalTourItems = ($(xmlDom).find('item').length);
	var tourDateLimit = tdAllFlag ? totalTourItems : tourDateMaxItems;


	var itemLen=$(xmlDom).find('item').length;
	var titleText=($(xmlDom).find('item').children("title").text());

	if (!(itemLen == 1 && (jQuery.trim(titleText).indexOf("Sorry",0)!=-1))) {
		$(xmlDom).find('item').each(function(){

			if((tourDateCount<(tdPageNameNo*tourDateMaxItems)) && (tourDateCount>=((tdPageNameNo-1)*tourDateMaxItems)) ){
				var title = $(this).children("title").text();
				
				var venueName = $(this).children("venueName").text();
				var venueCountry = $(this).children("venueCountry").text();
				var venueCity = $(this).children("venueCity").text();
				var venueLocation = $(this).children("venueLocation").text();
				var venueState = $(this).children("venueState").text();
				var buyLink = $(this).children("buylink").text();
				var appearingWith = $(this).children("appearingWith").text();
				tourDatesUnit = createTourDateUnit(title, venueName, venueCountry,venueState,venueCity, venueLocation, buyLink, appearingWith);

				$(tourDatesWrapper).append(tourDatesUnit);	
			}
			tourDateCount++;
			
			if (tourDateCount == tourDateLimit*tdPageNameNo) {
				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) {
			
		}
		if(tdAllFlag) {
			$(tourDatesUnit).addClass("lastUnit");
		}
	}
		
	if(viewmoretour){
		return tourDatesWrapper;
	}	
	tdPageNameNoPos = tdPageNameNo+1;
	tdPageNameNoNeg = tdPageNameNo-1;
	
	if (tdPageNameNo * tourDateMaxItems >= itemLen && tdPageNameNo == 1) {
		    $(divObj).find(".module .content .foot").empty();
	}
	else if(tdPageNameNo * tourDateMaxItems >= itemLen) {
		   $(divObj).find(".module .content .foot").empty();
		     $(divObj).find(".module .content .foot").append('<div class="nav_page"><ul><li class="jump next"><span>Next</span></li><li class="page"></li><li class="jump prev"><a onClick=' + 'showCSPrevPageTour("'+divObj+'","'+rssContentId+'")' + '>Prev</a></li></ul></di>');
		   $(divObj).find(".module .content .foot").append('<span class="clear"/>');
			$(tourDatesWrapper).append('<span class="clear"/>');
			if(tdPageNameNo!=1){
				$(divObj).find(".module .content .foot .nav_page ul li.page").append("<a onClick="+ "showCSCurrentPageTour("+ tdPageNameNoNeg + ",'" +divObj+ "','" + rssContentId +"')"+">" + tdPageNameNoNeg + "</a>");
			}
			$(divObj).find(".module .content .foot .nav_page ul li.page").append("<a class='active' onClick=" + "showCSCurrentPageTour(" + tdPageNameNo+",'" + divObj + "','" + rssContentId +"')" +">" + tdPageNameNo + "</a>");
			
	}
	else if(tdPageNameNo==1){
		    $(divObj).find(" .module .content .foot").empty();	
			var tempString = '<div class="nav_page"><ul><li class="jump next"><a onClick=' + "showCSNextPageTour('" + divObj+"','" +rssContentId +"')" + '>Next</a></li><li class="page"></li><li class="jump prev"><span>Prev</span></li></ul></div>';
		    $(divObj).find(" .module .content .foot").append(tempString);
		   $(divObj).find(".module .content .foot").append('<span class="clear"/>');		
			$(tourDatesWrapper).append('<span class="clear"/>');
			$(divObj).find(".module .content .foot .nav_page ul li.page").append("<a class='active' onClick="+ "showCSCurrentPageTour(" + tdPageNameNo + ",'" + divObj + "','" + rssContentId + "')"+" >" + tdPageNameNo + "</a>");			
			if((itemLen/tourDateMaxItems)>tdPageNameNo){
				$(divObj).find(" .module .content .foot .nav_page ul li.page").append("<a onClick=" + "showCSCurrentPageTour("+tdPageNameNoPos+",'" + divObj + "','" + rssContentId + "')" +" >" + tdPageNameNoPos + "</a>");			
			}
	}
	else{
		   $(divObj).find(" .module .content .foot").empty();		
		   $(divObj).find(".module .content .foot").append('<div class="nav_page"><ul><li class="jump next"><a onClick=' + "showCSNextPageTour('"+ divObj + "','" + rssContentId +"')"+ '>Next</a></li><li class="page"></li><li class="jump prev"><a onClick=' + "showCSPrevPageTour('"+divObj+"','" + rssContentId + "')"+ '>Prev </a></li></ul></di>');
		  $(divObj).find(".module .content .foot").append('<span class="clear"/>');	
			$(tourDatesWrapper).append('<span class="clear"/>');	
			$(divObj).find(".module .content .foot .nav_page ul li.page").append("<a onClick="+ "showCSCurrentPageTour(" + tdPageNameNoNeg + ",'" + divObj+ "','" + rssContentId + "')" + ">" + tdPageNameNoNeg + "</a>");			
			$(divObj).find(" .module .content .foot .nav_page ul li.page").append("<a class='active' onClick=" + "showCSCurrentPageTour("+ tdPageNameNo +",'" + divObj + "','" + rssContentId + "')" +">" + tdPageNameNo + "</a>");			
			$(divObj).find(" .module .content .foot .nav_page ul li.page").append("<a onClick=" + "showCSCurrentPageTour("+ tdPageNameNoPos + ",'" + divObj + "','" + rssContentId +"')" + ">" + (tdPageNameNoPos) + "</a>");						
	}


	}

	
	return tourDatesWrapper;
}



function showCSNextPageTour(divObj,rssContentId){
	var divObjChild = $(divObj).find('.module .content .description');
	tdPageNameNo++;
	tourDatesWrapper = tourDatesBuildStructure(false,divObj,rssContentId);
	$(divObjChild).empty();
	$(divObjChild).append(tourDatesWrapper);
}
function showCSCurrentPageTour(iPageNo,divObj,rssContentId){
	var divObjChild = $(divObj).find('.module .content .description');
	tdPageNameNo=iPageNo;
	tourDatesWrapper = tourDatesBuildStructure(false,divObj,rssContentId);
	$(divObjChild).empty();
	$(divObjChild).append(tourDatesWrapper);
}
function showCSPrevPageTour(divObj,rssContentId){
	var divObjChild = $(divObj).find('.module .content .description');
	tdPageNameNo--;
	tourDatesWrapper = tourDatesBuildStructure(false,divObj,rssContentId);
	$(divObjChild).empty();
	$(divObjChild).append(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;
		}
	}
};

function truncate(truncateTxt,character){
	
				truncateTxt = truncateTxt.trim();
				if (truncateTxt.length > character) {
					truncateTxt = truncateTxt.substring(0, character);
					truncateTxt = truncateTxt +  '<span>' + '...</span>';

			}
			return truncateTxt;	
}

function photoStructure(data){
	var title;
	var author;
	var description;
	var photoItems=0;
	var photoWrapper;
	var photoitems;
	var photoitemlist;


	xmlDom = getXMLDOM(data);
	photoWrapper = document.createElement('div');
	$(photoWrapper).attr("class","photoContainer");

   if ($(xmlDom).find('item').length <= 0) {
		$(photoWrapper).append('<span class="ErrorText">'+ 'No photos yet!' + '</span>');
	}
	else
	{
		photoitems=document.createElement('ul');
		
		$(xmlDom).find('item').each(function(){
			title = $(this).children("title").text();
			link = $(this).children("link").text();
			description = $.trim($(this).children("description").text());
			author = $.trim($(this).children("author").text());
			date = $.trim($(this).children("pubDate").text());

			photoitemlist=document.createElement('li');
			$(photoitemlist).attr("class","photo small");
			
			var photoDescription = document.createElement('div');
			$(photoDescription).attr("class","photoDescription");
			$(photoDescription).append(description);
			$(photoitemlist).append(photoDescription);
			
			var photoTitle = document.createElement('div');
			$(photoTitle).attr("class","photoTitle");
			$(photoTitle).append(title);
			$(photoitemlist).append(photoTitle);
			
			var photoAuthor = document.createElement('div');
			$(photoAuthor).attr("class","photoAuthor");
			$(photoAuthor).append("<div>Posted by <a href='/member/i/5050047/'>" + author + "</a></div>");
			$(photoitemlist).append(photoAuthor);
			
			var photoDate = document.createElement('div');
			$(photoDate).attr("class","photoDate");
			$(photoDate).append(" |<span> " + dateConvert(date) +"</span>");
			$(photoitemlist).append(photoDate);
			
				   
			
	        var rrmFB = '<iframe src="http://www.facebook.com/plugins/like.php?href=' + link + '&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true"></iframe>';

			$(photoitemlist).append(rrmFB);
							
			$(photoitems).append(photoitemlist);
			photoItems++;
		
			if (photoItemsLimit == photoItems) {
					return false;
			}
		});	
		
		$(photoWrapper).append(photoitems);
       }

   return photoWrapper;

}


/* Convert the timestamp to text format */
function dateConvert(date){
		var dateArray = date.split(",");
		var monthDate = dateArray[1].split(" ");
		var day = monthDate[1];
		var month = monthDate[2];
		var year = monthDate[3];
		
		var newDate = month+" "+day+", "+year;
		
		return newDate;
						
}



