var events = {
	eventItems			: new Object(),
	filteredItems		: new Array(),
	filteredItemsPos	: 0,
	filteredItemsOffset	: 0,
	filteredItemsLimit	: 200,
	lastWrittenCount	: 0,
	currentFeed         : '',
	item_index          : '',
	todays_event        : '0',
	type                : '',
	thisDate            : '',
	thisMonth           : '',
	thisDay             : '',
	thisyear            : '',
	eventsLoaded		: false,
	validDisplayTags    :['community','owners','actionsports','auto_show'],
	totalToShow          : 0,
	
	
	/*Set TIME*/
	setTime : function() {
	    events.thisDate  =  new Date();
	    events.thisMonth = events.thisDate.getMonth() + 1;
	    events.thisDay =   events.thisDate.getDate();
	    events.thisyear =  events.thisDate.getFullYear();    
	},
	
	/*********************************
	 * PUBLIC METHODS                *
	 *********************************/

	// read() converts XML in myFeed into eventItems with help from parseXML()
	read : function(feedID, feedURL, buildNow, divToWriteTo, outputExtraInfo, type, filterIDs, totalToShow) {
		buildNow = buildNow || false;
		outputExtraInfo = outputExtraInfo || false;
		events.type = type;
		
        var feed = new Ajax(feedURL, {
			method: 'get',
			onComplete: function(text, xml) { // text is an unneeded variable though it must be in this function param list
				this.parseXML(feedID, xml);
				if (buildNow) {
					this.update(divToWriteTo, [feedID], filterIDs, outputExtraInfo, totalToShow);
				}
			}.bind(this)
		}).request();
    },
    
	// update() handles the outputting of information to the page
	// divToWriteTo is the div the feed content (with optional outputExtraInfo) will be put into
	// feedIDs is an array of feed array indices, filterIDs is likewise but of tags
	update : function(divToWriteTo, feedIDs, filterIDs, outputExtraInfo, totalToShow) {

	    events.item_index = 0;
		// Set default for outputting extra info
		outputExtraInfo = outputExtraInfo || false;
		
		// Set default for filterIDs
		filterIDs = filterIDs || [''];
		
		if(totalToShow){
		   events.totalToShow = totalToShow;
		}
	    
	    // Clean out previous data
		this.clearFilteredItems();
		global.clearFilter();
		
	    // Only proceed if parseXML() has fully read in the data
		if (!this.eventsLoaded) {
			setTimeout("events.update('"+divToWriteTo+"', ['"+feedIDs+"'], ['"+filterIDs+"'], "+outputExtraInfo+", "+totalToShow+");", 1000);
			return;
		}
		
		// Setup filters if there are any
		if (filterIDs.length > 0) {
			for (filter in filterIDs) {
				if ($type(filterIDs[filter]) == "string") {
					global.setFilter(filterIDs[filter]);
				}
			}
		}

		// Setup filtered feed items
		for (feed in feedIDs) {
			if ($type(feedIDs[feed]) == "string") {
				this.build(feedIDs[feed]);
			}
		}
		
		// Output items
		this.outputLinks(divToWriteTo, outputExtraInfo);
	},

	// Write filteredItemsLimit number of items to page, direction defaults to 'forward' though can be 'backwards' to traverse backwards 
	outputLinks : function(divToWriteTo, outputExtraInfo, direction) {
	
		// Set default for outputting extra info
		outputExtraInfo = outputExtraInfo || false;
		
		var textConglomerate = '<ul>';
		var itemsWritten = 0;
		divToWriteTo = $(divToWriteTo);

		for (var i = this.filteredItemsPos + this.filteredItemsOffset; i <= this.filteredItemsPos + this.filteredItemsOffset + this.filteredItemsLimit; i++) {

			if ($type(this.filteredItems[i]) == "string") {
				textConglomerate += this.filteredItems[i];
				itemsWritten++;
			}
		}

		textConglomerate += '</ul>';
		
		// Write out filtered items if there are any
		if (events.item_index == 0) {
		    divToWriteTo.setHTML(textConglomerate);
		}else{
		    divToWriteTo.setHTML(textConglomerate);
		    this.setAccordion();
		}
		
		// Update sentinel value
		this.lastWrittenCount = itemsWritten;
		
		// This is very much tied to the specific HTML of the News archive page.  TODO: create a more general solution
		if(outputExtraInfo){
		    if(events.type == "calendar"){
		        // Update info on viewed items
			    if (events.item_index == 0) {
				    divToWriteTo.getParent().getParent().getElement('span').setHTML("I'm sorry, but there are no " + extraInfo + "s scheduled for the month of " + month_name[selectedMonth - 1] + ", "+ selectedYear +".<br />Please choose another category.");
				    $('events_scrollarea').setStyle('visibility', 'hidden');
			    }else{
			        
			        if(events.item_index > 1){
			            var message = "You are now viewing "+ events.item_index  +" " + extraInfo + "s for the month of " + month_name[selectedMonth - 1] + ", "+ selectedYear +"."
			        }else{
			            var message = "You are now viewing "+ events.item_index  +" " + extraInfo + " for the month of " + month_name[selectedMonth - 1] + ", "+ selectedYear +"."
			        }
			        
			        divToWriteTo.getParent().getParent().getElement('span').setHTML(message);
			        
			    }
		    }
		}
	},
	
	
	
	setFilterOffset : function(val) {
		this.filteredItemsOffset = val;
	},
	
	// Set the number of filtered items displayed at a time
	setFilterLimit : function(val) {
		this.filteredItemsLimit = val;
	},

	// Delete a source feed from eventItems
	removeFeed : function(feedID) {
		return delete this.eventItems[feedID];
	},

	// Resets eventItems and filteredItems
	reset : function() {
		this.eventItems = new Object();
		this.clearFilteredItems();
	},

	// Resets just filteredItem
	clearFilteredItems : function() {
		this.filteredItems = new Array();
		this.filteredItemsPos = 0;
	},
	
	
	/*********************************
	 * PRIVATE METHODS               *
	 *********************************/
	
	
	// parseXML() does the actual conversion from RSS <item>s into an in-memory array
	parseXML : function(feedID, feedXML, options) {
		var channel = feedXML.getElementsByTagName('channel')[0];		
		var items = channel.getElementsByTagName('item');
		var itemCount = items.length;
		this.currentFeed = feedID;
		
		this.eventItems[feedID] = new Object();
		
		// Loop through all <item>s and build up eventItems
		for (i = 0; itemCount > i; i++) {
			this.eventItems[feedID]["item" + i] = new Object();
			this.eventItems[feedID]["item" + i]["subjects"] = new Array();
			this.eventItems[feedID]["item" + i]["description"] = new Object();
			
			var nodeCount = items[i].childNodes.length;
			for (n = 0; nodeCount > n; n++) {
				// if current node is an element and it has a child...
				if ((items[i].childNodes[n].nodeType == 1 && items[i].childNodes[n].firstChild) || (items[i].childNodes[n].nodeName == 'enclosure')) {
					// if current node is a tag node...
					if (items[i].childNodes[n].nodeName == "dc:subject") {
					
						// push the tag value into the list of subjects for this item
						if(items[i].childNodes[n].attributes.getNamedItem("category").value != "System Tag"){
						    //this.eventItems[feedID]["item" + i]["subjects"] = items[i].childNodes[n].firstChild.nodeValue.split(' ');
						    this.eventItems[feedID]["item" + i]["subjects"].push(items[i].childNodes[n].firstChild.nodeValue);
						}
						
					}
					else {
						// push XML node and value into eventItems array
						this.eventItems[feedID]["item" + i][items[i].childNodes[n].nodeName] = items[i].childNodes[n].firstChild.nodeValue;
						
						// if this is the testimonials feed and we have the description node, overwrite the just-set value with the actual description from the feed
						if (items[i].childNodes[n].nodeName == "description") {
							// push the description node into the eventItems array
							// Get the paragraphs, see if there are any, find the first one and grab its textContent
							if ((items[i].childNodes[n].getElementsByTagName('p'))[0] && (items[i].childNodes[n].getElementsByTagName('p'))[0].firstChild) {
								this.eventItems[feedID]["item" + i]["description"] = (items[i].childNodes[n].getElementsByTagName('p'))[0].firstChild.nodeValue;
							}
						}
					}
				}
			}
		}
		//Events are now loaded and fully parsed, build() is now allowed to fire
		this.eventsLoaded = true;
	},

	// Looks for tag-matches between the current filters and all the items in eventID, writes data about matches back to document inside of elt
	build : function(eventID) {
		var newItemLayout = '';
		
		for (item_instance in this.eventItems[eventID]) {
			// Loop only over the itemX children in eventItems
			if (typeof(this.eventItems[eventID][item_instance]) == 'object') {
				var curItem = this.eventItems[eventID][item_instance];
				var subjectsCount = curItem['subjects'].length;
				var filtersCount = global.filtersArray.length;

				// if current node is pubDate, make date consistent
				if (this.eventItems[eventID][item_instance]['pubDate']) {
					var pubDate = this.eventItems[eventID][item_instance]['pubDate'];
					
					// this is setup to fix a date that looks like this: Wed, 21 Nov 2007 10:57:53 -0500
					if (pubDate.indexOf(':') != -1) {
						var dates = this.splitter(this.splitter(pubDate, ', ')[1], ' ');
						var newdate = dates[1] + ' ' + dates[0] + ', ' + dates[2];
						
						// change node value
						this.eventItems[eventID][item_instance]['pubDate'] = newdate;
						}
				}
				
				
				// If filtersArray is set
				if (global.filtersArray != '' && global.filtersArray != 'undefined' && global.filtersArray != null) {
					// Loop through subjects and find a match to any of the filters
					for (i = 0; subjectsCount > i; i++) {
						// Loop through filters
						for (j = 0; filtersCount > j; j++) {
							// if the current subject matches the current filter, stick the output of build_helper() into the filteredItems array
							if (curItem['subjects'][i] == global.filtersArray[j]) { 
							
							    if(events.type == "calendar"){
							        var newItem = events.build_helper_calendar(curItem, eventID);
							    }else{
							        var newItem = events.build_helper(curItem, eventID);
							    }
		
								var duplicate = false;
								
								// for (item in this.filteredItems) { // changed from item to item_instance_two
								for (item_instance_two in this.filteredItems) {
									if ($type(this.filteredItems[item_instance_two]) == 'string' && this.filteredItems[item_instance_two] == newItem) {
										duplicate = true;
										break;
									}
								}
								
								if (!duplicate) {
								    
								     if(newItem){
									    this.filteredItems.push(newItem);
									 }
									
								}
							}
						}
					}
				}
				// if filtersArray is empty
				else {
				    if(events.type == "calendar"){
				        var newItem = events.build_helper_calendar(curItem, eventID);
				        
				        if(newItem){
				            this.filteredItems.push(newItem);
				        }
				        
				    }else{
				        var newItem = events.build_helper(curItem, eventID);
				        
				        if(newItem){
				            this.filteredItems.push(newItem);
				        }

				    }
					
				}
			}
		}  
		
        /* Not sure if we need this yet, but Tracking looks like its working fine with out it.
        $$('.copy').each(function(f){
		    $(f).onclick = function(){
		    var linkName = $(f).getFirst().innerHTML;
			    _hbSet('lid', linkName + ' Story Link');
			    _hbSet('lpos', eventID);
			    _hbSend();
		    }
	    });*/
		
	},

	build_helper_calendar : function(item, feedID) {

		var itemLayout = '';
	    var accordionPrefix = this.currentFeed;
	    
	    //Check to see if there is a start day.
	    if(item['start_date'] != "//"){
	        var startDateArray = item['start_date'].split("/");
	        
	         for(curStartDateValue in startDateArray){
	            if(typeof(startDateArray[curStartDateValue]) == "string"){
	                startDateArray[curStartDateValue] = parseInt(startDateArray[curStartDateValue]);
	            }
	        }
	        
	        var startDay = startDateArray[1];
	    }
	
	   
	    
	    //Check to see if there is an end day, if not make the same as start day.
	    if(!item['end_date']){
	        item['end_date'] = "//";
	    }
	   
	    if(item['end_date'] != "//"){
	        var endDateArray = item['end_date'].split("/");
	        
	        for(curEndDateValue in endDateArray){
	            if(typeof(endDateArray[curEndDateValue]) == "string"){
	                endDateArray[curEndDateValue] = parseInt(endDateArray[curEndDateValue]);
	            }
	        }
	    
	        var endDay = endDateArray[1];
	    }else{
	        var endDateArray = item['start_date'].split("/");
	        
	        for(curEndDateValue in endDateArray){
	            if(typeof(endDateArray[curEndDateValue]) == "string"){
	                endDateArray[curEndDateValue] = parseInt(endDateArray[curEndDateValue]);
	            }
	        }
	        
	        var endDay = startDateArray[1];
	    }
	    
	    
	      //Find a valid display tag from the validDisplayTags
           for(i = 0;i < item["subjects"].length; i++){
                for(j = 0;j < events.validDisplayTags.length; j++){
           
                    if(item["subjects"][i] == events.validDisplayTags[j]){
                        var itemTopic = item["subjects"][i];
                    }
                }
           }
           
         
         

	    //Check to see if Item is within the Date of the current Month and Year.
	    if((startDateArray[2] == selectedYear) && (startDateArray[0] == selectedMonth || endDateArray[0] == selectedMonth)){
            
           
            
            
	        //Check end date for overlapping months
             if(startDay > endDay){
             
                if(selectedMonth == startDateArray[0]){
                   var i = startDay;
                   var total = parseInt(monthTotalDays);
                }else{
                   var i = 1;
                   var total = endDay;
                }
                
             }else if(startDay <= endDay){

                if(selectedMonth == startDateArray[0]){
                     var i = startDay;
                     var total = endDay;
                }else{
                     var i = startDay;
                     var total = parseInt(monthTotalDays);
                }
             }
             
              
              //Draw Items into the calendar 
              for (i; i <= total; i++) {
                var thisCalendarData = $('date_'+i).innerHTML;
                var calendarDayData = "";
                calendarDayData += thisCalendarData;
                calendarDayData += '<a class="key"  title="'+item['title']+'<br/>'+item['location']+'" href="javascript:events.toggleAccordion('+events.item_index+');"><img src="/shared/images/experience/calendar/'+itemTopic+'_sm.gif"/></a>';
                $('date_'+i).setHTML(calendarDayData);
              }
         
         
		    itemLayout += '<li class="'+itemTopic+'">';
		        itemLayout += '<div class="'+accordionPrefix+'Toggler autoclear">';
		            itemLayout += '<img class="event_image" src="/shared/images/experience/calendar/'+itemTopic+'_lg.jpg"/>'+item['title']+'<span class="location">'+item['location']+'</span>';
	                itemLayout += '<span class="date">';
	                itemLayout += item['start_date'];
            		
	                //if end date
	                if(item['end_date'].length > 2){
	                    itemLayout += " - " + item['end_date'];
	                }
            		
	                if(item['start_time'].length > 2){
	                    itemLayout += "<br />" + item['start_time'];
	                }
            		
	                if(item['end_time'].length > 2){
	                    itemLayout += " to " + item['end_time'];
	                }
            		
	                itemLayout += '</span>';
		            itemLayout += '<div class="autoclear">';
		            itemLayout += '<br/>';
		            itemLayout += '</div>';
		        itemLayout += '</div>';
        		
		        itemLayout += '<div class="'+accordionPrefix+'Accordion">';
		            itemLayout += '<p class="description">'+item['description']+'</p>';
		           if(item['link'] != "" && item['link'] != undefined && item['link_name'] != "" && item['link_name'] != undefined){
		                
		                    var link = ""
		                     //Check to see if the link is internal or external.
		                    if(item['link'].indexOf("www.jeep.com") > 0){
		                        link = item['link'];
		                    }else{
		                        //link = "http://www.jeep.com/en/experience/bounce.html?item=" + escape(item['link']);
								link = "/en/experience/bounce.html?item=" + escape(item['link']);
		                    }
		                     itemLayout += '<a class="moreInfo" title="Event'+' '+item['title']+' '+item['start_date']+' '+item['end_date']+' '+item['location']+' '+'" name="&lid=Event '+item['start_date']+' - '+item['end_date']+ ' ' + item['location'] +'&lpos=Jeep Events Nav" href="'+link+'" target="_new">'+item['link_name']+'<img src="/shared/images/experience/title_arrow.png"/>';
		                
		                itemLayout += '</a>';
		            } else {
		                itemLayout += '<br />';
		            }
		        itemLayout += '</div>';
		    itemLayout += '</li>';

		    events.item_index++;
		}
		return itemLayout;
	},
	
	build_helper: function(item, feedID) {
		var itemLayout = '';
	    var accordionPrefix = this.currentFeed;
	    
	   
	     //Check to see if there is a start day.
	    if(item['start_date'] != "//"){
	        var startDateArray = item['start_date'].split("/");
	        
	         for(curStartDateValue in startDateArray){
	            if(typeof(startDateArray[curStartDateValue]) == "string"){
	                startDateArray[curStartDateValue] = parseInt(startDateArray[curStartDateValue]);
	            }
	        }
	        
	        var startDay = startDateArray[1];
	    }
	
	    //Check to see if there is an end day, if not make the same as start day.
	    
	    if(!item['end_date']){
	        item['end_date'] = "//";
	    }
	    
	    if(item['end_date'] != "//" && item['end_date'] != ""){
	        var endDateArray = item['end_date'].split("/");
	        
	        for(curEndDateValue in endDateArray){
	            if(typeof(endDateArray[curEndDateValue]) == "string"){
	                endDateArray[curEndDateValue] = parseInt(endDateArray[curEndDateValue]);
	            }
	        }
	    
	        var endDay = endDateArray[1];
	    }else{
	        var endDateArray = item['start_date'].split("/");
	        
	        for(curEndDateValue in endDateArray){
	            if(typeof(endDateArray[curEndDateValue]) == "string"){
	                endDateArray[curEndDateValue] = parseInt(endDateArray[curEndDateValue]);
	            }
	        }
	        
	        var endDay = startDateArray[1];
	    }
	   
	         //Find a valid display tag from the validDisplayTags
           for(i = 0;i < item["subjects"].length; i++){
                for(j = 0;j < events.validDisplayTags.length; j++){
                    if(item["subjects"][i] == events.validDisplayTags[j]){
                        var itemTopic = item["subjects"][i];
                    }
                }
           }
	
	    //Check to see if Item is within the Date of the current Month and Year.
	    if((((startDateArray[0] == selectedMonth && startDateArray[1] >= selectedDay && startDateArray[2] == selectedYear) || (endDateArray[0] == selectedMonth && endDateArray[1] >= selectedDay && endDateArray[2] == selectedYear)) || ((startDateArray[0] > selectedMonth || endDateArray[0] > selectedMonth) && startDateArray[2] == selectedYear) || (startDateArray[2] > selectedYear || endDateArray[2] > selectedYear)) && events.item_index < events.totalToShow && item['location'] != "no_events"){
	   
		    itemLayout += '<li class="'+itemTopic+'">';
		        itemLayout += '<div class="'+accordionPrefix+'Toggler autoclear">';
		            itemLayout += '<img class="event_image" src="/shared/images/experience/calendar/'+itemTopic+'_lg.jpg"/>'+item['title']+'<span class="location">'+item['location']+'</span>';
	                itemLayout += '<span class="date">';
	                itemLayout += item['start_date'];
            		
	                //if end date
	                if(item['end_date'].length > 2){
	                    itemLayout += " - " + item['end_date'];
	                }
            		
	                if(item['start_time'].length > 2){
	                    itemLayout += "<br />" + item['start_time'];
	                }
            		
	                if(item['end_time'].length > 2){
	                    itemLayout += " to " + item['end_time'];
	                }
            		
	                itemLayout += '</span>';
		            itemLayout += '<div class="autoclear">';
		            itemLayout += '<br/>';
		            itemLayout += '</div>';
		        itemLayout += '</div>';
        		
		        itemLayout += '<div class="'+accordionPrefix+'Accordion">';
		            itemLayout += '<p class="description">'+item['description']+'</p>';
		            
		             if(item['link'] != "" && item['link'] != undefined && item['link_name'] != "" && item['link_name'] != undefined){
		                
		                 var link = ""
		                    //Check to see if the link is internal or external.
		                    if(item['link'].indexOf("www.jeep.com") > 0){
		                        link = item['link'];
		                    }else{
		                        //link = "http://www.jeep.com/en/experience/bounce.html?item=" + escape(item['link']);
								link = "/en/experience/bounce.html?item=" + escape(item['link']);
		                    }
		                     itemLayout += '<a class="moreInfo" title="Event'+' '+item['title']+' '+item['start_date']+' '+item['end_date']+' '+item['location']+' '+'" name="&lid=Event '+item['start_date']+' - '+item['end_date']+ ' ' + item['location'] +'&lpos=Events Nav" href="'+link+'" target="_new">'+item['link_name']+'<img src="/shared/images/experience/title_arrow.png"/>';
		                     itemLayout += '</a>';
		            }else{
		                itemLayout += '<br />';
		            }
		            
		        itemLayout += '</div>';
		    itemLayout += '</li>';

		    events.item_index++;
		}
		return itemLayout;
	},
	
	splitter : function(item, spliton) {
		return item.split(spliton);
	},
	
	setAccordion : function() {
	    var accordionPrefix = this.currentFeed;

	        if(events.type == "calendar"){
	      
	             global.initAccordion('events','div.'+accordionPrefix+'Accordion','div.'+accordionPrefix+'Toggler', true, false, "global.setScrollBar");
	             
	            /*Loop thru days and find one from the current day to end of the month
	            if(selectedMonth == events.thisMonth){
	                for(i = parseInt(selctedDay); i <= parseInt(monthTotalDays); i++){
	                    var d = $('date_'+i).innerHTML;
	                    if(d.length > 2){
	                        var item = d.indexOf('(');
	                        item = d.charAt(item + 1);
	                        events.todays_event = item;
	                        break;
	                    }
	                }
	            }
        	    
	            //If there are no events for this month, don't fire toggle.
                if(events.item_index){
                    acc.togglers[events.todays_event].fireEvent('click');
                    events.todays_event = 0;
                }*/
                
               /*Turn on First Event of the month*/
                if(events.item_index){
        	        acc.togglers[0].fireEvent('click');
        	    }
        	   
               global.scrollBar('events');
               global.makeTips({x:-44,y:-75},'.key','events-tool');
  
          }else{
                global.initAccordion('events','div.'+accordionPrefix+'Accordion','div.'+accordionPrefix+'Toggler', true, false);
                acc.togglers[0].fireEvent('click');
          }
          
        if (window.ie6){iePngFix();}
        
         //Event Tracking for HBX
        $$('.moreInfo').each(function(f){
		    $(f).onclick = function(){
		    var linkName = $(f).getAttribute('title');
			    _hbSet('lid', linkName);
			    _hbSet('lpos', 'Events Nav');
			    _hbSend();
		    }
	    });
	    
	},
	
	toggleAccordion: function(argItem) {
	    acc.togglers[argItem].fireEvent('click');
	}
}


onload_register('events.setTime();');


// function always returns the correct year when passed a 2 digit year number
function takeYear(theDate) {
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}