var Local = {

    onCommentReply: function(id) {
		Comments.openReply(id);
	},

    onCancelReply: function(id) {
		Comments.closeReply();
	}

};

var wt = {}; // This is the setup for the webtools namespace

(function() { // This is where jQuery code can safely go without foobarring prototype
	var $ = jQuery
	
	$(document).ready(function() { // These functions get called on DOM ready
		$('a').click(function() { $(this).blur() }) // prevents outlines on links for IE
		wt.hero() // Crossfades hero shots if applicable
		wt.formDefaults()
		wt.bookmarkClick()
		wt.slideshow()
		$('ul.presentations-list a').not('[href$=pdf]').each(function() {
			var link = $(this)
			link.click(function(c) {
				c.preventDefault();
				if(!$('div#ajax-temp').size()) {
					$('body').append($(jQuery('<div id="ajax-temp" style="display: none"></div>')))
				}
				if(!$('div#overlay').size()) {
					$('body').append($(jQuery('<div id="overlay"></div>')))
				} else {
					$('#overlay').show()
				}
				$('div#ajax-temp').load(
					link.attr('href') + ' div.slideshow',
					{},
				 	function(){
						var content = $('div#ajax-temp').children()
						wt.slideshow()
						$('body').append(content)
						$('div#ajax-temp').html('')
					}
				);
			});
		});
		wt.socialNetworks($('li.share a'))
		wt.equalStories();
	})
	
	$(window).load(function() { // These functions get called when everything has loaded
		$('#main_left, #main_right').equalizeCols()
	})
	
	wt.slideshow = function(callback) {
		if(!$('.slideshow').size()) { return; }
		var duration = 5000
		var transition = 1000
		
		wt.slideshow.loops = [];
		
		var containers = $('.slideshow')
		containers.each(function() {
			var loop = wt.slideshow.loops.length
			wt.slideshow.loops[loop] = null;
			var container = $(this)
			var close = container.find('.close')
			var previous = container.find('.previous')
			var next = container.find('.next')
			var playPause = container.find('.play-pause')
			var progressMeter = container.find('.progress-meter')
			$('#overlay').width($('body').width()).height($('body').height() > $(window).height() ? $('body').height() : $(window).height())
			
			close.click(function(c) {
				c.preventDefault()
				container.hide()
				$('#overlay').hide()
				if(container.hasClass('video')) {
					clearInterval(wt.slideshow.video.updateMeter.loop)
					clearInterval(wt.slideshow.video.updateMeter.downloadLoop)
				}
			});
			
			container.removeClass('video').removeClass('images')

			if(container.find('img').size()) { // This is a slideshow
				container.addClass('images')
				var images = container.find('img')
				images.each(function(i) {
					$(this).attr({'count': i+1})
				});
				images.hide()
				$(images[0]).show().attr({'current': 'current'})
				
				wt.slideshow.rotateImage = function(images, direction) {
					var current = images.filter('[current]')
					var previousImage = images.filter('[count=' + (parseInt(current.attr('count'),10) - 1) + ']')
					var nextImage = images.filter('[count=' + (parseInt(current.attr('count'),10) + 1) + ']')
					var lambdaImage = direction == 'previous' ? previousImage : nextImage;
					if(lambdaImage.size()) {
						current.removeAttr('current').fadeOut(transition)
						lambdaImage.attr({'current': 'current'}).fadeIn(transition)
						progressMeter.width( ((100 / images.size()) * parseInt(lambdaImage.attr('count'),10)) + '%' )
					}
				}
				
				wt.slideshow.stopLoop = function(playPause) {
					playPause.removeClass('pause').addClass('play')
					clearInterval(wt.slideshow.loops[loop])
					wt.slideshow.loops[loop] = null;
				}
				
				wt.slideshow.startLoop = function(images,playPause) {
					playPause.removeClass('play').addClass('pause')
					wt.slideshow.rotateImage(images,'next')
					wt.slideshow.loops[loop] = setInterval(function() {
						wt.slideshow.rotateImage(images,'next')
					}, duration + transition)
				}
				
				previous.click(function(c) {
					c.preventDefault()
					wt.slideshow.stopLoop(playPause)
					wt.slideshow.rotateImage(images,$(this).attr('href').substr(1))
				});

				next.click(function(c) {
					c.preventDefault()
					wt.slideshow.stopLoop(playPause)
					wt.slideshow.rotateImage(images,$(this).attr('href').substr(1))
				});

				playPause.click(function(c) {
					c.preventDefault()
					if(playPause.hasClass('play')) {
						playPause.removeClass('play').addClass('pause')
						wt.slideshow.startLoop(images,playPause)
					} else {
						playPause.removeClass('pause').addClass('play')
						wt.slideshow.stopLoop(playPause)
					}
				});

				container.find('.progress-wrapper').click(function(c) {
					var point = c.clientX - container.find('.progress-wrapper').offset().left
					var newImage = Math.round(images.size() * (point / 100))
					var current = images.filter('[current]')
					var previousImage = images.filter('[count=' + (parseInt(current.attr('count'),10) - 1) + ']')
					var nextImage = images.filter('[count=' + newImage + ']')
					if(nextImage.size()) {
						current.removeAttr('current').fadeOut(transition)
						nextImage.attr({'current': 'current'}).fadeIn(transition)
						progressMeter.width( ((100 / images.size()) * parseInt(nextImage.attr('count'),10)) + '%' )
					}
				});
				
			} else if(container.find('a.attachment-file').size()) { // This is a video
				container.addClass('video')
				var videoLink = container.find('a.attachment-file')
				videoLink.attr({'id': 'video-link'})
				wt.slideshow.video = flashembed("video-link", { src: '/FlowPlayerLight.swf', width: 640, height: 510, }, {config: { autoPlay: false, autoBuffering: false, videoFile: videoLink.attr('href'), loop: false, usePlayOverlay: false }} );
				
				wt.slideshow.video.updateMeter = function() {
					var timer = container.find('.progress-meter')
					var counter = container.find('.progress-counter')
					var download = container.find('.progress-download')
					wt.slideshow.video.updateMeter.loop = setInterval(function() {
						if(typeof wt.slideshow.video.getTime() != 'number') { return; }
						var time = Math.round(wt.slideshow.video.getTime())
						var duration = Math.round(wt.slideshow.video.getDuration())
						timer.css({'width': ((time / duration) * 100) + '%'});
//						counter.innerHTML = Math.floor(time/60) + ':' + ((time % 60) < 10 ? '0' + (time % 60) : (time % 60)) + '/' + Math.floor(duration/60) + ':' + ((duration % 60) < 10 ? '0' + (duration % 60) : (duration % 60));
						if(!wt.slideshow.video.getIsPlaying()) {
							wt.slideshow.video.updateMeter.isRunning = false;
						} else {
							wt.slideshow.video.updateMeter.isRunning = true;
						}
					},10)
					if(!wt.slideshow.video.getPercentLoaded() || wt.slideshow.video.getPercentLoaded() < 100) {
						wt.slideshow.video.updateMeter.downloadLoop = setInterval(function() {
							download.css({'width': wt.slideshow.video.getPercentLoaded() + '%'});
							if(wt.slideshow.video.getPercentLoaded() == 100) {
								clearInterval(wt.slideshow.video.updateMeter.downloadLoop)
							}
						}, 10)
					} else {
						clearInterval(wt.slideshow.video.updateMeter.downloadLoop)
					}
					wt.slideshow.video.updateMeter.isRunning = true;
				}

				wt.slideshow.video.updateMeter.isRunning = false;
				
				playPause.click(function(c) {
					c.preventDefault()
					if(playPause.hasClass('play')) { // Play the video
						if(!wt.slideshow.video.updateMeter.isRunning) {
							wt.slideshow.video.updateMeter();
						}
						playPause.removeClass('play').addClass('pause')
						wt.slideshow.video.DoPlay();
					} else { // Pause the video
						playPause.removeClass('pause').addClass('play')
						wt.slideshow.video.Pause();
					}
				});
				
				previous.click(function(c) {
					c.preventDefault()
					wt.slideshow.video.Seek(0);if(wt.slideshow.video.getIsPlaying() == false) { wt.slideshow.video.DoPlay(); }
				});
				
				container.find('.progress-wrapper').click(function(c) {
					var point = c.clientX - container.find('.progress-wrapper').offset().left
					if(wt.slideshow.video.getDuration()) { // This only works if the video has started and we know the length
						var duration = wt.slideshow.video.getDuration();
						wt.slideshow.video.Seek(Math.round(duration * (point / 100)))
//						console.log({'duration': duration, 'point': point, 'seconds': Math.round(duration * (point / 100))})
					}
				});
			}
		});
		if(typeof callback == 'function') { callback(); }
	}
	
	wt.bookmarkClick = function() {
	    if(!$('html#home ul.linkage').size()) {
	        return
	    }
	    $('ul.linkage li.bookmark a').click(function(c){
			c.preventDefault();
			
            title = document.title; 
            url = window.location.href;

               if (jQuery.browser.mozilla) { // Firefox 
                   window.sidebar.addPanel(title, url,"");
               } else if( jQuery.browser.ie ) { // IE 
                   window.external.AddFavorite( url, title);
               } else if(jQuery.browser.opera) {
                   CreateBookmarkLink();
               } else { 
                   alert("For Safari, press CTRL-D");
               }
		})
	}
	
	wt.formDefaults = function() { // Swaps default text form input values to blank on focus and back to default text on blur
		$('input:text,textarea').each(function() {
			var elem = $(this)
			var defaultText = elem.val()
			elem.focus(function(){
				if(elem.val() == defaultText) {
					elem.val('')
				}
			})
			elem.blur(function(){
				if(elem.val() == '') {
					elem.val(defaultText)
				}
			})
		})
	}

	wt.hero = function() { // Heroshot crossfader; set options below this function

		if(!$('#imageFadeContainer').size()) {
			return
		}
		
		wt.hero.interval = null
		
		wt.hero.container = $('#imageFadeContainer')

		var fade = wt.hero.container.find('input[name=fadevalue]')
		wt.hero.fade = fade.val() * 1000
		fade.remove()
		
		var dur = wt.hero.container.find('input[name=showvalue]')
		wt.hero.dur = dur.val() * 1000
		dur.remove()
		
		if(wt.hero.useForeground) {
			wt.hero.container.append(
				$(jQuery('<div />')).attr({id: 'hero-foreground'})
			)
		}
			
		if(wt.hero.useCaptions) {
			if(wt.hero.container.children('a:first-child').size()) {
				var firstCaption = wt.hero.container.children('a:first-child').children('img').attr('alt')
			} else if(wt.hero.container.children('img:first-child').size()) {
				var firstCaption = wt.hero.container.children('img:first-child').attr('alt')
			} else {
				var firstCaption = ''
			}

			wt.hero.container.append(
				$(jQuery('<div />'))
					.attr({id: 'hero-caption'})
					.append(
						$(jQuery('<span />'))
							.attr({id: 'caption-holder'})
							.show()
							.text(firstCaption)
					)
			)
		}

		if(wt.hero.container.children('a,img').size() < 2) { // Less than two images, we don't need to xfade or add controls
			return
		}
		
		if(wt.hero.useControls) {
			wt.hero.container.append(
					$(jQuery('<div />'))
						.attr({id: 'hero-controls'})
						.append(
							$(jQuery('<ul />'))
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Previous Photo',
													id: 'hero-previous',
													href: '#previous-photo'
												})
												.click(function(c){
													c.preventDefault()
													clearInterval(wt.hero.interval)
													wt.hero.rotate('prev')
													$('#hero-pause').hide()
													$('#hero-play').show()
												})
										)
								)
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Pause Photos',
													id: 'hero-pause',
													href: '#pause-photos'
												})
												.click(function(c){
													c.preventDefault()
													clearInterval(wt.hero.interval)
													$('#hero-pause').hide()
													$('#hero-play').show()
												})
												.css({display: 'block'})
												.show()
										)
								)
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Play Photos',
													id: 'hero-play',
													href: '#play-photos'
												})
												.click(function(c){
													c.preventDefault()
													wt.hero.interval = setInterval(function(){
														wt.hero.rotate('next')
													}, wt.hero.dur + wt.hero.fade)
													$('#hero-pause').show()
													$('#hero-play').hide()
												})
												.css({display: 'block'})
												.hide()
										)
								)
								.append(
									$(jQuery('<li />'))
										.append(
											$(jQuery('<a />'))
												.attr({
													title: 'Next Photo',
													id: 'hero-next',
													href: '#next-photo'
												})
												.click(function(c){
													c.preventDefault()
													clearInterval(wt.hero.interval)
													wt.hero.rotate('next')
													$('#hero-pause').hide()
													$('#hero-play').show()
												})
										)
								)
						)
				)
		}
			
			
		wt.hero.container.children('a:first-child,img:first-child').attr({current: 'current'})
		wt.hero.container.children('a:not(:first-child),img:not(:first-child)').hide()
		if(jQuery.browser.safari) {
			wt.hero.container.children('a:not(:first-child),img:not(:first-child)').css({display: 'none'})
		}

		wt.hero.interval = setInterval(function() {
			wt.hero.rotate('next')
		}, wt.hero.dur + wt.hero.fade)

		wt.hero.rotate = function(dir) {
			if(typeof dir == 'undefined') {
				var dir = 'next'
			}
			var images = wt.hero.container.children('a,img')
			var current = wt.hero.container.children('a[current],img[current]')
			if(dir == 'next') {
				if(current.next('a,img').size()) {
					var to = current.next('a,img')
				} else {
					var to = $(images[0])
				}
			} else {
				if(current.prev('a,img').size()) {
					var to = current.prev('a,img')
				} else {
					var to = $(images[images.size() - 1])
				}
			}

			current.removeAttr('current').fadeOut(wt.hero.fade)
			
			if(wt.hero.useCaptions) {
				wt.hero.container.find('#caption-holder').fadeOut(wt.hero.fade / 2, function(){
					wt.hero.container.find('#caption-holder').text(to.find('img').size() ? to.find('img').attr('alt') : to.attr('alt'))
					wt.hero.container.find('#caption-holder').fadeIn(wt.hero.fade / 2)
				})
			}

			if(wt.hero.useForeground) {
				if(to.href != 'undefined') {
					wt.hero.container.find('#hero-foreground').bind('click',function() {
						window.location = to.href
					})
				} else {
					wt.hero.container.find('#hero-foreground').unbind('click',function() {
						window.location = to.href
					})
				}
			}
			to.attr({current: 'current'}).fadeIn(wt.hero.fade)
		}
	}

	// Heroshot options
	wt.hero.useForeground = true
	wt.hero.useControls = true
	wt.hero.useCaptions = true
	
	wt.socialNetworks = function(links) {
		if(typeof links == 'undefined') { return; }
		wt.socialNetworks.urlEscape = function(inputString) {
			var encoded = escape(inputString);
			encoded = encoded.replace(/http%3A\/\//gi,'');
			encoded = encoded.replace(/\+/gi, "%2B");
			encoded = encoded.replace(/\//gi, "%2F");
			encoded = encoded.replace(/iago/gi,'com');
			return encoded;
		}

		var page = [];
		page['url'] = wt.socialNetworks.urlEscape(window.location);
		page['title'] = wt.socialNetworks.urlEscape($('.entry h2').html());
		page['description'] = wt.socialNetworks.urlEscape($('.entry h4').html());
		
		
		links.each(function() {
			var link = $(this)
			var list = $(jQuery('<ul />'))
			var digg = $(jQuery('<li />'))
			digg.addClass('digg')
			var diggLink = $(jQuery('<a />'))
			diggLink.click(function(c) {
				c.preventDefault()
				window.open('http://digg.com/submit?url='+page.url+'&title='+page.title+'&bodytext='+page.description+'&topic=design&step=2','digger');
			});
			diggLink.html('Digg')
			diggLink.attr({'href': '#digg'})
			diggLink.appendTo(digg)
			digg.appendTo(list)
			
			var facebook = $(jQuery('<li />'))
			facebook.addClass('facebook')
			var facebookLink = $(jQuery('<a />'))
			facebookLink.click(function(c) {
				c.preventDefault()
				window.open('http://www.facebook.com/sharer.php?u='+page.url+'&t='+page.title,'sharer','toolbar=0,status=0,width=626,height=436');
			});
			facebookLink.html('Facebook')
			facebookLink.attr({'href': '#facebook'})
			facebookLink.appendTo(facebook)
			facebook.appendTo(list)
			
			var buzz = $(jQuery('<li />'))
			buzz.addClass('buzz')
			var buzzLink = $(jQuery('<a />'))
			buzzLink.click(function(c) {
				c.preventDefault()
				window.open('http://buzz.yahoo.com/submit/?submitUrl=' + escape('http://').replace(/\//gi, "%2F") + page.url + '&submitHeadline=' + page.title + '&submitSummary=' + page.description,'buzzer');
			});
			buzzLink.html('Y! Buzz')
			buzzLink.attr({'href': '#buzz'})
			buzzLink.appendTo(buzz)
			buzz.appendTo(list)
			
			list.appendTo(link)
			
			link.click(function(c) {
				c.preventDefault()
				list.toggle()
			});
		});
	}
	
	wt.equalStories = function() {
		var tallest = 0;
		var stories = $('div.other_story')
		stories.each(function() {
			tallest = $(this).height() > tallest ? $(this).height() :  tallest;
		});
		
		stories.each(function() {
			if($(this).height() < tallest) {
				$(this).find('h4').css({'padding-bottom': (parseInt($(this).find('h4').css('padding-bottom'),10) + (tallest - $(this).height())) + 'px'})
			}
		});
	}
})();