/* ********* Tour Dates */
/* Sets the maximum number of tour dates to be shown with in the module.*/
var tourDateMaxItems = 5; 

if ($("body").is("#event_detail")) {
	tourDateMaxItems = 4;
}


/*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";

/*Iggli input information*/
var invite_widget_version="2.0";
var invite_widget_skin="button_small";
var invite_partner_id="145";//Do not change this partner id


var monthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",
			"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

var tempcount=0;
var nooffeeds;
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") {
		/* Empty the container div */
		div.empty();	
		//initCellstream(div, data);
		var itemsPerPage = 3;
		var csOrdinates = {
		  "active": {
		            "left": [0, 75, 164],
		            "top": [-35, -35, -35],
		            "height": "252",
			    	"width":"225"
		        },
				
			"normal": {
		             "left": [0, 133, 266],
		             "top": [0, 0, 0],
		             "height": "180",
			     	"width":"123"
		        }
		    };
		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 */
		div.empty();	
		var itemsPerPage = 3;
		var csOrdinates = {
			  "active": {
			            "left": [0, 0, 0],			            
			            "height": "245",
				    	"width":"225",
						"top": [-5, 160, 332]
			        },
					
				"normal": {
			             "left": [0, 0, 0],			             
			             "height": "181",
				     	 "width":"178",
						 "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 */
		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") {
		
		div.empty();
		if ($("body").is("#tour_dates")) {
			/* 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 = true;
		} 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 = false;
		}
		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 Jonathan Tyler");
		$("#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");
	if(tempcount==0){
		$(tourDatesUnit).addClass("firstentry");
	}
	tempcount++;
	//create tour date unit
	tdDateUnit = document.createElement('div');
	$(tdDateUnit).attr("class","tdDateField");
	if ($("body").is("#homepage_ss2")){ // For SS2 Homepage
	var day;
	var monthNumString = "";
	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("\/");
		monthNumString = dateArray[0];	
		monthString = monthNames[dateArray[0]-1];
		dateString = dateArray[1];		
	}
	$(tdDateUnit).append('<div class="tdMonth">'+ monthString +'</div><div class="tdDD">'+ dateString +'</div>');
		
	}else{
	var dateInTitle = "" + title.match(/\d{1,2}\/\d{1,2}/);
	var dateString = "";
	var monthString = "";
	if(dateInTitle != null ) {
		var dateArray = dateInTitle.split("\/");
		monthNumString = dateArray[0];
		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)}
	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);
	
	//Values for iggli variables
	var newDate = new Date();
	var yearString = newDate.getFullYear();	
	invite_title = title.replace(/\'/g,"\\'");
	invite_title = title.replace(/\&/g,'\&amp;');
	invite_location = venueName + $.trim(venueLocation);
	invite_location = invite_location.replace(/\'/g,"\\'");
	invite_location = invite_location.replace(/\&/g,'\&amp;');
	invite_date = monthNumString + '/' + dateString + '/' +yearString;


	if (appearingWith.replace(/\s/g,"") != ""){
		$(tdVenueField).append('<div class="tdArtistName">'+ "Appearing with " + appearingWith +'</div>');
	}
	$(tourVenueBuyWrapper).append(tdVenueField);
	onclickString = "populateInviteData('"+ invite_title + "','"+invite_location+"','"+invite_date +"');";
	$(tourVenueBuyWrapper).append('<div class="iggli-invite-button"><a class="iggli-button" onclick="' + onclickString + '">Invite Friends</a></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(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;
	if ($(xmlDom).find('item').length <= 0){
			$(tourDatesWrapper).append('<span class="tdErrorText">'+ tdNoShowsText + '</span>');
		}else {
			if(!tdAllFlag && totalTourItems > tourDateLimit && $("body").is("#homepage_ss2")) {
				$(tourDatesWrapper).append('<div class="tdViewAll header"><a href="' + tdViewAllLink + '">VIEW MORE</a></div');
			}
		}
	

	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(){
			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) {
				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;
		}
	}
};

