/* ********* 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-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="161";//Do not change this partner id

var monthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",
			"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

/* ********* News Module */
/* Sets the maximum number of news to be shown with in the module.*/
var newsMaxItems = 4; 

/*This is the View All Link of the Tour Date module.*/
var tdNewsViewAllLink="/news/"; 

/* Text that is displayed when no shows are available */
var tdNoNewsText="No news reported. Check again later";

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 = 2;


		var csOrdinates = {
		  "active": {
		            "left": [0, 75, 164],
		            "top": [-44, -44, -44],
		            "height": "252",
			    "width":"225"
		        },
				
		  "normal": {
		             "left": [0, 164],
		             "top": [0, 0],
		             "height": "180",
			     "width":"150"
		        }
		    };

		csObj = new CellStream(csOrdinates, div, data, itemsPerPage);
		csObj.csItem();	
	});
	}
	
	else if($(div).attr("id") == "rss_content-3238496" ){
	 /* c=data;
	  
	  b=div;*/a=format;
    jQuery.getFeed({xml:data,success:function(g){jQuery(div).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>";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(div).append(e)}})
    
  }
/*
	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);		
	}
	else if (div.attr("id") == "rss_content-3217663") {
		
		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.
		 	 */
			tdNewsAllFlag = 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.
		 	 */
			tdNewsAllFlag = true;
		}
		newsWrapper = newsBuildStructure(tdNewsAllFlag,data);
		div.append(newsWrapper);		
	}
	/* 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 Matt White");
		$("#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, showTime){
		
	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}\/\d{4}/);
	var dateString = "";
	var monthString = "";
	var yearString = "";
	if(dateInTitle != null ) {
		var dateArray = dateInTitle.split("\/");
		//monthNameString = monthNames[dateArray[0]-1];
		monthString = dateArray[0];
		dateString = dateArray[1];
		yearString = dateArray[2];		
	}
	
	//Values for iggli variables
	//var newDate = new Date();
	//var yearString = newDate.getFullYear();	
	var invite_title = title.replace(/\'/g,"\\'");
	var invite_title = title.replace(/\&/g,'\&amp;');
	var invite_location = venueName + $.trim(venueLocation);
	var invite_location = invite_location.replace(/\'/g,"\\'");
	var invite_location = invite_location.replace(/\&/g,'\&amp;');
	var invite_date = monthString + '/' + dateString + '/' +yearString;
	
	//$(tdDateUnit).append('<div class="tdMonth">'+ monthString +'</div><div class="tdDD">'+ dateString +'</div>');
	$(tdDateUnit).append('<div class="tdDate">'+ monthString +'.'+ dateString +'.'+ yearString.substr(2,2) +'</div>');

	onclickString = "populateInviteData('"+ invite_title + "','"+invite_location+"','"+invite_date +"');";
	//$(tdDateUnit).append('<div class="iggli-invite-button"><a class="iggli-button" onclick="' + onclickString + '">Invite Friends</a></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>";
	venueString="";
	//if ($.trim(venueLocation) != "" ){venueString += $.trim(venueLocation)}
	if ($.trim(venueCity) != "" || $.trim(venueState) != "" ){
		venueString += ($.trim(venueCity)+' '+$.trim(venueState));
	}
	//venueString += "</span>"
	$(tdVenueField).append('<div class="tdVenue">' + $.trim(venueName) +', '+ $.trim(venueString) + '</div>' );
	
	if ($.trim(buyLink)!= ""){
	//$(tdVenueField).append('<div class="tdBuyLinks"><a class="eventbuylink" target="_blank" href="'+ buyLink +'">Buy Tickets</a></div>');
	}
	
	if (appearingWith.replace(/\s/g,"") != ""){
		$(tdVenueField).append('<div class="tdArtistName">'+ "Appearing with: " + appearingWith +'</div>');
	}
	if (showTime != "") {
		$(tdVenueField).append('<div class="tdShowTime">'+ "Show Time: " + showTime+'</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 +'">Buy Tickets</a></div>');
		$(tourVenueBuyWrapper).append(tdBuyLinksField);
		$(tourVenueBuyWrapper).append('<div class="clear"></div>');		
	}
	
	/* code to add a hardcoded buylink specfic to Matt White site */
    /*tdBuyLinksField = document.createElement('div');
    $(tdBuyLinksField).attr("class","tdBuyLinksField");
    $(tdBuyLinksField).append('<div class="tdBuyLinks"><a target="_blank" href="http://tixx1.artistarena.com/whitejames/">Buy 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 createNewsUnit(title, pubDate, description,guid){
		
	newsUnit = document.createElement('div');
	$(newsUnit).attr("class","newsUnit");	
	
	//create tour date unit
	tdTitleUnit = document.createElement('div');
	$(tdTitleUnit).attr("class","tdTitleField");
	
	//$(tdTitleUnit).append('<div class="newsTitle"><a target="_blank" href="'+ guid +'">'+title+'</a></div>');
	$(tdTitleUnit).append('<div class="newsTitle">'+title+'</div>');

	//create tourVenueBuyWrapper	
	publishedDate = document.createElement('div');
	$(publishedDate).attr("class","tdPublished");
	$(publishedDate).append('<div class="updated">'+ pubDate +'</div>');

	//create tour venue unit
	newsDescription = document.createElement('div');
	$(newsDescription).attr("class","tdDescription");
	$(newsDescription).append('<div class="description">'+ description +'</div>');
	
	
	$(newsUnit).append(tdTitleUnit);
	$(newsUnit).append(publishedDate);
	$(newsUnit).append(newsDescription);
	$(newsUnit).append('<div class="clear"></div>');
	return newsUnit;
}
function newsBuildStructure(tdNewsAllFlag,data){
	newsCount = 0;
	
	//Load into XML DOM
	xmlDom = getXMLDOM(data);
	newsWrapper = document.createElement('div');
	//$(newsWrapper).attr("class","newsWrapper");
	totalNewsItems = ($(xmlDom).find('item').length);
	newsLimit = tdNewsAllFlag ? totalNewsItems : newsMaxItems;


	var newsItemLen=$(xmlDom).find('item').length;
	var titleText=($(xmlDom).find('item').children("title").text());
	var title;
	var pubDate;
	var description;
	var guid;

	var newsHeaderTitle = ($(xmlDom).find('channel').children("title").text());
	var newsHeaderTitleLink = ($(xmlDom).find('channel').children("link").text());
	newsSectionTitle = document.createElement('div');
	$(newsSectionTitle).attr("class","tdNewsSectionTitle");
	$(newsSectionTitle).append('<div class="newsSectionTitle"><a target="_blank" href="'+ newsHeaderTitleLink +'">'+newsHeaderTitle+'</a></div>');
	$(newsWrapper).append(newsSectionTitle);

	if (!(newsItemLen == 1 && (jQuery.trim(titleText).indexOf("Sorry",0)!=-1))) {
		$(xmlDom).find('item').each(function(){
			title = $(this).children("title").text();
			pubDate = $(this).children("pubDate").text();
			description = $(this).children("description").text();
			guid = $(this).children("guid").text();
			newsUnit = createNewsUnit(title, pubDate, description,guid);
			$(newsWrapper).append(newsUnit);
			newsCount++;
			if (newsCount == newsLimit) {
				return false;
			}
		})
	}

	if ($(xmlDom).find('item').length <= 0){
		$(newsWrapper).append('<span class="tdErrorText">'+ tdNoNewsText + '</span>');
	}else if (jQuery.trim(titleText).indexOf("Sorry",0)!=-1) {
			writeToConsole("Not able to get feed");
			$(newsWrapper).append('<span class="tdErrorText">'+ tdNoNewsText + '</span>');
	}else {
		if(!tdNewsAllFlag && totalNewsItems > newsLimit) {
			$(newsWrapper).append('<div id="tdNewsViewAllLink"><a target="_blank" href="' + tdNewsViewAllLink + '">VIEW MORE</a></div');
		}
		if(tdNewsAllFlag) {
			$(newsUnit).addClass("lastUnit");
		}
	}
	return newsWrapper;
}
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;
	var venueName;
	var venueCountry;
	var venueLocation;
	var venueState;
	var buyLink;
	var appearingWith;
	var tourDatesUnit;
	var showTime;	

	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();
			showTime = $(this).children("showTime").text();
			tourDatesUnit = createTourDateUnit(title, venueName, venueCountry,venueState,venueCity, venueLocation, buyLink, appearingWith, showTime);
			$(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 target="_blank" 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;
		}
	}
};
