/* WORK FUNCTIONS
-----------------------------------------------------*/
function deleteMe(id) {
	var el = document.getElementById(id);
	el.parentNode.removeChild(el);
};

(function($) {
	var skipFirstTracking = false;
	var pageTitle = document.title.split('|');
	pageTitle = pageTitle[pageTitle.length-1];
	
	var workApp = {		
		_setupVars: function() {
			workCats = [];
			prevFile = {};
			nextFile = {};
			images = [];
			current = { slidePos:0, imagePos:0 };
			imageDirectory = '/images/work/';
			navAnchors = navAnchors = $('#subnav a');
			menu = $('#campaign-menu');
			bottom = $('#work-bottom');
		},
				
		init: function() {
			this._setupVars();
			workTop = $('#work-top-content');
			loading = $('<div id="loading"><img src="/images/work-ajax-loader.gif" alt="Loading" /></div>').appendTo(workTop).hide();
			slider = $('<div></div>').css({ position:'absolute', top:0, left:0 }).appendTo(workTop);
			hover = $('<div id="campaign-menu-hover"></div>').appendTo('body').hide();

			$('<div id="nextPrev"><a id="nextButton" href="#"></a> <a id="prevButton" href="#"></a></div>').appendTo(workTop).hide()
				.find('#nextButton').click(this.gotoNextSample).end()
				.find('#prevButton').click(this.gotoPrevSample);
			$('#subnav ul li a').click(this._catClicked);
			
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this._updatePage);
		},
		
		nextSample: function(t) {
			//$(loading).css({ opacity:.7 }).show();
			prevFile = nextFile;
			if(!(nextFile = current.category.samples[current.index])) {
				nextFile = workApp._getSampleById(current.index);
				current.index = workApp._lookUpIndex(nextFile);
			};
			if(!nextFile) {
				workApp.nextSample(t);
			};
			nextFile.index = current.index;
			
			setTimeout(function() {
				SWFAddress.setTitle(nextFile.name.replace(/&amp;/g, '&')+' '+nextFile.type+' | '+pageTitle);
				urchinTracker('/work/'+current.category.url+'/'+nextFile.id+'/');
			}, 100);
			$('#samples li').eq(current.index).siblings().find('a').removeClass('current').end().end().find('a').addClass('current');
			
			if(prevFile && prevFile.index>nextFile.index) { direction = 'right'; } else { direction = 'left'; };			
			
			if(nextFile.filename.slice(-3) != 'swf' || nextFile.filename != prevFile.filename) {
				$('#flash-container object').each(function(i,obj) { 
					document.getElementById(obj.id).stopAll(obj.id);
				});
			}
			
			switch(nextFile.filename.slice(-3)) {
				case 'swf':	workApp._changeFlash();
							break;
				default:	workApp._changeImage();
			};
			
			$(menu).animate({ top:345 }, 300, function() { 
				$(menu).find('#case-study').html(nextFile.case_study);
			});
		},
		
		_getSampleById: function(id) {
			var l = current.category.samples.length;
			var f = null;
			for(var i = 0; i<l; i++) {
				if(current.category.samples[i].id == id+1) {
					f = current.category.samples[i];	
					i=1000;
				};
			};
			return f;
		},
		
		_changeFlash: function() {			
			current.imagePos += (direction=='left' ? 650 : -650);
			
			$(loading).stop().fadeOut();
			if(prevFile.filename == nextFile.filename) {
				nextFile.flash = { id:prevFile.flash.id };
				document.getElementById(nextFile.flash.id).nextSample(current.category.samples[current.index].flash_filename);	
			} else {
				workApp._slideImages(true);
				
				var flash = $('<div id="flashInstance-'+Math.round(Math.random()*100)+'"></div>').appendTo('#flash-container');
				nextFile.flash = { id:$(flash).attr('id') };
			
				var flashvars = { currentSample:current.category.samples[current.index].flash_filename };
				var params = { menu:"false", wmode:"transparent", allowscriptaccess:"always", allowFullScreen:"true" };
				var attributes = {};
				swfobject.embedSWF("/flash/"+current.category.samples[current.index].filename, nextFile.flash.id, "615", "335", "9.0.0","/flash/expressInstall.swf", flashvars, params, attributes);
			}
			$('#sample-title','#sample-description').stop();
			$(bottom).find('#sample-title').animate({ left:-300 }, 200).end().find('#sample-description').animate({ top:200 }, 200, workApp._changeBottom);
		},
		
		_changeImage: function() {
			var html = new Array('<img class="sample-preview" src="/images/work/',nextFile.filename,'" />');
			current.imagePos += (direction=='left' ? 650 : -650);
			$(html.join('')).css({ position:'absolute', left:current.imagePos }).appendTo(slider).load(function() {
				images.push(this);
				$(loading).stop().fadeOut();
				workApp._slideImages();
				
				$('#sample-title','#sample-description').stop();
				$(bottom).find('#sample-title').animate({ left:-300 }, 200).end().find('#sample-description').animate({ top:200 }, 200, workApp._changeBottom);
			});
		},
		
		_slideImages: function(flashLoaded) {
			var last = images.length-(flashLoaded ? 1 : 2);
			var l = (flashLoaded ? (direction=='left' ? '-=650px' : '+=650px') : -parseInt($(images[last+1]).css('left')));
			$(slider).animate({ left:l }, 500, function() {																					  
				if(last>=0) {
					var r = images.shift();
					$(r).remove();
				}
			});
			current.slidePos += (direction=='left' ? 650 : -650);	
		},
		
		_changeBottom: function() {
			$('#sample-title').html(nextFile.name+'<br /><em>'+nextFile.type+'</em>');
			$('#sample-description').html(nextFile.overview+'<p class="case-study"></p>');
			
			if(nextFile.case_study) { $('<a href="/work/'+current.category.url+'/'+nextFile.id+'/case-study/">Case Study</a><br />').appendTo('.case-study').click(workApp._toggleCaseStudy); };
			if(nextFile.link_url) { $('<a href="http://'+nextFile.link_url+'">Visit Site</a><br />').appendTo('.case-study').click(function() { 
				window.open(this.href);  
				urchinTracker(nextFile.link_analytics);
				return false; 
			});};
			if(nextFile.link_other) { $('<div>'+nextFile.link_other+'</div>').appendTo('.case-study'); };
			$('#sample-title','#sample-description').stop(true,true);
			$(bottom).find('#sample-title').css({ left:-300 }).animate({ left:15 }, 350).end().find('#sample-description').css({ top:-200 }).animate({ top:0 }, 300);
		},
		
		_changeMenu: function() {
			var html = new Array('<h2>',current.category.name,'</h2>');
			html.push('<ul id="samples">');
			for(var i=0, sample; sample = current.category.samples[i]; i++) {
				html.push('<li><a ',(i==current.index ? 'class="current" ' : ''),'title="',sample.name,'" href="/work/',current.category.url,'/',i+1,'/">',i+1,'</a></li>');
			};
			html.push('</ul>');
			html.push('<div id="case-study">',nextFile.case_study,'</div>');
			$(menu).html(html.join('')).find('a').each(function(i,a) {
				$(this).click(function() {
					current.index = i; 
					SWFAddress.setValue(current.url+'/'+parseInt(current.index+1)+'/');
					return false; 
				});													
			});
			
			$(menu).animate({ top:345 });
		},
		
		_toggleCaseStudy: function() {
			var t = (parseInt($(menu).css('top')) != 345 ? 345 : 400-$(menu).height());
			$(menu).animate({ top:t }); 
			return false;	
		},
		
		gotoNextSample: function() {
			if(current.index+1<current.category.samples.length) {
				current.index++;
				SWFAddress.setValue(current.url+'/'+parseInt(current.index+1)+'/');
			};
			return false;
		},
		
		gotoPrevSample: function() {
			if(current.index-1>=0) {
				current.index--;
				SWFAddress.setValue(current.url+'/'+parseInt(current.index+1)+'/');
			}
			return false;
		},
		
		_catClicked: function() {
			var h = this.href;
			if(h.charAt(h.length-1)=='/') h = h.slice(0,-1);
			h = h.substr(h.lastIndexOf('/')+1)+'/';
			SWFAddress.setValue(h);
			return false;
		},
				
		_updatePage: function() {
			var v = SWFAddress.getValue().substr(1);
			if(v.indexOf('?')>=0) {
				v = v.substr(0,v.indexOf('?'));
			};
			v = v.split('/');
			if(!v[0]) return false;

			current.index = (v[1] ? v[1]-1 : 0);
			$('#nextPrev').fadeIn();
			if(current.url == v[0]) {
				workApp.nextSample();
			} else {
				current.url = v[0];
				
				$(navAnchors).removeClass('current');
				$('#subnav').find('a[href$=/work/'+current.url+'/]').addClass('current');
				if(!skipFirstTracking) {
					urchinTracker('/work/'+current.url+'/');
				};
				skipFirstTracking = false;
				if(!workCats[current.url]) {
					$(loading).css({ opacity:.9 }).show();
					$.getJSON('/ajax-data.php', { action:'workCategory', category:current.url }, workApp._handleNewCat);
				} else {
					current.category = workCats[current.url];
					$(menu).stop().animate({ top:380 }, 300, workApp._changeMenu);
					workApp.nextSample();
				};
			}
		},
		
		_lookUpIndex: function(file) {
			for(var i=0; i<current.category.samples.length; i++) {
				if(current.category.samples[i].id == file.id) {
					return i;
				};
			};
			return 0;	
		}, 
		
		_handleNewCat: function(res) {
			if(res.error) {
				$(loading).stop().fadeOut();
				alert(res.error);
			} else {
				current.category = workCats[res.url] = res;
				$(menu).stop().animate({ top:380 }, 300, workApp._changeMenu);
				workApp.nextSample();
			}
		}
	};
		  
	$(document).ready(function() {
		var href = String(window.location);
		if(href.indexOf('#')>0) skipFirstTracking = true;
		workApp.init();
	});
})(jQuery);