//custom fullCalendar views created for calendarize-it.

(function($){
$.fullCalendar.views.rhc_grid = GridGalleryView;	
function GridGalleryView(element, calendar) {
	var t = this;
	var body;
	t.id = $(element).parents('.rhc_holder').attr('id');
	t.name = 'rhc_grid';
	t.render = render;
	t.unselect = unselect;
	t.setHeight = setHeight;
	t.setWidth = setWidth;
	t.clearEvents = clearEvents;
	t.renderEvents = renderEvents;
	t.trigger = trigger;
	t.viewChanged = viewChanged;
	t.beforeAnimation = beforeAnimation;
	t.transitionStarted = transitionStarted;
	t.transitionEnded = transitionEnded;
	t.setEventData = setEventData; //fc 1.64
	t.clearEventData = clearEventData;//fc 1.64
	t.triggerEventDestroy = triggerEventDestroy;//fc 1.64
	t.viewLeave = viewLeave;
	t.handle_rendered = handle_rendered;
	t.get_norepeat = get_norepeat;
	
	t.element = element;
	t.oldView = null;
	//not part of fc api.
	t.calendar = calendar;//needed for clicking event title.
	fc = $.fullCalendar;
	//--
	t.direction = 0;//direction in wich the user is navigating.
	t.first_date = null;
	t.scroll_lockdown = false;
	t.loading = loading;
	t.have_events = false;
	t.rendered_events = [];
	t.empty_polls = 0;
	
	t.grid_options = $.extend( {
		animonscroll: 'effect-2',
		help:'Navigate with arrow keys',
		source: grid_source,
		date_format_start: 'MMMM d, yyyy hh:mm tt',
		date_format_end: 'MMMM d, yyyy hh:mm tt',
		date_format_start_allday: 'MMMM d, yyyy',
		date_format_end_allday: 'MMMM d, yyyy',
		delta: 30,
		nolink: 0,
		showongoing: true,
		max_empty_polls: 10
	}, t.calendar.options.rhc_grid );	
	
	t.grid_options.showongoing = t.grid_options.showongoing && '1'==t.grid_options.showongoing ? true : false;
	
	t.gridgallery = null;
	t.gridgallery_holder = null;
	t.transitioned = true;
	t.clear_events = false;
	//function fetch_events
	function grid_source( gridgallery ){
		t.gridgallery = gridgallery;
		
	}

	function viewLeave(oldView,newView, c){
		var starting_date = $(element).parents('.rhc_holder').find('.fullCalendar').data('starting_date');
		if( starting_date ){
			$(element).parents('.rhc_holder').find('.fullCalendar').fullCalendar('gotoDate', starting_date );
		}
	}
	
	function viewChanged(oldView){

	}

	function setEventData( events ){

	}
	
	function clearEventData(){
	
	}
	
	function triggerEventDestroy(){

	}

	function viewRender(){

	}
	
	function transitionStarted(oldView){
		t.transitioned = false;	
	}
	
	function transitionEnded(oldView){
		t.transitioned = true;		
		$(element).css('z-index','');
	}
	//not part of fc api.
	function beforeAnimation(oldView){
		
	}

	function render(date,delta){	
		t.direction = delta;
		//---
		date_changed=false;
		first_date = t.first_date || fc.cloneDate( date );
		first_date = ( date < first_date ) ? fc.cloneDate( date ) : first_date ;
		if( t.direction < 0 ){
			body = false;
			if( date > first_date ){
				date = fc.cloneDate( first_date );
				date_changed = true;
			}
		}		
		t.first_date = first_date;
		//---
		custom_delta = parseInt( t.grid_options.delta );
		variation = custom_delta*delta;
		
		fc.addDays( date, variation, true );
		
		start  = fc.cloneDate( date );
		
		end = fc.cloneDate( start );
		fc.addDays(end, custom_delta, true );		
		
		t.title = '';
		t.start 	= start;
		t.visStart 	= fc.cloneDate( start );	
		t.visStart.setHours(0,0,0,0);	
		t.end 		= end
		t.visEnd 	= fc.cloneDate( end );				
		t.visEnd.setHours(23,59,59,0);
		if(date_changed) calendar.gotoDate(date);
		
		var firstTime = !body;
		if(firstTime){	
	
			t.clear_events = false;	
			$(element).find('.rhc_grid-events-holder').remove();
			
			var html = $(
			'<div class="rhc_grid-events-holder rhg-default grid-gallery">' +
			'<section class="grid-wrap"><ul id="rhg_grid_' + t.id + '" class="rhg_grid rhg_grid_items ' + t.grid_options.animonscroll + '"><li class="grid-sizer"></li></ul></section>' +
			'<section class="rhg_slideshow slideshow rhc_holder">' +
				'<ul class="rhg_slideshow_items"></ul>' +
				'<nav>' +
					'<span class="icon rhg-nav-prev"></span>' +
					'<span class="icon rhg-nav-next"></span>' +
					'<span class="icon rhg-nav-close"></span>' +
				'</nav>' +
			'</section>' +			
			'</div>'
			);
			html
				.data('options', t.grid_options)
				.on('more_events_scroll',function(e){more_events_scroll(e);})
				.on('slideshow_more',function(e){more_events_scroll(e);})
				.appendTo(element)
			;
		
			if( $(element).parents('.rhc_holder').find('.grid-item-template').length==0 ){
				$('<div class="grid-item-template"></div>')
					.load( t.grid_options.template, function(){
						$(this).addClass('loaded');
					})
					.hide()
					.appendTo( $(element).parents('.rhc_holder') )
				;
			}
		
			if( t.grid_options.classes && t.grid_options.classes.length > 0 ){
				$(element).addClass( t.grid_options.classes.join(' ') );
				$(element).find('.rhg_slideshow').addClass( t.grid_options.classes.join(' ') );
			}
			
			autoload = true;
			if( t.grid_options.autoload && '0' == t.grid_options.autoload ){
				autoload = false;
			}
			
			html.RHGallery({
				autoload: autoload
			});
			t.gridgallery_holder = html[0];
			body = true;
		}else{
		 
		}
	}

	function handle_rendered(){
		return t.rendered;
	}
	
	function get_norepeat( _default ){
		return t.grid_options && t.grid_options.norepeat ? t.grid_options.norepeat : _default ;
	}
	
	function more_events_scroll(e){
		$(element).parents('.rhc_holder').find('.fullCalendar').fullCalendar('next');	
	}
		
	function unselect(){

	}
	function setHeight(h){
		//element.css('min-height',h);
		element.css('min-height','200px');
		element.css('height','auto');
	}
	function setWidth(){/*console.log('setWidth');*/}
	function clearEvents(){

	}

	function renderEvents(_events, modifiedEventId){
		if( !t.transitioned ){
			setTimeout( function(){renderEvents(_events, modifiedEventId)}, 50 );
			return;
		}	

		var template = $(element).parents('.rhc_holder').find('.grid-item-template');
		if( false == template.is('.loaded') ){
			setTimeout( function(){renderEvents(_events, modifiedEventId)}, 25 );
			return;		
		}

		if( t.clear_events ){
			slideshow_id = $(element).find('.rhc_grid-events-holder').data('slideshow_id');
			slideshow = $('#' + slideshow_id );
				
			t.clear_events = false;
			$(element).find('ul.rhg_grid_items li:not(.grid-sizer)').remove();
			$(element).find('ul.rhg_slideshow_items li').remove();	
			slideshow.find('ul.rhg_slideshow_items li').remove();	
			t.rendered_events = [];		
			t.rendered = [];
		}

		if( $(element).find('ul.rhg_grid_items li:not(.grid-sizer)').length == 0 ){
			t.rendered_events = [];
			t.rendered = [];
		}
		
		t.gridgallery.have_posts = _events.length>0 ? true : false;
		
		griditem = $('<li></li>').append( template.find('.grid-item').clone() ) ;
		slide = $('<li></li>').append( template.find('.grid-slide').clone() ) ;

		if(_events.length>0){	
			
			var render_events=_events;	
			//render_events.sort(_sort_events);
			if( '1'==calendar.options.eventList.reverse ){
				render_events.sort(_rsort_events);
			}else{
				render_events.sort(_sort_events);
			}			

			//---
			$.each(render_events,function(i,ev){
				if( ev.end && ev.end < t.visStart ) return;
				if( !t.grid_options.showongoing && ev.start < t.visStart ) return;
				if( ev.start > t.visEnd ) return;	
				if( in_rendered_events( ev ) ) return;		

				triggerRes = trigger('eventRender', ev, ev, '');
				if(false===triggerRes){
				
				}else{	
					t.empty_polls = 0;
					
					t.rendered_events.push( ev );
							
					$(element).find('.rhg_grid_items').append( 
						add_event_data_to_template( ev, griditem.clone(), 'griditem' )
					);	
					if( t.grid_options.enableslideshow=='1' ){
						$(element).find('.rhg_slideshow_items').append( 
							add_event_data_to_template( ev, slide.clone(), 'slideshow' )
						);					
					}

				}				
			});
		
			init_grid();
			
			//TODO: find why hitting forward arrow and then backward arrow displays no item, eventhough they are there.
			setTimeout( function(){ bug_on_back_arrow_item_not_shown(); }, 200 );
		}else{
			if( t.empty_polls++ < t.grid_options.max_empty_polls ){
				more_events_scroll( null );
			}
		}
					
		trigger('loading', null, false);
		//raise an even so that other plugins can initialized anything added to the custom fields, like shortcodes that require initialization.
		$('BODY').trigger('rhc.gridview.rendered');
	}
	
	function in_rendered_events( ev ){
		for( var a=0; a < t.rendered_events.length ; a++ ){
			if( ev.id == t.rendered_events[a].id && ev.start.getTime()==t.rendered_events[a].start.getTime() ){
				return true;
			}
		}
		return false;
	}
	
	function bug_on_back_arrow_item_not_shown(){	
		if( $(element).find('.cbp-triggers-slide').length>0 && $(element).find('.cbp-triggers-slide.shown').length==0 && $(element).find('.cbp-triggers-slide.animate').length==0 ){
			$(element).find('.cbp-triggers-slide').each(function(i,el){
				if(i<3)	$(this).addClass('animate');
			});
		}
	}
	
	function add_event_data_to_template( ev, item, section ){
		if(section=='griditem'){
			var trigger_size = t.grid_options.trigger_size || 0;
			if( trigger_size > 0 ){
				var url = ev.url;
				if ( null!=url && ''!=url && -1 == url.indexOf("javascript:void(0);") ){
					item
						.attr('data-url', url )
						.attr('data-target', t.grid_options.link_target )
						.attr('data-trigger_size', trigger_size )
					;				
				}				
			}
		}

		item.find('.fc-title').html( ev.title );
		item.find('.fc-description').html( ev.description );
		
		//--grid image
		image = ev.image || ev.image_full || false;
		if(image && image.length==4){
			item
				.find('.griditem-img')
				.append(
					$('<img />')
						.attr('src', image[0])
						//.attr('width', image[1])
						//.attr('height', image[2])				
				)
			;				
		}
			
		//--slide image
		image = ev.image_full || ev.image || false;
		if(image && image.length==4){
			item
				.find('.slideshow-img')
				.append(
					$('<img />')
						.attr('src', image[0])
						//.attr('width', image[1])
						//.attr('height', image[2])				
				)
			;				
		}
	
	
		//--start
		if(ev.start){
			if(ev.allDay){
				_format = item.find('.fc-start').data('date_format_allday'); 
				_format = _format || t.grid_options.date_format_start_allday;			
			}else{
				_format = item.find('.fc-start').data('date_format'); 
				_format = _format || t.grid_options.date_format_start;						
			}

			item.find('.fc-start').html( $.fullCalendar.formatDate( ev.start, _format, calendar.options ) );
			
			
			if( !ev.local_feed ){
				box = $(get_box_template_for_external_source());
				box.appendTo(item.find('.gridviewbox'));
				box.find('.fc_start').html(
					$.fullCalendar.formatDate( ev.start, t.grid_options.date_format, calendar.options )
				);
				box.find('.fc_start_time').html(
					$.fullCalendar.formatDate( ev.start, t.grid_options.time_format, calendar.options )
				);
				
				sbox = box.clone();
				sbox.appendTo(item.find('.slideviewbox'));
			}			
		}else{
			item.find('.fc-start')
				.parent().addClass('grid-empty-field').end()
				.remove()
			;
		}

		//--end
		if(ev.end){
			if(ev.allDay){
				_format = item.find('.fc-end').data('date_format_allday'); 
				_format = _format || t.grid_options.date_format_end_allday;			
			}else{
				_format = item.find('.fc-end').data('date_format'); 
				_format = _format || t.grid_options.date_format_end;						
			}
			item.find('.fc-end').html( $.fullCalendar.formatDate(ev.end, _format, calendar.options) );
		}else{
			item.find('.fc-end')
				.parent().addClass('grid-empty-field').end()
				.remove()				
			;
		}		

		//--linking
		if( item.find('.fc-event-link').length > 0 ){			
			tooltip_target = t.grid_options.link_target || '_self' ;
			if( !ev.local_feed && ev.fc_click_target ){
				tooltip_target = ev.fc_click_target ;
			}
			
			tooltip_click = function(e){
				jQuery('form#calendarizeit_repeat_instance').remove();
				var form = '<form id="calendarizeit_repeat_instance" method="post"></form>';
				jQuery(form)
					.attr('target',tooltip_target)
					.attr('action',ev.url)
					.appendTo('BODY')	
				;
				if(ev.gotodate){
					jQuery('<input type="hidden" name="gotodate" value="' + ev.gotodate + '"/>')
						.appendTo('form#calendarizeit_repeat_instance')
					;
				}
				if(ev.event_rdate){
					jQuery('<input type="hidden" name="event_rdate" value="' + ev.event_rdate + '" />')
						.appendTo('form#calendarizeit_repeat_instance')
					;
				}
				jQuery('form#calendarizeit_repeat_instance')
					.submit(function(e){
						e.stopPropagation();
						return true;
					})
					.submit()
				;	
				return false;
			}	
			
			var sel = '.fc-event-link';
			if( t.grid_options.enableslideshow=='1' ){
				sel = '.fc-event-link:not(.noslide-link)';
			}else{
				item.addClass('fc-grid-slideshow-disabled');
			}			
				
			if(ev.gcal || ev.url=='' || 0==parseInt(t.grid_options.nolink) ){

			}else if(ev.direct_link){	
				if( '_nolink' != tooltip_target ){
					item.find(sel).wrapInner( '<a target="' + tooltip_target + '" href="' + ev.url + '"></a>' );
				}
			}else{
				if( '_nolink' != tooltip_target ){
					item.find(sel)
						.wrapInner(  
							$('<a target="' + tooltip_target + '" href="javascript:void(0);"></a>')	
								.bind('click', tooltip_click )							
						)
					;	
				}
			}		
		}
	
		//-- terms
		if( ev.terms && ev.terms.length>0){
			$.each(ev.terms,function(i,t){		
				if( t.name && ''!=t.name && item.find('.taxonomy-'+t.taxonomy).length>0 ){
					if( t.url=='' ){
						$('<span class="taxonomy-label">'+ t.name +'</span>')
							.appendTo( item.find('.taxonomy-'+t.taxonomy).show().parents('.taxonomy-holder').removeClass('empty-taxonomy').show().end() )
						;	
					}else{
						$('<a>'+ t.name +'</a>')
							.attr('href',t.url)
							.appendTo( item.find('.taxonomy-'+t.taxonomy).show().parents('.taxonomy-holder').removeClass('empty-taxonomy').show().end() )
						;								
					}

				}
				
				if( item.find('.taxonomy-'+t.taxonomy+'-gaddress').length>0 && t.gaddress && t.gaddress!=''){
					var _url = 'http://www.google.com/maps?f=q&hl=en&source=embed&q=' + escape(t.gaddress);
					$('<a>'+ t.gaddress +'</a>')
						.attr('href', _url)
						.attr('target','_blank')
						.appendTo( item.find('.taxonomy-'+t.taxonomy+'-gaddress' ).show().parents('.taxonomy-holder').removeClass('empty-taxonomy').show().end() )
					;	
				}
			});
		}		
		
		//color bar
		if( ev.color!='' && ev.color!='#' ){
			if('slideshow'==section){
				item.css('border-color', ev.color);
			}else{
				item.find('.grid-item figcaption').css('border-color', ev.color);
			}
		}
		
		if( ev.meta_data && ev.meta_data.length > 0 ){
			item.find('.meta-data').each(function(i,holder){
				$.each( ev.meta_data, function(i,m){
					if( 'slideshow' == section ){
						if( !m[5] ) return;
					}else{
						if( !m[4] ) return;
					}	
					
					if( m[0]=='url' ){
						tmp = '<a target="_self" href="' + m[3] + '" class="rhc-grid-meta-' + m[2] + ' fc-button fc-button-custom fc-state-default  fc-corner-left fc-corner-right"><span class="fc-button-inner"><span class="fc-button-content">' + m[1] + '</span></span></a>';
						$(tmp)
							.unbind('click')
							.bind('click', function(e){
								e.stopPropagation();
								return true;
							})
							.appendTo(holder)
						;
					}else{
						tmp = '<div class="rhc-grid-meta-' + m[2] + ' grid-meta-row"><label>' + m[1] + '<span>' + m[3] + '</span></label></div>';
						$(holder).append( tmp );
					}
				});			
			});
		}
		
		//---add gridviewbox 
		//console.log( ev.gridviewbox );
		if( ev.gridviewbox ){
			var gridviewbox = $( ev.gridviewbox );
			
			gridviewbox.find('.rhc_date').each(function(i,el){
				field = jQuery(el).data('fc_field');
				date_format = jQuery(el).data('fc_date_format')||'';	
				if( value = ev[field] ){
					jQuery(el).html(
						jQuery.fullCalendar.formatDate(value, date_format, t.calendar.options )
					);				
				}
			});

			gridviewbox.find('.rhc-info-cell').unbind('click').bind('click', function(e){
				e.stopPropagation();	
			});
			
			//bug fix empty values, hide row to avoid empty space
			gridviewbox
				.find('.fe-is-empty-1')
				.closest('.row-fluid')
				.hide()
			;
			
			item
				.find('.gridviewbox')
				.append( gridviewbox )
			;
			//---------------
			var slideviewbox = $( ev.slideviewbox );
			
			slideviewbox.find('.rhc_date').each(function(i,el){
				field = jQuery(el).data('fc_field');
				date_format = jQuery(el).data('fc_date_format')||'';	
				if( value = ev[field] ){
					jQuery(el).html(
						jQuery.fullCalendar.formatDate(value, date_format, t.calendar.options )
					);				
				}
			});

			slideviewbox.find('.rhc-info-cell').unbind('click').bind('click', function(e){
				e.stopPropagation();	
			});
			
			//bug fix empty values, hide row to avoid empty space
			slideviewbox
				.find('.fe-is-empty-1')
				.closest('.row-fluid')
				.hide()
			;
			
			item
				.find('.slideviewbox')
				.append( slideviewbox )
			;
		}
		
		return item;
	}
	
	function get_box_template_for_external_source(){
		var tpl = 	'<div class="rhc fe-extrainfo-container  fe-have-image-0">' +
					'    <div class="fe-extrainfo-container2 row-fluid">' +
					'        <div class="fe-extrainfo-holder fe-extrainfo-col1 span12">' +
					'            <div class="row-fluid">' +
					'                <div class="span12 fe-maincol fe-maincol-0" data-column_index="0">' +
					'                    <div class="row-fluid fe-sortable">' +
					'                        <div class="span12">' +
					'                            <div class="rhc-info-cell fe-cell-postmeta icon-postmeta-fc_start postmeta-fc_start fe-is-empty-0 fe-is-empty-label-0">' +
					'                                <span class="fe-extrainfo-value fc_start"></span>' +
					'                            </div>' +
					'                        </div>' +
					'                    </div>' +
					'                    <div class="row-fluid fe-sortable">' +
					'                        <div class="span12">' +
					'                            <div class="rhc-info-cell fe-cell-postmeta icon-postmeta-fc_start_time postmeta-fc_start_time fe-is-empty-0 fe-is-empty-label-0">' +
					'                                <span class="fe-extrainfo-value fc_start_time"></span>' +
					'                            </div>' +
					'                        </div>' +
					'                    </div>' +
					'                    <div class="row-fluid fe-sortable taxonomy-holder empty-taxonomy" style="display:none;">' +
					'                        <div class="span12">' +
					'                            <div class="rhc-info-cell fe-cell-taxonomy icon-taxonomy-venue">' +
					'                                <span class="fe-extrainfo-value taxonomy-venue"></span>' +
					'                        </div>' +
					'                    </div>' +
					'                </div>' +
					'            </div>' +
					'        </div>' +
					'    </div>' +
					'</div>	'
					;

		return tpl;	
	}
		
	function trigger(name, thisObj) {
		return calendar.trigger.apply(
			calendar,
			[name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
		);
	}
	
	function loading( isLoading, view, fc_options ){
		if(isLoading){
			t.scroll_lockdown = true;
			$(view.element).parents('.rhc_holder').addClass('stacking-loading');

			t.gridgallery.loading(true);
			t.gridgallery.scroll_lockdown = true;
		}else{
			t.scroll_lockdown = false;
			$(view.element).parents('.rhc_holder').removeClass('stacking-loading');
			
			t.gridgallery.loading(false);
			t.gridgallery.scroll_lockdown = false;				
		}
	}
	
	function init_grid(){		
		setTimeout( function(){
			t.gridgallery.init_grid( t.gridgallery_holder );
		}, 25 );
	}
	
	function _sort_events(o,p){
		if(o.start>p.start){
			return 1;
		}else if(o.start<p.start){
			return -1;
		}else{
			return 0;
		}
	}
	function _rsort_events(o,p){
		if(o.start<p.start){
			return 1;
		}else if(o.start>p.start){
			return -1;
		}else{
			return 0;
		}
	}
}	

})(jQuery);