// JavaScript Document
$().ready( function () {
	
	if($id('home_cal_left')){
	
	$('#upcoming_events').hide();
	$('#home_calendar').show();
  	$("#minileft .events_toggle").click(function(ev){
	 	toggle_events(this);
 		ev.preventDefault();
	});
	
	hp.getCal();
	
	};
 	

}); // end dom ready
var eventInfo = {};
hp = {  // home page
	currentlyOpen: '',
	currentOpenDay: 0,
	firstEventDay: 35, // first day in month with an event
	lastEventDay: 0, // last day in month with an event
	goTo: '', // if the event arrows
	getEventsNumTries: 0, // a way to limit the number of times we try to get the next event
	arrow_click: false, // a way to distinguish from a fresh page load versus a arrow click - this will let us prevent the search for the next event
	setVisEventArrows: function ( compareDay )
	{
		// check first
		if ( compareDay == hp.firstEventDay ) {
			//$id('prev_event').style.visibility = 'hidden';
		} else {
			$id('prev_event').style.visibility = 'visible';
		}
		// check last
		if ( compareDay == hp.lastEventDay ) {
			//$id('next_event').style.visibility = 'hidden';
		} else {
			$id('next_event').style.visibility = 'visible';
		}
		
	}, // end func set vis event arrows
	findNextEvent: function ()
	{
		var holdDay = 1000;
		for( i in eventInfo ) {
			if ( eventInfo[i].day > hp.currentOpenDay && eventInfo[i].day < holdDay ) {
				holdDay = eventInfo[i].day;
			} // end if 
		} // end for in event info
		if ( holdDay == 1000 ) {
			var nextMon = (parseInt(eventInfo.thisMonth)%12) + 1;
			if( nextMon == 1 ) {
				var nextYear = parseInt(eventInfo.thisYear) + 1;
			} else {
				var nextYear = parseInt( eventInfo.thisYear );
			}
			hp.goTo = 'firstDay';
			hp.getCal( nextMon, nextYear );
			return;
		}
		hp.createInfoChunk( holdDay );
		// now that the chunk is in there, decide if which arrows should show
		hp.setVisEventArrows( holdDay )
	}, // end find next event
	
	findPrevEvent: function ()
	{
		if ( hp.currentOpenDay == 0 ) { // current event is not set so if this is clicked it means no event has really been "chosen" so this button just shows first event
			this.findNextEvent();
			return;
		}
		var holdDay = 0;
		for( i in eventInfo ) {
			if ( eventInfo[i].day < hp.currentOpenDay && eventInfo[i].day > holdDay ) {
				holdDay = eventInfo[i].day;
			} // end if 
		} // end for in event info
		
		if ( holdDay == 0 ) { // move to next month
			var nextMon = (parseInt(eventInfo.thisMonth)%12);
			if(nextMon == 1 ) {
				nextMon = 12;
				var nextYear = parseInt(eventInfo.thisYear) - 1;
			} else {
				var nextYear = parseInt( eventInfo.thisYear );
			}
			if( nextMon == 0 ) {
				nextMon = 11;
			}
			if ( nextMon != 11 && nextMon != 12 ) {
				nextMon--;
			}
			cl( 'next mmonth: ' + nextMon );
			hp.goTo = 'lastDay';
			hp.getCal( nextMon, nextYear );
			return;
		}
		
		hp.createInfoChunk( holdDay );
		// now that the chunk is there decide which arrows should show up
		hp.setVisEventArrows( holdDay );
	}, // end find prev event
	
	getCal: function ( month, year ) {
		// reset the current open day to zero to contain next / prev event clicks
		hp.currentOpenDay = 0;
		hp.lastEventDay = 0;
		hp.firstEventDay = 35;
		if ( typeof month == 'undefined' ) {
			var d = new Date();
			month = (d.getMonth() + 1); // starts with 0
			year = d.getFullYear();
		}
		$.get( '/ajax_content/event_calendar_home.php', { 'mon':  month, 'year': year }, function (resp) {
			
			respArr = resp.split( '|=|' );
			eval( '(' + respArr[0] + ')' ); // creates object 'eventInfo'
			
			// if no events in this month try up to 6 times to find an event
			if( eventInfo.numEvents == '0' && hp.getEventsNumTries < 6 && !hp.arrow_click )
			{ // look for next month
			  hp.getEventsNumTries++;
			  var next_try_month = parseInt( eventInfo.thisMonth );
			  var next_try_year = parseInt( eventInfo.thisYear );
			  if( next_try_month == 12 )
			  {
				next_try_month = 1;
				next_try_year  = ( year + 1 );
			  }
			  else
			  {
			     next_try_month = ( next_try_month + 1 );
			  }
			  hp.getCal( next_try_month, next_try_year );
			  return;
			} 
			else if( hp.getEventsNumTries == 6 && !hp.arrow_click )
			{ // in this circumstance we have looked 6 months ahead and still not found anything - this is the 7th attempt - just grab this month and say nona avail
				hp.getEventsNumTries = 7; // so we don't get into an infinite loop
				var d = new Date();
				var this_month = ( d.getMonth() + 1 );
			    var this_year = d.getFullYear();
				hp.getCal( this_month, this_year );
				return;
			}// end if num events is none
			
			$id('home_cal_left').innerHTML = respArr[1]; // set calendar html
			
			
			if ( $id('home_cal_right').innerHTML.match(/\S/) ) {
				// already have content - so we don't want to change it?
				// but do set the first  and last event dates
				
				for( i in eventInfo ) {
					if ( eventInfo[i].day < hp.firstEventDay ) {
						hp.firstEventDay = eventInfo[i].day;	
					}
					if ( eventInfo[i].day > hp.lastEventDay ) {
						hp.lastEventDay = eventInfo[i].day;	
					}
				} // end for loop
				// if we clicked on a next / prev arrow and changed months - then we need to set the first or last event
				// if in current month we want to default to the next event in this month
				var test_d = new Date();
				test_month = (test_d.getMonth() + 1);
				if ( eventInfo.thisMonth == test_month ) { 
					var nextDate = hp.getNearestDate();
					hp.createInfoChunk( nextDate );
				} else {
					if ( hp.goTo == 'lastDay' ) {
						hp.createInfoChunk( hp.lastEventDay );
					} else {
						hp.createInfoChunk( hp.firstEventDay );
					}
					
					if ( $id('prev_event') ) {
					
					if ( eventInfo.numEvents == '0' || eventInfo.numEvents == '1'  ) {
						$id('prev_event').style.visibility = 'hidden';
						$id('next_event').style.visibility = 'hidden';
					} else {
						$id('prev_event').style.visibility = 'visible';
						$id('next_event').style.visibility = 'visible';
					}
				} // end if else in current month
			} // end if prev event exists
				return;
			}
			// set the next event date
			var d = new Date( );
			
			// d.getDate() is unreliable in IE - only returned one digit 
			var today = eventInfo.thisDay;
			var d = new Date();
	
			var thisMonth = (d.getMonth() + 1);
			// if we're looking in the next month then set today to zero
			if ( eventInfo.thisMonth != thisMonth ) {
				today = 0;
			}
			
			// cycle through the event object and find the next event date
			var nearestNextDate = hp.getNearestDate(); // init to 1000 - way more days than in a month

					
			if ( nearestNextDate != 1000 ) { // we found the next nearest date in this month
				hp.createInfoChunk( nearestNextDate );
			} else if ( eventInfo.thisMonth == thisMonth ) { // we did not find a next nearest date - but this month is same as next month so ok to look one month beyond
				// if jan - then want feb - if december want jan next year
				var nextMonth = ((thisMonth % 12) + 1 );
				if ( nextMonth == 1 ) { // if we increased the month to next year
					var nextYear = ( d.getFullYear() + 1 ); // increase the year to next year
				} else {
					var nextYear = d.getFullYear();
				}
				hp.getCal( nextMonth, nextYear ); // next year is usually this year - misnomer - sorry
			} else {
				// get out of season chunk
				//cl( 'get out of season chunk' );
			}
			//cl( 'next date: ' + nearestNextDate );
		});
	}, //end get cal
	
	getNearestDate: function () {
		// cycle through the event object and find the next event date
		var nearestNextDate = 1000; // init to 1000 - way more days than in a month
		var d = new Date( );
			
		// d.getDate() is unreliable in IE - only returned one digit 
		var today = eventInfo.thisDay;
		var d = new Date();

		var thisMonth = (d.getMonth() + 1);
		// if we're looking in the next month then set today to zero
		if ( eventInfo.thisMonth != thisMonth ) {
			today = 0;
		}
		
		for ( var i in eventInfo ) {
			if ( eventInfo[i].day >= today && eventInfo[i].day < nearestNextDate ) {
				nearestNextDate = eventInfo[i].day;
			}// end if
			// also set first and last day of month
			if ( eventInfo[i].day < hp.firstEventDay ) {
				hp.firstEventDay = eventInfo[i].day;	
			}
			if ( eventInfo[i].day > hp.lastEventDay ) {
				hp.lastEventDay = eventInfo[i].day;	
			}				
		} // end for loop
		return nearestNextDate;
	}, // end get nearest date func
	
	createInfoChunk: function ( day ) {
		
		//$('.event > p', $id( 'home_cal_left' ) ).unbind('click')
		this.currentOpenDay = day;
		var concertsArr = [];
		var rehersalsArr = [];
		var othersArr = [];
		var eventDate = '';
		for( var i in eventInfo ) {
			if ( eventInfo[i].day == day ) { // put the correct info into these arrays
				if ( eventInfo[i].event_instance_type_id == '1' ) {
					concertsArr.push( i );
				} else if ( eventInfo[i].event_instance_type_id == '2' ) {
					rehersalsArr.push( i );
				} else {
					othersArr.push( i );
				}
				eventDate = eventInfo[i].heading_date;
			} // end if day
			
		} // end for i in event info 
		// first_switch    selected      
		var htmlHeadChunk = '\
            <div id="home_cal_right_head"><a id="prev_event" style="float: left; padding: 11px 0 0 5px;"; onclick="hp.findPrevEvent(); return false;" href="#">\
<img src="/images/wht_arrow_left.gif"/>\
</a><p style="float: left; width: 160px; text-align: center;">' + eventDate + '</p><a id="next_event" style="float: right; padding: 11px 5px 0 0;"; onclick="hp.findNextEvent(); return false;" href="#">\
<img src="/images/wht_arrow_right.gif"/>\
</a></div>\
            <ul class="event_type_switch">\
            <li class="concerts first_switch none_available">Concerts</li>\
            <li class="rehearsals none_available">Rehearsals</li>\
            <li class="other none_available">Other</li>\
            </ul>\
			 <div id="cal_event_wrap"><!-- use as ID -->\
		';
		var htmlConcerts = '<div id="concerts" class="hidden" >' + hp.getChunkHTML( concertsArr ) + '</div>';
		
		var htmlRehersals = '<div id="rehearsals" class="hidden" >' + hp.getChunkHTML( rehersalsArr ) + '</div>';
		
		var htmlOthers = '<div id="other" class="hidden" >' + hp.getOtherChunkHTML( othersArr ) + '</div>';
		
		var htmlClosing = '</div>';
		
		if( eventInfo.numEvents == '0' ) {
			htmlConcerts = '<p style="text-align:center; margin: 50px 20px 0; color: #666666">There are no events scheduled for this month</p>';
		}
		
		$id('home_cal_right').innerHTML = ''; // reset the content
		//$('#home_cal_right').prepend( htmlHeadChunk + htmlConcerts + htmlRehersals + htmlOthers + htmlClosing );
		var holdHTML = html_entity_decode(htmlHeadChunk + htmlConcerts + htmlRehersals + htmlOthers + htmlClosing);
		//holdHTML = holdHTML.replace( /’/, "'");
		$id('home_cal_right').innerHTML = holdHTML;
		$( $id('concerts') ).removeClass('hidden');
		$( $id('rehearsals') ).removeClass('hidden');
		$( $id('other') ).removeClass('hidden');
		$('.scroll_hold').jScrollPane();
		$( $id('concerts') ).addClass('hidden');
		$( $id('rehearsals') ).addClass('hidden');
		$( $id('other') ).addClass('hidden');
		
		this.initEls( concertsArr.length, rehersalsArr.length, othersArr.length ); 
		this.setCurrentDiv( day );
		this.setVisEventArrows( day );
	},
	setCurrentDiv: function ( day ) {
		for ( var i = 0; i < $id('home_cal_left').getElementsByTagName('td').length; i++ ) {
			// turn them all off
			var divEl = $id('home_cal_left').getElementsByTagName('td')[i].getElementsByTagName('div')[0];
			if ( divEl ) {
				divEl.className = divEl.className.replace( /\sevent_select/, '' );
			}
		} // end for loop
		for ( var i = 0; i < $id('home_cal_left').getElementsByTagName('td').length; i++ ) {
			// turn them all off
			if ( $id('home_cal_left').getElementsByTagName('td')[i].getElementsByTagName('div')[0] ) {
				var pTag = $id('home_cal_left').getElementsByTagName('td')[i].getElementsByTagName('div')[0].getElementsByTagName('p');
				if ( pTag[0] ) {
					
					if ( pTag[0].innerHTML == day ) {
						$id('home_cal_left').getElementsByTagName('td')[i].getElementsByTagName('div')[0].className += ' event_select';
					} // end if == day
				} // end if pTag
			} // end if div 0 exists
		} // end for loop
	},
	toggleContent: function ( el )
	{
		
		this.hideAll();
		
		this.currentlyOpen = el.innerHTML
		var ch_id = el.innerHTML.toLowerCase();
		$('li.'+ch_id, $id('home_cal_right') ).addClass('selected');
		
		$id(ch_id).className = '';
		$('.scroll_hold').removeClass('scroll_pane');
		
	},
	
	hideAll: function ()
	{
		// to avoid doubling the class - lets remove before we add
		$( $id('concerts') ).removeClass('hidden');
		$( $id('rehearsals') ).removeClass('hidden');
		$( $id('other') ).removeClass('hidden');
		
		$( $id('concerts') ).addClass('hidden');
		$( $id('rehearsals') ).addClass('hidden');
		$( $id('other') ).addClass('hidden');
		
		$('li.concerts', $id('home_cal_right') ).removeClass('selected');
		$('li.rehearsals', $id('home_cal_right') ).removeClass('selected');
		$('li.other', $id('home_cal_right') ).removeClass('selected');
	},
	initEls: function (coLen, rhLen, othLen ) {
		
		// make non-empty tabs available
		if ( coLen ) {
			$('li.concerts', $id('home_cal_right') ).removeClass('none_available').click( function () { hp.toggleContent( this ) } );
		} 
		if ( rhLen ) {
			$('li.rehearsals', $id('home_cal_right') ).removeClass('none_available').click( function () { hp.toggleContent( this ) } );		
		} 
		if ( othLen ) {
			$('li.other', $id('home_cal_right') ).removeClass('none_available').click( function () { hp.toggleContent( this ) } );			
		}// end if else - which tabs to allow clickabel
		
		// decide which content to show
		if ( coLen ) {
			$( $id('concerts') ).removeClass('hidden');
			$('li.concerts', $id('home_cal_right') ).addClass('selected');
			this.currentlyOpen = 'Concerts';
		} else if ( rhLen ) {
			$( $id('rehearsals') ).removeClass('hidden');
			$('li.rehearsals', $id('home_cal_right') ).addClass('selected');
			this.currentlyOpen = 'Rehearsals';
		} else if ( othLen ) {
			$( $id('other') ).removeClass('hidden');
			$('li.other', $id('home_cal_right') ).addClass('selected');
			this.currentlyOpen = 'Other';
		}
		
	},
	getChunkHTML: function ( cArr ) // concert / rehersal 
	{
		
		var holdHTML = "\
	<div class=\"scroll_hold scroll_pane\">\n";
		// cArr contains the IDs on the eventInfo object
		var firstpass = true;
		for ( var i in cArr ) { 
			// cl( 'concertsArr '+ i + ' is: ' + concertsArr[i] );
			var extraClass = '';
			( firstpass ) ? ( extraClass = 'first_event_content') : ( extraClass = '' );
			if ( typeof eventInfo[ cArr[i] ].image_filename == 'undefined' ) {
				im = ''; //eventInfo[ cArr[i] ].image_fileName = ' ';
			} else {
				var im =  eventInfo[ cArr[i] ].image_filename;	
			}
			
        	holdHTML += '\
		<div class="event_content ' + extraClass + '"><!-- begin wrap single event-->\
			<h1><a href="' + eventInfo[ cArr[i] ].slug + '">' + eventInfo[ cArr[i] ].event_title + '&nbsp;<img src="/images/green_arrow.gif"/></a></h1>\
			<div class="cal_event_two_col">\
				<div class="cal_event_two_col_left">\
					' + im + '\
				</div>\
				<div class="cal_event_two_col_right">\
					<p><span class="cal_when_where">When</span><br />\
						' + eventInfo[ cArr[i] ].event_instance_start_time;
						if(eventInfo[ cArr[i] ].event_instance_end_time!='12:00am'){ holdHTML +='&ndash;'+eventInfo[ cArr[i] ].event_instance_end_time; }
						holdHTML += '\
					</p>\
					<p><span class="cal_when_where">Where</span><br />\
						 ' + eventInfo[ cArr[i] ].event_instance_venue + '\
					</p>\
				</div>\
			</div><!-- End cal event two column -->\
		</div><!--end wrap single event-->';
			firstpass = false;
		} // end for in in concertsArr
		
		holdHTML += "\n</div><!--end scroll pane-->";
		return holdHTML;
	},
	
	getOtherChunkHTML: function ( oArr ) // other array
	{
			///        
		var iconImages = {};
		iconImages['TalkBack'] = '<img src="/images/coffeetalk_lrg.gif" alt="" />';
		iconImages['PlayBack'] = '<img src="/images/playback_lrg.gif" alt="" />';
		iconImages['CoffeeTalk'] = '<img src="/images/talkback_lrg.gif" alt="" />';
		iconImages['Fundraiser'] = '<img src="/images/special_event_lrg.gif" alt="" />';
		
		var holdHTML = "\
	<div class=\"scroll_hold scroll_pane\">\n";
		// cArr contains the IDs on the eventInfo object
		var firstpass = true;
		for ( k in eventInfo[oArr[0]] ) {
				cl( k + ' is: ' + eventInfo[oArr[0]][k] );
		}
		for ( var i in oArr ) { 
			// cl( 'concertsArr '+ i + ' is: ' + concertsArr[i] );
			var extraClass = '';
			( firstpass ) ? ( extraClass = 'first_event_content') : ( extraClass = '' );
				
			holdHTML += '\
					<div class="event_content ' + extraClass + '">\
						<div class="other_label">' + iconImages[ eventInfo[ oArr[i] ].event_type_name ] + '\
						</div>\
						<h1>\
							<a href="' + eventInfo[ oArr[i] ].slug + '">' + eventInfo[ oArr[i] ].event_title + '&nbsp;<img src="/images/green_arrow.gif"/></a>\
						</h1>\
						<div class="cal_event_two_col">\
							<p><span class="cal_when_where">When</span><br />\
								' + eventInfo[ oArr[i] ].event_instance_start_time;
						if(eventInfo[ oArr[i] ].event_instance_end_time!=''){ holdHTML +='&ndash;'+eventInfo[ oArr[i] ].event_instance_end_time; }
						holdHTML += '\
							</p>\
							<p><span class="cal_when_where">Where</span><br />\
								 ' + eventInfo[ oArr[i] ].event_instance_venue + '\
							</p>\
						</div><!-- End cal event two column -->\
					</div>\
					';
			
				firstpass = false;
			} // end for in in concertsArr
		
		holdHTML += "\n</div><!--end scroll pane-->";
		return holdHTML;
	}
}; // end hp object





//HOME EVENT CAL UPCOMING TOGGLE
function toggle_events(elem){
	$(elem).removeClass('gray_link');
	if ( elem.id == 'ev_up_toggle' ) {//if you clicked on Upcoming Events
		$('#ev_cal_toggle').addClass('gray_link');//add class 'gray_link' to other toggle
		$('#home_calendar').hide();
		$('#upcoming_events').show();
	
	} else if ( elem.id == 'ev_cal_toggle' ) { //if you clicked on Events calendar
		$('#ev_up_toggle').addClass('gray_link');//add class 'gray_link' to other toggle
		$('#upcoming_events').hide();
		$('#home_calendar').show();
	
	} // end if else elem id
} // end function toggle events
 


