/* Global Variables */
var eventManager;
var imgid = 0;
Array.prototype.randomize = function (){
    this.sort(
        function(a,b) {
            return  Math.round( Math.random() );
        }
    );
};

function sortByCMSOrder(a,b){
	return a.order-b.order;
};

/* Runtime Initialization */
$(function(){

	var gm = null;
	
	eventManager = new EventManager();
		
	var $thumbnails = $('.section-item');
	if( $thumbnails.length > 0 )
		var tr = new ThumbRollover( $thumbnails );
	
	var $rotatingGallery = $('.rotational');
	if ( $rotatingGallery.length > 0 ) {
		var rg = new RotatingGallery( $rotatingGallery, 4500 );
		rg.loadThumbs('sites/bdf3/bdf3_cust_home_gallery.php?p=bdf3');
	};
	
	if( refid != null ) {
		
		var thePath = SWFAddress.getPathNames();
		var initIndex = -1;
		var gm = new GalleryModel( 'bdf3', null );
		var gv = new GalleryView( gm );
		var gc = new GalleryController( gm );
		
		gm.get( refid );

	};
	
	var galleryNavOver = function ( e ) {	
		$(this).attr( 'src', $(this).attr('src').replace(/.jpg/, '_active.jpg') );
	};
		
	var galleryNavOut = function ( e ) {
		$(this).attr( 'src', $(this).attr('src').replace(/_active.jpg/, '.jpg') );
	};
		
	$('.gallery-navigation').find('img').bind({
		mouseover: galleryNavOver,
		mouseleave: galleryNavOut
	});
	
	var nerdhause = new Nerdhaus( gm ? gm : null );
	

});

var RotatingGallery = function ( $container, interval ) {

	var gallery = this;
	var loadLen = 0;
	var $childSpots = $container.children('.featured-item');
	var currentPosition = -1;
	var currentSource = $childSpots.length-1;
	var loadlen = 0;
	
	this.sources = [];
	this.positions = $childSpots;
	this.interval = interval;
	this.timer = null;
	this.thumbdata = null;
	this.paused = false;
	
	this.loadThumbs = function ( json ) {
		$.getJSON( json, parseData );
	}
	
	this.startTimer = function () {
		gallery.timer = setInterval( changeState, gallery.interval );
	}
	
	this.stopTimer = function () {
		clearTimeout( gallery.timer );
	}
	
	var parseData = function ( data ) {
		var i;
		for( i in data ) {
			gallery.sources.push( data[i] );
		}
		
		gallery.sources.sort(sortByCMSOrder);
		
		
		if( gallery.sources.length > 3 ) {
			var c;
			for( c = 0; c < gallery.sources.length; c++ ) {
				var img = new Image();
				img.src = gallery.sources[c].img;
				gallery.sources[c].pic = img;
				
				$(img).load( loadup );
				$childSpots.unbind({
					mouseenter: gallery.stopTimer,
					mouseleave: gallery.startTimer
				});
			}
		} else {
			gallery.stopTimer();
			$childSpots.unbind({
				mouseenter: gallery.stopTimer,
				mouseleave: gallery.startTimer
			});
		}
	}
	
	var changeState = function () {
		currentPosition++;
		currentSource++;
		gallery.controlIndices();
		gallery.updateData();
	}
	
	this.controlIndices = function () {
		if( currentPosition >= gallery.positions.length ) {
			currentPosition = 0;
		}
		
		if( currentSource >= gallery.sources.length ) {
			currentSource = 0;
		}

	}
	
	this.updateData = function () {
		var pos = $(gallery.positions[ currentPosition ]);
		var src = gallery.sources [ currentSource ];
		
		if( src.pic && src.title && src.desc ) {
			pos.animate({
				opacity: 0
			}, 500, function(){
				pos.children('.featured-item-image').attr('src', src.pic.src);
				pos.children('img').addClass('featured-item-image');
				pos.children('.featured-item-title').html( src.title ).attr('href', '?p=bdf3&id='+src.id+'&gallery='+src.gallery);
				pos.children('.featured-item-description').html( src.desc );
				
				pos.animate({opacity: 1});
			});
		}
	}
	
	var loadup = function () {
		loadlen++;
		if( loadlen == gallery.sources.length ) gallery.startTimer();
	}
	
};

var ThumbRollover = function ( $t ) {
	var thumbs = $t;
	var descriptions = $t.find('.section-item-description');
		
	var dropdown = function ( e ) {
		e.stopPropagation();
		var $thumb = $(this);
		var $otherthumbs = $thumb.siblings('.section-item');
		var $description = $thumb.find('.section-item-description');
		var $otherdescriptions = $otherthumbs.find('.section-item-description');
		
		$description.stop().animate({
			height: 150
		}, 450);
		
		$otherdescriptions.trigger('mouseleave');
	};
	
	var rollup = function ( e ) {
		e.stopPropagation();
		var $thumb = $( e.target );
		var $description = $thumb.parent('.section-item').find('.section-item-description');
		$description.stop().animate({
			height: 0
		}, 450);
	};
	
	var rollthisup = function ( e ) {
		e.stopPropagation();
		var $description = $( e.target ).filter('.section-item-description');
		$description.stop().animate({
			height: 0
		}, 450);
	};
	
	var rollallup = function ( e ) {
		$('.section-item-description').animate({
			height: 0
		});
	};
	
	var killinfo = function ( e ) {
		$('.section-item-description').css({
			height: 0
		});
	};
	
	thumbs.bind({
		mouseover: dropdown,
		mouseleave: rollup
	});
	
	thumbs.find('a').bind({
		click: killinfo
	});
	
	descriptions.bind({
		mouseleave: rollthisup
	});
	
	$('.body').bind({
		mouseover: rollallup
	});
};

/* Model View Controller: MODEL */

var GalleryModel = function( page, initIndex ) {
	var model = this;
	this.ref;
	var base = 'sites/'+page+'/';
	var prefix = '';
	this.page = page;
	this.phpmodule = prefix + base + page + '_cust_json.php';
	this.galleries = new Array();
	this.imageSet = new Array();
	this.currentIndex = 0;
	this.currentImage = 0;
	this.totalImages = 0;
	this.nextGallerys = new Array();
	this.isclient = false;
	this.data = null;
	
	this.JSON_PARSED = "jsonParsed";
	this.UPDATE_GALLERY = "updateGallery";
	
	this.get = function ( refid ) {
		model.ref = refid;
		var rid = Math.floor( Math.random() * 1000000 );
		var requestString = '?p=' + model.page + '&refid=' + model.ref + '&rid=' + rid;		
		$.ajax({
			type: 'GET',
			dataType: 'json',
			url: model.phpmodule + requestString,
			dataFilter: jsonFilter,
			timeout: 10000,
			error: onError,
			success: parseJSON
		});
		
	};
	
	var jsonFilter = function( data, type ) {
		if( type == 'json' ) {
			return data;
		} else {
			$.parseJSON( data );
			return data;
		};
	};
	
	var onError = function ( xhr, status, error ) {
		var error = 'There is a ' + status + ': ' + error;
		//alert(error);
	};

	var parseJSON = function( data ) {
		model.data = data;
		var g;
		var c = 0;
		var indexSet = false;
				
		for( g in data ) {
			if(g != 'type') {
				data[g].ref = g;
				model.galleries.push( data[g] );
			};
			
			
			/*
			if( initIndex > 0 && g == initIndex ) {
				model.currentIndex = c;
				indexSet = true;
			};
			*/
		};
		
		
		
		model.isclient = (data.type=='client') ? true : false;
		
		c = 0;
		for( g in data ) {
			if( g != 'type' ) {
	

					if( g == gal ) {
						model.currentIndex = c;
					}
					
				data[g].index = c;
				model.galleries[c].thumbnail = prefix + model.galleries[c].thumb;
				c++;
				
			};
		};
				
		updateData();
		eventManager.dispatchEvent( model.JSON_PARSED );
		
	};
	
	var countImages = function ( gallery ) {
		var count = 0;
		var i;
		for( i in gallery ) {
			count++;
		};
		return count;
	};
	
	this.setCurrentIndex = function ( currentIndex, jump ) {
		currentIndex = parseInt( currentIndex );
		if( !jump )
			model.currentImage = 0;
		
		model.currentIndex = currentIndex;
		controlCurrentIndex();
		
		if( jump )
			switch( jump ) {
				case 'up':
					model.currentImage = 0;
					break;
				case 'down':
					model.currentImage =  countImages( model.galleries[model.currentIndex].images ) - 1;
					break;
			}
		
		updateData();
	};
	
	this.setCurrentImage = function ( currentImage ) {
		currentImage = parseInt( currentImage );
		model.currentImage = currentImage;
		controlCurrentImage();
		updateData();
	};
	
	var controlCurrentIndex = function () {
		var maxGalleries = model.galleries.length;
				
		if( model.currentIndex >= maxGalleries ) {
			model.currentIndex = 0;
		} else if( model.currentIndex < 0 ) {
			model.currentIndex = maxGalleries - 1;
		};
	};
	
	var controlCurrentImage = function () {
		var currentImage = model.currentImage;
		var maxImages = model.imageSet.length;
		
		if( currentImage >= maxImages ) {
			model.setCurrentIndex( model.currentIndex + 1, 'up' );
		} else if( currentImage < 0 ) {
			model.setCurrentIndex( model.currentIndex - 1, 'down' );
		};
	};
	
	var updateData = function () {
		model.imageSet = new Array()
		var currentGallery = model.galleries[model.currentIndex].images;
		var i;
		c = 0;
		for( i in currentGallery ) {
			if( imgid && i == imgid )
				model.currentImage = c;
			
			var currentImage = currentGallery[i];
			currentImage.img = new Image();
			currentImage.img.src = prefix + currentImage.url;
			
			model.imageSet.push( currentImage );			
			c++;
		};
		
		model.imageSet.sort(sortByCMSOrder);
		model.totalImages = countImages( model.galleries[model.currentIndex].images );
		
		model.nextGalleries = new Array();
		
		var total = model.galleries.length;
		var g;
		for( g = 0; g < 3; g++ ) {
			var nextgal = model.currentIndex + g + 1;
			if(nextgal >= total)
				nextgal = -( total-nextgal );
			model.nextGalleries[g] = model.galleries[nextgal];
		};
		
		eventManager.dispatchEvent(model.UPDATE_GALLERY);
		
	};
	
};

/* Model View Controller: VIEW */

var GalleryView = function( model ) {

	var blankCarousel;
	var carousel;
	var dot;
	var vimeo = new VimeoView();
	var activeDot = new Image();
	var inactiveDot = new Image();
	activeDot.src = 'sites/bdf3/images_sys/bdf_gallery_dot_active.jpg';
	inactiveDot.src = 'sites/bdf3/images_sys/bdf_gallery_dot.jpg';

	var init = function () {
		eventManager.addListener( new Event( model.JSON_PARSED, establishGallery ) );
		eventManager.addListener( new Event( model.UPDATE_GALLERY, updateGallery ) );
		blankCarousel = $('.dot-carousel').clone();
		carousel = blankCarousel.clone();
		dot = carousel.find('.dot-carousel-item').eq(0).removeClass('hidden').clone();
		carousel.children().remove();
	};
	
	var establishGallery = function () {
		updateGallery();
	};
	
	var hideimgnav = function () {
		$('.gallery-navigation-prev-image').addClass('hidden');
		$('.gallery-navigation-next-image').addClass('hidden');
	};
	
	var showimgnav = function () {
		$('.gallery-navigation-prev-image').removeClass('hidden');
		$('.gallery-navigation-next-image').removeClass('hidden');
	};
	
	var hidegalnav = function () {
		$('.gallery-navigation-prev-gallery').addClass('hidden');
		$('.gallery-navigation-next-gallery').addClass('hidden');
	};
	
	var showgalnav = function () {
		$('.gallery-navigation-prev-gallery').removeClass('hidden');
		$('.gallery-navigation-next-gallery').removeClass('hidden');
	};
	
	var updateGallery = function () {
		if( $('#moogaloop').filter('object').length>0 ) $('#moogaloop').replaceWith( vimeo.placeholder ).addClass('bdf-video-player');
		var currentGalleryTitle = $('.single-page-header').find('.site-title');
		var currentImageTitle = $('.single-page-description');
		var currentImageImg = $('#moogaloop').find('img');
		var upcomingGalleries = $('.single-page-featured-item').next('.section-items').find('.section-item');
		var currentGalleryText = $('.single-page-featured-item-description').find('.single-page-featured-item-caption');
		var currentGalleryClient = $('.single-page-featured-item-description').find('.single-page-featured-item-client');
		var imgcount = model.totalImages;
		var g;
		
		var anotherCarousel = carousel.clone();
		
		if( imgcount == 1 ) {
			hideimgnav();
		} else if( imgcount > 1 ) {
			showimgnav();
		};
		
		if( model.galleries.length == 1 ) {
			hidegalnav();
		} else {
			showgalnav();
		};
		
		if( imgcount > 1 ) {
			for( g = 0; g < imgcount; g++ ){
				var anotherDot = dot.clone();
				if( g == model.currentImage ) {
					anotherDot.find('img').eq(0).replaceWith( $(activeDot).clone() );
				} else {
					anotherDot.find('img').eq(0).replaceWith( $(inactiveDot).clone() );
				}
				anotherCarousel.append( anotherDot );
			};
		};
		
		$('.dot-carousel').replaceWith( anotherCarousel );
		
		
		var currentGallery = model.galleries[ model.currentIndex ];
		
		currentGalleryTitle.html( currentGallery.name );
		currentGalleryText.html( currentGallery.text );
		var currentImage = model.imageSet[ model.currentImage ];
		currentImageTitle.html( currentImage.name || '&nbsp;' );
		currentImageImg.replaceWith( $(currentImage.img).clone().addClass('main-gallery-item') );
			
		if( model.data.type == 'client' ) {
			currentGalleryClient.addClass('hidden');
		} else {
			currentGalleryClient.removeClass('hidden');
		};
		if(currentGalleryClient.length>0 && currentGallery.clienthide == false) currentGalleryClient.html('Client: <a href="index.php?p=bdf3&id='+currentGallery.clientid+'">' + currentGallery.client + '</a>');
		var isvimeo = ( !isNaN( currentImage.vimeo ) && currentImage.vimeo > 0 );
		if( isvimeo ) {
			vimeo.embed( currentImage.vimeo );
		};
		 
		var n;

		for( n = 0; n < model.nextGalleries.length; n++ ) {
			var currentItem = upcomingGalleries.eq(n);

			var currentTitle = currentItem.find('.section-item-title');
			var currentThumb = currentItem.find('.section-item-thumbnail');
			var currentLink = currentItem.find('a');
			var currentCaption = currentItem.find('.section-item-description').children('p');
			if( model.nextGalleries[n] ) {
				currentTitle.html( model.nextGalleries[n].name );
				currentThumb.css({
					background: 'url("'+model.nextGalleries[n].thumbnail+'") top center no-repeat'
				});
				
				//var trg = model.isclient ? parseInt( model.nextGalleries[n].order ) - 1 : model.nextGalleries[n].index;
				var trg = model.nextGalleries[n].index;
				
				currentLink.attr('href', trg );
				currentCaption.text( model.nextGalleries[n].teaser );
			};
		};
		
	
		$('.section-items').css('opacity', 1);
	
	};
	
	init();
};

var VimeoView = function () {
	var vimeo = this;
	
	var flashvars = {
		clip_id: -1,
		show_portrait: 0,
		show_byline: 0,
		show_title: 0,
		js_api: 0,
		js_swf_id: 'moogaloop'
	};
	
	var params = {
		allowscriptaccess: 'always',
		allowfullscreen: 'true'
	};
	
	var attributes = {};
	
	var $placeholder = $('<div/>', {
		id: 'moogaloop',
		html: '<img />'
	});
	
	this.placeholder = function () {
		return $placeholder.clone();
	};
	
	this.embed = function ( video_id ) {
		flashvars.clip_id = video_id;
		swfobject.embedSWF("http://vimeo.com/moogaloop.swf", 'moogaloop', "605", "341", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	};
	
};

/* Model View Controller: Controller */

var GalleryController = function ( model ) {
	var controller = this;
	
	var init = function () {
		eventManager.addListener(new Event( model.JSON_PARSED, bindController ) );
		eventManager.addListener(new Event( model.UPDATE_GALLERY, rebindDynamics ) );
	};
	
	var showcaption = function ( e ) {
		$('.gallery-navigation-caption').html( $(this).find('img').attr('alt') );
	};
	
	var hidecaption = function ( e ) {
		$('.gallery-navigation-caption').html( '&nbsp;' );
	};
	
	var bindController = function () {
		
		$('.gallery-navigation-next-image').bind({
			click: function ( e ) {
				e.preventDefault();
				model.setCurrentImage( model.currentImage + 1 );
				return false;
			},
			mouseenter: showcaption,
			mouseleave: hidecaption
		});
		$('.gallery-navigation-prev-image').bind({
			click: function ( e ) {
				e.preventDefault();
				model.setCurrentImage( model.currentImage - 1 );
				return false;
			},
			mouseenter: showcaption,
			mouseleave: hidecaption
		});
		$('.gallery-navigation-next-gallery').bind({
			click: function ( e ) {
				e.preventDefault();
				model.setCurrentIndex( model.currentIndex + 1 );
				return false;
			},
			mouseenter: showcaption,
			mouseleave: hidecaption
		});
		$('.gallery-navigation-prev-gallery').bind({
			click: function ( e ) {
				e.preventDefault();
				model.setCurrentIndex( model.currentIndex - 1 );
				return false;
			},
			mouseenter: showcaption,
			mouseleave: hidecaption
		});
		
		$('.gallery-navigation-close-gallery').bind({
			mouseenter: showcaption,
			mouseleave: hidecaption
		});
		
		rebindDynamics();
		
	};
	
	var rebindDynamics = function () {

		$('.single-page-featured-item').find('img').css('cursor', 'pointer').bind({
			click: function ( e ) {
				model.setCurrentImage( model.currentImage + 1 );
			}
		});
		
		$('.section-item-description a').unbind().bind({
			click: function ( e ) {
				e.preventDefault();
				var index = $(this).attr('href');
				model.setCurrentIndex( index );

				$('.section-item-description').css({
					height: 0
				});
				$(window).scrollTop( $('.single-page-header').parent('.section-items').offset().top );
			}
		});
		
		$('.dot-carousel-item').bind({
			click: function ( e ) {
				e.preventDefault();
				target = $(this).index();
				model.setCurrentImage( target );
				
			}
		});
	};
	
	init();
	
};

/* Event Manager */
var Event = function ( e, cb, data ) {

	if( !e || !cb )
		return "Improper event request";
	
	this.e = e;
	this.cb = cb;
	this.data = data || null;
};

var EventManager = function () {
	var events = new Array();
		
	this.addListener = function ( evt ) {
		var len = events.length;
		var eventExists = false;
		if( len > 0 ) {
			var i;
			for( i = 0; i < len; i++ ) {
				if( events[i].e == evt.e && events[i].cb == evt.cb )
					eventExists = true;
			};
			if( !eventExists ) events.push(evt);
		} else {
			events.push( evt );
		}
	};
	
	this.removeListener = function ( evt ) {
		var len = events.length;
		var i;
		for( i = 0; i < len; i++ ) {
			if( events[i].e == evt.e && events[i].cb == evt.cb ) events.splice(i,1);
		};
	};
	
	this.dispatchEvent = function ( evt, data ) {
		var len = events.length;
		var i;
		for( i = 0; i < len; i++ ) {
			if( events[i].e == evt) {
				events[i].cb( data );
			}
		};
	};
	
	this.eventList = function () {
		return events;
	};
};

var Nerdhaus = function ( ja ) {
	var NERDHAUS = false;
	var MAX_HEIGHT = $(window).height();

	var nh = $('<div/>', {
		id: 'nerdhaus',
		css: {
			width: $(window).width(),
			height: 0,
			position: 'fixed',
			top: 0,
			left: 0,
			overflow: 'hidden',
			zIndex: 100
		}
	}).append( $('.nerdhaus').css('display', 'block') ).prependTo('body');
	
	var cheech = $('<div/>', {
		id: 'cheech',
		css: {
			background: '#000000',
			opacity: .95,
			width: $(window).width(),
			height: $(window).height(),
			position: 'absolute',
			top: 0,
			left: 0
		}
	}).appendTo(nh);
	
	
	$(window).bind({
		resize: function ( e ) {
			cheech.css({
				width: $(window).width(),
				height: $(window).height()
			});
		}
	});
	var nerdhaus = this;
	var model = ja;
	
	this.loadService = function ( index ) {
		var $section = $('.site-sections').children('li').eq(index).children('a');
		window.location.href = $section.attr('href');
	};
	
	this.goHome = function () {
		var home = $('.header-gear').parent('a').attr('href');
		window.location.href = home;
	};
	
	this.prevImage = function () {
		model.setCurrentImage( model.currentImage - 1);
	};
	
	this.nextImage = function () {
		model.setCurrentImage( model.currentImage + 1);
	};
	
	this.prevGallery = function () {
		model.setCurrentIndex( model.currentIndex - 1);
	};
	
	this.nextGallery = function () {
		model.setCurrentIndex( model.currentIndex + 1);
	};
	
	this.welcomeToTheNerdhaus = function ( e ){
		if( e ) e.preventDefault();
		
		NERDHAUS = true;
		
		nh.stop().animate({
			height: MAX_HEIGHT
		});
		
		cheech.bind({
			click: nerdhaus.laterJa
		});
		
	};
	
	this.laterJa = function () {
	
		if( NERDHAUS == true ) {
		
			nh.stop().animate({
				height: 0
			});
			
			cheech.unbind({
				click: nerdhaus.laterJa
			});
			
			NERDHAUS = false;
		};
		
	};
	
	$('.nerdhaus-link').bind({
		click: nerdhaus.welcomeToTheNerdhaus
	});
	
	$(window).bind({
		keydown: function(e){
			switch(e.keyCode){
				case 109:
				case 37:
					e.preventDefault();
					nerdhaus.prevImage()
					break;
				case 107:
				case 39:
					e.preventDefault();
					nerdhaus.nextImage();
					break;
				case 219:
				case 40:
					e.preventDefault();
					nerdhaus.prevGallery();
					break;
				case 221:
				case 38:
					e.preventDefault();
					nerdhaus.nextGallery();
					break;
				case 191:
					e.preventDefault();
					nerdhaus.welcomeToTheNerdhaus();
					break;
				case 27:
					nerdhaus.laterJa();
					break;
				case 48:
				case 96:
					nerdhaus.goHome();
					break;
				case 49:
				case 97:
					nerdhaus.loadService( 0 );
					break;
				case 50:
				case 98:
					nerdhaus.loadService( 1 );
					break;
				case 51:
				case 99:
					nerdhaus.loadService( 2 );
					break;
				case 52:
				case 100:
					nerdhaus.loadService( 3 );
					break;
				case 53:
				case 101:
					nerdhaus.loadService( 4 );
					break;
				case 54:
				case 102:
					nerdhaus.loadService( 5 );
					break;
			};
		},
		resize: function ( e ) {
			MAX_HEIGHT = $(window).height();
			if( NERDHAUS == true ) {
				nh.css({
					height: MAX_HEIGHT,
					width: $(window).width()
				});
			};
			
			$('.nerdhaus').css({
				marginTop: $(window).height()/2 - $('.nerdhaus').height()/2
			});
			
		}
	}).trigger('resize');
};
