(function(){
	var app = window.app ={
		sizeDB:[],
		cache:{},
		oldhash:false,
			init: function(root,rooturl,home){
				if(root)this.root = root;
				if(rooturl)this.rooturl = rooturl;
				// this.initwatchHash();
				this.loaded();
				$('#content').after('<div id="loader" class="hidden"><img src="'+this.root+'/images/douchebagloading.gif" /></div>');
				$('#content').append('<img class="hidden" id="preloader"/>');
				$('#loader').click(function(){
					$('#loader').css({display:'none'});
					$('#content').css({display:'block'});
				})
				$('.showthing,#thingback,#thingimg,#thing h1').click(this.showthing).css({cursor:'pointer'});
				
				
				// $.cookie('has_been_here_before',1,{expires: 30,path:'/'});
				// 	
				// 	if($.cookie('app_intro') == null){
				// 			this.showthing();
				// 	}
				// 	$.cookie('app_intro',1,{expires: null,path:'/'});

				return this;
			},
			loaded: function(){
				// this.fadeInImages();
				this.enableWorklist();
				// this.enableKeyBordShortcuts();
				this.videoplayer();
				this.enableAjaxNav();
				this.setUpChange();
				this.preload();
				
				//TODO: BETTER GALLERY
				$.fn.fancyzoom.defaultsOptions.imgDir=this.root+'/images/zoom/';
				$('a[href*=.jpg],a[href*=.png]').fancyzoom({showoverlay:true,overlay:.5}).addClass('zoomlink');
				
				$('a[href^=http][rel=framed]').each(function(i,e){
					$(e).attr('href',app.rooturl+'/frame/?t='+$(e).attr('href'));
				});
				
			},
			/*
				Automatic Ajax Version
			*/
			enableAjaxNav: function(){
				$('#sitenav a,#worklist a,#project-nav a').unbind('click',this.clickAjaxLink).click(this.clickAjaxLink);
			},
			clickAjaxLink:function(){
				// $('#container').remove();
				// $('#loader').css({display:'block'});
							$('#loader').css({display:'block'});
							$('#content').css({display:'none'});
				// app.loadpage($(this).attr('href'),$(this).is('.up'));
				// return false;
			},
		  loadpage: function(url,up){
					url += '/';
					
		
					var nh = url.replace(this.rooturl,'');
					if(!app.setHash(nh))return;	
						// $('#container').remove();
						$('#loader').css({display:'block'}); //.css({opacity:0}).animate({opacity:1},300,'easeInOutQuad');;
					// $('#container').animate({opacity:0},300,'easeInOutQuad',function(){
					// 	$('#container').remove();
					// 	$('#header').after('<img width="400px" height="400px" style="margin :26px 0 26px 0" id="loader" class="" src="'+aplusplus.root+'/images/douchebagloading.gif"/>');
					// 	$('#loader')
					// })
					
					if(app.cache[app.oldhash]) {
						this.loadedpage(this.cache[this.oldhash],nh,up);
					} else {
						$.ajax({
							url:url,
							data:'ajax=1',
							dataType:'html',
							success:function(d){
								// alert('ajax loaded!');
								app.loadedpage(d,nh,up);
							},
							error:function(){
								// alert('ajax error!');
								self.location.href = url;
							}
						})
					}
			},
			loadedpage: function(d,nh,up){
				if(!d) return;
				app.cache[app.oldhash] = d;
				values = (up) ? {pout:'5%',pin:'-5%'}:{pout:'-5%',pin:'5%'};
				values = {pout:0,pin:0}
				// $('#wrapper').addClass('aniout').after(d);
				
				$('#wrapper').addClass('aniout').animate({left:values.pout,opacity:0},300,'easeInOutExpo',function(){
					$('#wrapper.aniout').remove();
				
					
				}).after(d);
				// 
				app.waitplace = setInterval(function(){
					if($('#wrapper:not(.aniout)').length != 0){
						clearInterval(app.waitplace);
						$('#wrapper:not(.aniout)').css({opacity:0,left:values.pin,display:'block'}).animate({left:0,opacity:1},500,'easeInOutExpo',function(){
							$('#wrapper #content').css({visibility:'visible',opacity:1});// .animate({opacity:1},300);
						});
						app.loaded();
					}
				},1)
			},
			initwatchHash: function(){
				
				this.starturl = self.location.href;
				this.starturl = this.starturl.replace(this.rooturl,'');
				window.location.hash = this.starturl;
				this.oldhash = window.location.hash;
				app.cache[this.starturl] = $('#wrapwrap').html()
				clearInterval(this.hashcheck);
				this.hashcheck = setInterval(function(){
					this.app.watchHash();
					},300);
			},
			setHash: function(nh){
				if(nh == ''){
					nh = "/"
				}
				
				if(this.oldhash == '#'+nh)return false;
				this.oldhash = '#'+nh;
 				window.location.hash = nh;
				return true;
			},
			watchHash: function(){
				// console.log(window.location.hash+' == '+this.oldhash);
				if(window.location.hash != this.oldhash){
					this.loadpage(this.getHashUrl());
				}
				this.oldhash = window.location.hash;
			},
			getHashUrl: function(){
				return this.rooturl+window.location.hash.substr(1); d
			},
			/*
			*	Preloading
			*/
			preload: function(){
				// $('#container').after('<img width="400px" height="400px" style="background:black;margin :26px 0 26px 0" id="loader" class="hidden" src="'+app.root+'/images/douchebagloading.gif"/>');
				this.preloadLinks();
			},
			preloadLinks: function(){
				$('a').each(function(i,e){
					e = $(e);
					if(e.attr('rel')=='load'){
						href=e.attr('href');
						if(href.match(/^#/) ||  href == '' || !href) return;
							$('body').append('<iframe src='+href+' style="display:none"/>');
					}
				})
			},
			/*
			*	ul.change slideshows
			*/	
			setUpChange: function(){
				$('.change li').css({display:'none'}).eq(0).css({display:'block'});
				clearInterval(this.change);
				this.change = setInterval(this.changechange,5000);
			},
			changechange: function(el){
				$('.change').each(function(){app.triggerChangeLi(this);});
			},
			triggerChangeLi:  function(el){
				visibleIndex = null;
				c = 0;
				$('li',el).each(function(i,e){
					c++;
					if($(e).is(':visible')){
						visibleIndex = i;
					}
				});
				visibleIndex++;
				if(visibleIndex>(c-1)){
					visibleIndex = 0;
				}
				$('li',el).css({display:'none'}).eq(visibleIndex).css({display:'block'});
			}
		,
		/*
		*	jw player
		*/
		videoplayer:function(){
				if($('body').is('.ip-1')) return  //no flash for iphone;
			$('a[href*=.flv],a[href*=.mov],a[href*=.mp4]').each(function(i,e){
				e = $(e);
				e.attr('id','video'+i);
				var flashvars = {};
				flashvars.file = e.attr('href');
				flashvars.image = $('img',e).eq(0).attr('src');
				flashvars.controlbar = 'over'; 
				flashvars.autostart = false;
				flashvars.fullscreen = true;
				flashvars.skin = app.root+'/players/skin.swf';
				var params = {};
				params.scale = "noscale";
				params.wmode = "transparent";
				params.align = 'middle'
				params.allowfullscreen = "true";
				params.bgcolor = '#000000';
				params.allowscriptaccess = 'always';
				var attributes = {'class':'videoplayer',align:'left'};
				swfobject.embedSWF(app.root+'/players/player.swf',e.attr('id'),$('img',e).eq(0).width(),$('img',e).eq(0).height(),'9',true,flashvars,params,attributes);
			});
		}
	,
	/*
	*	WORKLIST!
	*/
	enableWorklistO: function() {
		if($('#worklist').length==0)return;	
		$('#worklist').css({visibility:'hidden'});
		if(!this.dbcreated){
			$('#worklist img').each(function(i,e){
				e = $(e);
				app.sizeDB[e.attr('id')] = {
					width:e.width(),
					height:e.height(),
					ratio:e.width()/e.height(),
					size:'t',
					img:0,
					slideInt:0,
					cw:null,
					ch:null,
					id:e.attr('id'),
					pics:app.sizeDB[e.attr('id')+'_i']
				};	
			});
			this.dbcreated = true;
		}
	
		this.enableSlideShows();
		$('#worklist').css({visibility:'visible'});
	},
	enableWorklist: function() {
		if($('#worklist').length==0)return;	
		$('#worklist').css({visibility:'hidden'});
		if(!this.dbcreated){
			app.dynSizeDB = {};
			$('#worklist .work-content a').each(function(i,e){
				e = $(e);
				app.dynSizeDB[e.attr('id')] = {
					width:e.width(),
					height:e.height(),
					ratio:e.width()/e.height(),
					size:'t',
					img:0,
					slideInt:0,
					cw:null,
					ch:null,
					id:e.attr('id'),
					pics:$('img',e),
					picCount:$('img',e).length
				};	
			});
			this.dbcreated = true;
		}
		// console.log(app.dynSizeDB);
		// this.enableSlideShows();
		this.subSildeShow();
		$('#worklist').css({visibility:'visible'});
	},
	subSildeShow: function(){
		$('.sub-slideshow').addClass('active').hover(
		function(a){
			var e = $(a.target).parent();
			d = app.dynSizeDB[e.attr('id')];
			if(!d)return;
			clearTimeout(d.slideInt);
			app.performSubSlide(e,true);
			
		},
		function(a){
			var e = $(a.target).parent();
			d = app.dynSizeDB[e.attr('id')];
			// if(!d.slideInt){
			// 	d.slideInt = 0;
			// }
			if(d.slideInt)clearTimeout(d.slideInt);
			d.slideInt = setTimeout(function(){app.performSubSlide(e,false);},(Math.random()*(8000))+5000);

		}).each(
			function(i,e){
				d = app.dynSizeDB[$(e).attr('id')];
				if(!d)return;
				d.img = 0;
			
				d.pics.each(function(si,se){
					$(se).css({opacity:0,zIndex:d.picCount-si});
				}).eq(d.img).css({opacity:1,zIndex:200});
					if(d.pics.length <= 1)return;
					
				d.slideInt = setTimeout(function(){app.performSubSlide(e,false)},(Math.random()*(8000))+4000);
		}).mousemove(function(a){
			// app.performSubSlide(a.currentTarget,true);
		});
		
	//.eq(1).show();
	},
	performSubSlide:function(e,over){
		
		
		e = $(e);
		var d = app.dynSizeDB[$(e).attr('id')];
		if(d.slideInt)clearTimeout(d.slideInt);
		if(d.pics.length <= 1)return;
		d.oimg = d.img;
		if(d.img-- == 0)d.img = d.picCount-1;
		
		// d.pics.eq(d.oimg).animate({opacity:1,top:'118px'},460,'easeInOutQuint');
		// d.pics.eq(d.img).css({zIndex:d.img+200,opacity:1,top:'-118px'}).animate({opacity:1,top:0},460,'easeInOutQuint',function(){
		// 	d.pics.eq(d.oimg).css({opacity:0,top:0});
		// });
		// d.pics.eq(d.oimg).css({zIndex:d.picCount-d.oimg});
		
		
		d.pics.eq(d.oimg).css({zIndex:d.picCount-d.oimg});
		d.pics.eq(d.img).css({zIndex:d.img+200,opacity:0}).animate({opacity:1,top:0},200,'easeInOutQuint',function(){
			d.pics.eq(d.oimg).css({opacity:0,top:0});
		});
		// 
		// d.pics.eq(d.oimg).css({zIndex:d.picCount-d.oimg,opacity:0});
		// d.pics.eq(d.img).css({zIndex:d.img+200,opacity:1});

		
		
		var t = (over) ? 400 : (Math.random()*(8000))+4000;
		d.slideInt = setTimeout(function(){app.performSubSlide(e,over);},t);

	},
	removeSubSildeShow: function(){
		$('.sub-slideshow').toggleClass('active');
	},
	enableSlideShows:  function(){
		$('#worklist img:not(.slideshow)').each(function(i,e){
			e = $(e);
			
			// console.log(e.attr('id').substr(1));
			var store = app.sizeDB[e.attr('id')];
		
			if(store.pics == undefined || store.pics.length<1 || store.pics[0].slides != 1) return;
			
				e.addClass('slideshow').parent().mousemove(function(e){
					var c = new Date();
					c = c.getTime();
					if(store.lastcall && Math.abs(store.lastcall -c) < 200){
						return;
					}
					clearInterval(store.autoslide);
					store.lastcall = c;
					return app.nextImage(store,false);
					}).mouseout(function(){
						clearInterval(store.autoslide);
						store.autoslide = setInterval(function(){
							app.nextImage(store);
						},(Math.random()*(2000))+2000);
						}).addClass('slideshowtrigger').trigger('mouseout');
						
						
			})
	},
	disableSlideShows:  function(){
		$('#worklist a.slideshow').each(function(i,e){
			var id = $(e).attr('id').substr(1);
			var store = this.sizeDB['wt'+e.attr('id')];
			clearInterval(store.autoslide);
			store.autoslide = null;
		})
		//remove slideshow
		$('.slideshow').removeClass('slideshow');
		$('.slideshowdisplay').remove();
		$('.slideshowtrigger').unbind('click');
	},
	preloadImage:function(src, callback){
		$('#preloader').clone().load(function(){
			callback.apply();
			$(this).remove();
		}).attr('src',src)
	},
	nextImage:  function(store,autonext){
			var e = $('#'+store.id);
			var bu = (store.pics[store.img].bu != undefined) ? ''+store.pics[store.img].bu : '';
			store.img++
			if(!store.pics[store.img]) store.img = 0;
			this.preloadImage(store.pics[store.img][store.size],function(){
				e.attr('title',(store.img+1)+'/'+store.pics.length).attr('src',store.pics[store.img][store.size]);
			});
			return false;
	},
	showNextImage:function(){
		
	},
	fadeInImages: function() {
		// return;
		// var wh = $(window).height()+600;
		$('.attachments li,#worklist li').each(function(i,e){
			e = $(e);
			// if(e.offset().top < wh){
					e.css({opacity:0}).animate({opacity:0},10+(i+1)*30,'linear',function(){
						e.animate({opacity:1},300+(i*30),'easeInOutQuad');
					});	
			// }
		})
		// $('.attachments li,#worklist li').shadow();
	},
	showthing:function(){
			if($('#thing').is(':visible')){
				$('#thing').css({display:'none'});
			}else {
				$('#thing').css({display:'block'})
				$('#thingcontent').css({opacity:0}).animate({opacity:1},700,'easeInOutQuad');;
			}
			return false;
		},
		hidething:function(){

		}
	}
})()






