/**
 * Monumenten.nl
 * @author    LBi Lost Boys
 */

var MONUMENTEN = (function($) {

    var MONUMENTEN = {
		
        init: function() {
	
			$('.box-link, .list-actual li').not('.box-horizontal:not(.box-no-space), .carousel-home .box').each(function(index) {
				var moreIcon = $(this).find('.icon');
				$(this).find('p:last').append(moreIcon);
			});
	
			this.initTabs();
			this.initEqualized();
			this.collapsibles = new Collapsibles();
			this.collapsibles.register(/address/, { target: 'tr' });	
			this.collapsibles.register(/signpost/, { target: 'li' });	
			this.initSplittedLists();
			this.initCarouselItemList();
			this.initDialogs();
			this.initColumns();
			this.initAddThis();
			
			$('a:not(:has(img))').filter(function() {
				return this.hostname && this.hostname !== location.hostname;
			}).addClass('external').attr('target', '_blank').append('<span class="icon"><i></i></span>');
			
			$('input[title!=""]').hint();
			
			$(".box-link a").bigTarget({
				hoverClass: 'box-hover',
				clickZone : 'div.box'
			});
			$(".map .zoom, .box-map h3 a").bigTarget({
				hoverClass: 'box-map-hover',
				clickZone : 'div.box'
			});
			$(".box-special h3 a").bigTarget({
				hoverClass: 'box-special-hover',
				clickZone : 'div.box'
			});
			$(".list-actual .icon").bigTarget({
				hoverClass: 'list-actual-hover',
				clickZone : 'li'
			});
			
			// Zebra striped
			$("table.table-zebra tr:nth-child(even), .list-toggle > li:nth-child(even)").addClass("even");
			$(".list-zebra > li:nth-child(even)").addClass("even");
			$("table.table-zebra-alt tr:nth-child(odd)").addClass("even");
			
			$('.carousel').not('.carousel-twitter').carousel({
				delay: 4,
				scroll: 1,
				nextButton: '<a href="#" class="icon next"><span>Volgende</span></a>',
				prevButton: '<a href="#" class="icon prev"><i>Vorige</i></a>'
			});
			
			var container = $('div.notification-error');
			$("#newsletter").validate({
				errorLabelContainer: $("#newsletter div.notification-error")
			});
			$("#form-login, #signup").validate();
				
			$( 'body' ).removeClass( "no-js" );
        },

		initTwitterCarousel: function() {
			
			$('.carousel-twitter').carousel({
				delay: 0,
				scroll: 1,
				nextButton: '<a href="#" class="icon next"><span>Volgende</span></a>',
				prevButton: '<a href="#" class="icon prev"><i>Vorige</i></a>'
			});
			
			
		},

		initTabs: function() {
			
			var navTabs = new LBi.Tabs({
				activeClass: 'active',
				selector: '.nav-tabs',
				relation: 'tab'
			});

			var tabsSection = new LBi.Tabs({
				activeClass: 'active',
				selector: '.tabs-section',
				relation: 'tab'
			});

			var toggle = new LBi.Tabs({
				activeClass: 'active',
				selector: '.list-toggle',
				relation: 'toggle',
				toggleEnabled: true
			});

			var glossary = new LBi.Tabs({
				activeClass: 'active',
				selector: '.list-glossary',
				relation: 'letter'
			});			
		},

		initEqualized: function() {
			var equal = new LBi.EqualizedNodes({
				selector: '.equalized',
				children: '.equal'
			});
		},

		initCarouselItemList: function() {

			var count    = $('.carousel li').size();
			var template = $('#carousel-item-template').children().first();

			$('.carousel .carousel-items').each( function(index) {
				var active = index + 1;
				var item;
				for ( var i = 1; i <= count; ++i ) {
					item = template.clone().attr('rel', i);
					if ( i == active ) {
						item.addClass('carousel-item-active');
					}
					item.appendTo(this);
				}
			});
		},
		
		initSplittedLists: function() {
			
			var split = new LBi.SplittedNodes({
				selector: '.splitted',
				pattern: /split-([0-9]+)/i
			});
			
		},
		
		initDialogs: function() {
		
			this.dialogs = new LBi.Dialogs( 
			{
                dialogClass: MONUMENTEN.BaseDialog,
                overlayTemplate: '<div class="dialog-darkener"></div>'
            } );
            
            this.dialogs.register('slideshow', MONUMENTEN.SlideshowDialog );
            this.dialogs.register('map', MONUMENTEN.MapDialog );
            this.dialogs.register('bedrijven', MONUMENTEN.MapDialog );
            this.dialogs.register('video', MONUMENTEN.VideoDialog );
		},
		
		initColumns: function()
		{
			$( '.article-col-2' ).columnize( {
				columns: 2,
				gap: 50
			} );
		
			$( '.article-col-3' ).columnize( {
				columns: 3,
				gap: 50
			} );
		},
		
		initAddThis: function ()
		{
			$( document ).ready( function() 
			{
				$( 'body' ).append( '<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e1d8e01163b5370"></script>' );
			} );
		}
    };

    $(function() {
		
        MONUMENTEN.init();

    });

	/**
	 * Collapsibles 
	 * 
	 */
	function Collapsibles() {
		this.relations = new LBi.LinkRelations();
	}

	Collapsibles.prototype = {
		register:function(reg, prefs) {
			var options = $.extend({}, Collapsibles.Defaults, prefs);
			var single = /single/i.test(options.mode);

			var handler = function(e) {
				var cls = options.className;
				var type = options.target;
				var target = $(e.target).closest(type);

				if(single) {
					target.siblings(type).removeClass(cls);
				}

				target.toggleClass(cls);

				if(options.preventDefault) {
					e.preventDefault();
				}

			};

			this.relations.subscribe(reg, handler);
		}
	};

	Collapsibles.Defaults = {
		target: 'div',
		mode: 'single',
		className: 'active',
		preventDefault: true
	};
	
	/* Slideshow Dialog */
	MONUMENTEN.BaseDialog = LBi.Class.extend(
		LBi.Dialog,
		function( type, settings )
		{
		
		}, {
			// enhanced version of the LBi.CenteredDialog's routine
			getPosition: function() {
			
				// first explicitly set the size.
				this.setSize();
			
				return MONUMENTEN.BaseDialog.getCenteredPosition( this.node );
			},
			
			setSize: function() {
			
				this.setVerticals();
				
				var win = $( window );
				var winHeight = win.height();
				var nodeHeight = this.$node.height();
				
				var calculatedHeight = Math.min( nodeHeight + this.getPadding( this.node ), winHeight - 40 );
				
				this.$node.height( calculatedHeight - this.getPadding( this.node ) );
				this.$node.find( '.body' ).css( { position: 'absolute' } );
			},
			
			setVerticals: function() {
				var props = 'padding-top,padding-bottom,border-top-width,border-bottom-width';
				if(document.body.currentStyle) {
					props = props.replace(/-([a-z])/mig, function(ignored, match) {
						return match.toUpperCase();
					});
				}
	
				this.verticals = props.split(',');
			},
			
			/**
			 * Returns the combined vertical padding. The interfaces presumably return px values, but 
			 * it doesn't hurt to explicitly define them as such.
			 * @private
			 */
			getPadding: function(node) {
				var style = node.currentStyle;
				var space = 0;
				var i, l = this.verticals.length;
	
				if(style) {
					for(i=0; i<l; i++) {
						space += parseInt(style[this.verticals[i]] || 0, 10);
					}
				} else if(window.getComputedStyle){
					style = window.getComputedStyle(node, null);
					for(i=0; i<l; i++) {
						space += parseInt(style.getPropertyValue(this.verticals[i]) || 0, 10);
					}
				}
	
				return !isNaN(space)? space : 0;
			}
		} );
		
	MONUMENTEN.BaseDialog.getCenteredPosition = function( node )
	{
		var win = $(window);
		var doc = $(document);
		var dialog = LBi.Dialogs.parseNode( node );
		return {
			left: doc.scrollLeft() + ( win.width() - dialog.width ) / 2,
			top: doc.scrollTop() + Math.max( ( win.height() - dialog.height ) / 2, 20 )
		};
	}

    MONUMENTEN.SlideshowDialog = LBi.Class.extend(
		LBi.Dialog,
		function ( type, settings ) 
		{
			
		}, {
			// enhanced version of the LBi.CenteredDialog's routine
			getPosition: function() {
				
				return MONUMENTEN.BaseDialog.getCenteredPosition( this.node );
			},
			
			activate: function(toggle) 
			{		
				if ( toggle )
				{
					// pause parent slideshow
					var parentNodeId = $( this.origin ).closest( '.slideshow_wrapper' ).attr( 'id' );
					this.parentSlideshow = LBi.slideshows.getSlideshow( parentNodeId );
					this.parentSlideshow.pause();
					
					// find the container for the slideshow to work with
					this.$slideshowWrapper = this.$node.find( '.slideshow_wrapper' )
				
					// determine max height
					var maxTotalHeight = $(window).height() - 140;
					
					this.$slideshowWrapper.attr( 'data-max-total-height', maxTotalHeight );
					this.$slideshowWrapper.bind( 'sizing_complete', this.sizingCompleteHandler.bind( this ) );
					
					this.slideshow = new LBi.Slideshow( this.$slideshowWrapper[ 0 ], {
						parentSlideshow: parentNodeId,
						showSlideInfo: true,
						fit: "outer"
					} );
					
					$( 'body, html' ).addClass( "noscroll" );
				}
				else
				{
					this.$slideshowWrapper.unbind( 'sizing_complete' );
					this.slideshow.destroy();
					this.parentSlideshow.resume();
					
					$( 'body, html' ).removeClass( "noscroll" );			
				}
			},
			
			sizingCompleteHandler: function ( e, height )
			{
				this.$node.find( '.body' ).height( height );
				this.redraw();
			}
		} );

	/* Map Dialog */
    MONUMENTEN.MapDialog = LBi.Class.extend(
		LBi.Dialog,
		function ( type, settings ) 
		{
			settings.modal = true;
		}, {
			// enhanced version of the LBi.CenteredDialog's routine
			getPosition: function() {
				return MONUMENTEN.BaseDialog.getCenteredPosition( this.node );
			},
		
			activate: function(toggle) {
				if ( toggle ) {
					this.setSize();
				
					if (!MONUMENTEN.MapDialog.map) {
						var type = 'monumenten',
							location = document.location.hash,
							typeAttr = $(this.origin).attr('data-type'),
							locationAttr = $(this.origin).attr('data-location');

						if (typeAttr === 'bedrijven') {
							type = 'bedrijven';
						}
						if (locationAttr) {
							location = escape(locationAttr);
						}
						MONUMENTEN.MapDialog.map = new MapApp($, type );
						MONUMENTEN.MapDialog.map.start(location);
					}
					$( 'body, html' ).addClass( "noscroll" );
				} else {
					$( 'body, html' ).removeClass( "noscroll" );			
				}
			},
			
			setSize: function() {
				var win = $(window);
								
				this.$node.height( win.height() - 40 );
				this.$node.find( '.body' ).css( { position: 'absolute' } );
			}
		} );
		
	MONUMENTEN.MapDialog.map = undefined;
	
	
	MONUMENTEN.VideoDialog = LBi.Class.extend(
		LBi.CenteredDialog,
		function( type, settings )
		{
		
		}, {
			
			activate: function( toggle )
			{
				if ( toggle )
				{					
					this.player = jwplayer( "videoContainer" );
					
					if ( this.player )
					{
						this.player.setup(
						{
							flashplayer: "/sites/all/themes/monumenten/js/libs/jwplayer/player.swf",
							file: $( this.origin ).attr( 'data-video' ),
							image: $( this.origin ).attr( 'data-image' ),
							plugins: {
								"captions-2": {
									file: $( this.origin ).attr( 'data-subtitles' )
								}
							},
							width: 594,
							height: 334
						});
					}
				}
				else
				{
					if ( this.player )
					{
						this.player.remove();
					}
					$( '#videoContainer' ).empty();
				}
			}
		} );


    return MONUMENTEN;

})(jQuery);


