/* ********* Tour Dates */
/* Sets the maximum number of tour dates to be shown with in the module.*/
var tourDateMaxItems = 5; 
var siteActivityItemsLimit = 6; 
var currentSiteURL = "http://www.simpleplan.com";
var artistActivityCharLimit = 84;


/*This is the View All Link of the Tour Date module.*/
var tdViewAllLink="/tour-dates/"; 

/* Text that is displayed when no shows are available */
var tdNoShowsText="No shows scheduled. Check again later";


var monthNames = new Array("January", "February", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December");


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();
		
		var itemsPerPage = 3;
		
		var csOrdinates = {
		  "active": {
		            "left": [0, 165, 360],
		            "top": [-44, -44, -44],
		            "height": "252",
			    	"width":"225"
		        },
				
		  "normal": {
		             "left": [0, 204,407],
		             "top": [0, 0,0],
		             "height": "235",
			     	 "width":"190"
		        }
		    };
			
		if($('body').attr('id')=="home" || $('body').hasClass("international")){
			
		itemsPerPage = 3;
		csOrdinates = {
		  "active": {
		            "left": [0, 165, 360],
		            "top": [-44, -44, -44],
		            "height": "252",
			    "width":"225"
		        },
				
		  "normal": {
		             "left": [0, 204, 407],
		             "top": [0, 0, 0],
		             "height": "235",
			     "width":"190"
		        }
		    };	
			
		}
		csObj = new CellStream(csOrdinates, div, data, itemsPerPage);
		csObj.csItem();
		
						
	});
	}
	
/*
	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);		
	}
	/* Site Activity */
	else if (div.attr("id") == "rss_content-5337103") {
		if ($("body").is("#community_landing")) {
			siteActivityItemsLimit=3;
		}
		
		div.empty();
		siteActivitywrapper = siteActivityStructure(data);
		div.append(siteActivitywrapper);	
	}
	 else if(div.attr("id") == "rss_content-5438802") {
		div.empty();
		intlBlogWrapper = intlBlogStructure(data);
		div.append(intlBlogWrapper);	
	}
	/* 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()+1 + '/' + 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 intlBlogStructure(data){
	var totalBlogItems;
	var blogTitle;
	var blogLink;
	var blogDescription;
	var blogCategory;
	var blogPubDate;
	var blogAuthor;
	
	data.replace(/dc:creator/g,"author");
	//alert(data);
	//Load into XML DOM
	xmlDom = getXMLDOM(data);
	intlBlogWrapper = document.createElement('div');
	$(intlBlogWrapper).attr("class","intlBlogWrapper");
	totalBlogItems = ($(xmlDom).find('item').length);
	intlBlogIntWrapouter = document.createElement('div');
	$(intlBlogIntWrapouter).attr("class","blog_listing");
	
	var itemLen=$(xmlDom).find('item').length;
	var titleText=($(xmlDom).find('item').children("title").text());
	if(totalBlogItems >0){ 
		intlBlogIntWrap = document.createElement('ul');
		$(intlBlogIntWrap).attr("class","articles");
		
		if (!(itemLen == 1 && (jQuery.trim(titleText).indexOf("Sorry",0)!=-1))) {
			$(xmlDom).find('item').each(function(){
				blogTitle = $(this).children("title").text();
				blogLink = $(this).children("link").text();
				blogDescription = $(this).children("description").text();
				blogCategory = $(this).children("category").text();
				blogPubDate = $(this).children("pubDate").text();
				blogAuthor = $(this).find('[nodeName=dc:creator]').text();				
				blogComments = $(this).children("comments").text();
				intlBlogUnit = createIntlBlogUnit(blogTitle, blogLink, blogDescription,blogCategory,blogPubDate, blogAuthor,blogComments);
				$(intlBlogIntWrap).append(intlBlogUnit);				
			})
		}
		
		$(intlBlogIntWrapouter).append(intlBlogIntWrap);
	}
	if ($(xmlDom).find('item').length <= 0){
		$(intlBlogWrapper).append('<span class="tdErrorText">Blogs not available at the moment. </span>');
	}	
	$(intlBlogWrapper).append(intlBlogIntWrapouter);
	
	return intlBlogWrapper;
}

function createIntlBlogUnit(blogTitle, blogLink, blogDescription,blogCategory,blogPubDate, blogAuthor,blogComments){
	
	intlBlogsUnit = document.createElement('li');
	$(intlBlogsUnit).attr("class","article");
	
	intlBlogstitle = document.createElement('div');
	$(intlBlogstitle).attr("class","title");
	$(intlBlogstitle).append('<h4>'+blogTitle+'</h4>');
	
	intlBlogsDate = document.createElement('div');
	$(intlBlogsDate).attr("class","date");
	$(intlBlogsDate).append(blogPubDate);
	
	intlBlogsAuthor = document.createElement('div');
	$(intlBlogsAuthor).attr("class","author");
	$(intlBlogsAuthor).append(blogAuthor);	
	
	intlBlogsdescription = document.createElement('div');
	$(intlBlogsdescription).attr("class","description");
	$(intlBlogsdescription).append('<p>'+blogDescription+'</p>');
	
	intlBlogsActivity = document.createElement('div');
	$(intlBlogsActivity).attr("class","activity");
	$(intlBlogsActivity).append('<a class="comment" target="_blank" href="'+blogComments+'"></a></h4>');
	$(intlBlogsActivity).append('<div class="fb_like"><iframe src="http://www.facebook.com/plugins/like.php?app_id=214014518637724&amp;href='+blogLink+'&amp;send=false&amp;layout=button_count&amp;width=110&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:110px; height:21px;" allowTransparency="true"></iframe></div>');
	$(intlBlogsActivity).append('<iframe class="twitter-share-button" allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+encodeURI(blogLink)+'&counturl='+encodeURI(blogLink)+'&text='+blogTitle+'" style="width:130px; height:24px;"></iframe>');
	$(intlBlogsUnit).append(intlBlogstitle);
	$(intlBlogsUnit).append(intlBlogsDate);
	$(intlBlogsUnit).append(intlBlogsAuthor);
	$(intlBlogsUnit).append(intlBlogsdescription);
	$(intlBlogsUnit).append(intlBlogsActivity);
	
	return intlBlogsUnit;
}


function siteActivityStructure(data){
 	var descriptionarray1;
	var descriptiontitle;
	var titlearray;
	var linkarray;
	var title;
	var author;
	var link;
	var description;
	var pubDate;
	var siteActivityItems=0;
	var siteActivityWrapper;
	var eventitems;
	var eventitemlist;
	var performer;
	var profile;
	
 	//Load into XML DOM
	xmlDom = getXMLDOM(data);
	siteActivityWrapper = document.createElement('div');
	$(siteActivityWrapper).attr("class","siteActivityWrapper");
	if ($(xmlDom).find('item').length <= 0) {
		$(siteActivityWrapper).append('<span class="ErrorText">'+ 'No Recent activities' + '</span>');
	}
	else{
		eventitems=document.createElement('ul');
		$(eventitems).attr("class","events");
		
		$(xmlDom).find('item').each(function(){
			title = $(this).children("title").text();
			author = $(this).children("author").text();
			link = $(this).children("link").text();
			description = $(this).children("description").text().trim();
			pubDate = $(this).children("pubDate").text();	
	
			eventitemlist=document.createElement('li');
			$(eventitemlist).attr("class","event");
			
			performer=document.createElement('div');
			$(performer).attr("class","performer");
		
			if(author == "Seb"){
				profile = "/member/i/4326480/";
			}else if(author == "Pierre"){
				profile = "/member/i/4326433/";
			}else if(author == "Chuck"){
				profile = "/member/i/4326272/";
			}else if(author == "David"){
				profile = "/member/i/4326317/";
			}else if(author == "Jeff"){
				profile = "/member/i/4326384/";
			}else if(author == "Amanderz"){
				profile = "/member/i/136540/";
			}
			
						
			var tempDiv = document.createElement('div');		
			$(tempDiv).html(description);
			$(tempDiv).find('a').remove();
						
			var descriptiontag = document.createElement('div');		
			$(descriptiontag).attr("class","description");
		   	linkarray=link.split(currentSiteURL);
			if (linkarray[1].indexOf("/photo/") == -1 && linkarray[1].indexOf("/video/") == -1) {
				tempDiv = truncate($(tempDiv).html(), artistActivityCharLimit);
				$(descriptiontag).append('<div class="txt"><a href="' + linkarray[1] + '">' + tempDiv + '</a>' + '</div>');
				$(eventitemlist).append(descriptiontag);
			}
			
			$(performer).append('<div class="txt"><a href = "' + profile + '">' + author + '</a></div>');
			$(eventitemlist).append(performer);
			
			var act=document.createElement('div');
			$(act).attr("class","act");	
			var title=title.substring(title.indexOf(" "),title.length);
			phovidLinkArray=link.split(currentSiteURL);
			if (title.indexOf("photo") != -1) {
				var titlesplit = title.split("photo");
				if (titlesplit[0].indexOf("commented on a") != -1 || titlesplit[0].indexOf("added a") != -1) {
					if (titlesplit[0].length == 9 || titlesplit[0].length == 16) {
						var photoPosition = title.indexOf("photo");
						var photoLink = title.substring(photoPosition, title.length);
						$(act).append(titlesplit[0] + '<a href="' + phovidLinkArray[1] + '">' + photoLink + '</a>');
					}
					else{
						$(act).append(title);
					}
				}
				else{
					
				}
			}
			else if (title.indexOf("video") != -1) {
					var videoPosition = title.indexOf("video");
					var videoLink=title.substring(photoPosition,title.length);
					var titlesplit = title.split("video");
					if (titlesplit[0].indexOf("commented on a") != -1 || titlesplit[0].indexOf("added a") != -1) {
						if (titlesplit[0].length == 8 || titlesplit[0].length == 15) {
							$(act).append(titlesplit[0] + '<a href="' + phovidLinkArray[1] + '">' + videoLink + '</a>');
						}
						else{
							$(act).append(title);
						}
					}
					else{
						$(act).append(title);
					}
				}
				
			else {
					$(act).append(title);
				}
			$(eventitemlist).append(act);
			
			var  ownertag=document.createElement('div');
			$(ownertag).attr("class","owner");
			
			var  itemtag=document.createElement('div');
			$(itemtag).attr("class","item");
			pubDate=simpleDate(pubDate);
			var datetag=document.createElement('div');
			$(datetag).attr("class","date");
			$(datetag).append(pubDate);
			$(eventitemlist).append(datetag);		
				
			$(eventitems).append(eventitemlist);
			siteActivityItems++;
		
			
			if (siteActivityItemsLimit == siteActivityItems) {
					return false;
				}
		});	
		
		$(siteActivityWrapper).append(eventitems);
			
	}
	return siteActivityWrapper;
 }


function createTourDateUnit(title, venueName,venueCountry,venueState,venueCity,venueLocation,buyLink, appearingWith){
		
	var dateText = ($(xmlDom).find('item').children("showDate").text());
	tourDatesUnit = document.createElement('div');
	$(tourDatesUnit).attr("class","tourDatesUnit");
	
	//create tour date unit
	tdDateUnit = document.createElement('div');
	$(tdDateUnit).attr("class","tdDateField");
	var dateInTitle = "" + dateText.match(/\d{1,2}\/\d{1,2}\/\d{1,4}/);
	var dateString = "";
	var monthString = "";
	var yearString = "";
	if(dateInTitle != null ) {
		var dateArray = dateInTitle.split("\/");
		monthString = monthNames[dateArray[0]-1];
		dateString = dateArray[1];
		yearString = dateArray[2];
	}
	
	
	$(tdDateUnit).append('<div class="tShowDate">' +monthString+ ' '+dateString+', '+yearString+'</div>');
	//$(tdDateUnit).append('<div class="tdMonth">'+ monthString +'</div><div class="tdDD">'+ dateString +'</div><div class="tdYear">'+ yearString +'</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">' + venueString + '</div>' + venueName);
		
	if (appearingWith.replace(/\s/g,"") != ""){
		$(tdVenueField).append('<div class="tdArtistName">'+ "Appearing with " + appearingWith +'</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,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());
	
	
	

	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;
		}
	}
};

function truncate(truncateTxt,character){
	
				truncateTxt = truncateTxt.trim();
				if (truncateTxt.length > character) {
					truncateTxt = truncateTxt.substring(0, character);
					truncateTxt = truncateTxt +  '<span>' + '...</span>';

			}
			return truncateTxt;	
}


