window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
      arguments.callee = arguments.callee.caller;
      console.log( Array.prototype.slice.call(arguments) );
  }
};

var cd = {
	init: function() {
		$('input[type="text"], input[type="email"], input[type="password"], textarea').cd_formlabel();
		
		if($('body').hasClass('HomePage')) cd.HomePage.init();
		else if($('body').hasClass('PortfolioPage')) cd.PortfolioPage.init();
		else if($('body').hasClass('NewsPage')) cd.NewsPage.init();
		else if($('body').hasClass('AwardsPage')) cd.AwardsPage.init();
	}, //init
	HomePage: {
		init: function() {
			this.slideshow.init();
		}, //init
		slideshow: {
			_running: false,
			_timer: null,
			_current: 0,
			_autoscroll_speed: 4500,
			_fadespeed: 700,
			container: null,
			items: null,
			init: function() {
				this.container = $('#photos');
				this.items = this.container.children('img');
				
				this.setup_autoscroll(2500);
			}, //init
			slide_to_index: function(slide) {
				var self = this;
				this._running = true;
				this._current = slide;
				
				clearTimeout(this._timer);
				
				var pending = this.items.eq(slide);
				pending.addClass("pending");
				
				this.items.filter('.current').fadeOut(this._fadespeed, function() {
					$(this).removeClass('current').attr("style", "");
					pending.removeClass('pending').addClass('current');
					self.setup_autoscroll();
				});
			}, //slide_to_index
			setup_autoscroll: function(speed) {
				if(typeof speed == 'undefined') speed=this._autoscroll_speed;
				this._timer = setTimeout(this.next, speed);
			}, // setup_autoscroll
			next: function() {
				var self = cd.HomePage.slideshow;
				var next = self._current+1;
				if(next >= self.items.length) next = 0;
				self.slide_to_index(next);
			} //next
		} //slideshow
	}, //HomePage
	PortfolioPage: {
		init: function() {
			this.setup_nav();			
		}, //init
		setup_nav: function() {
			var self = this;
			if($('#pagination .next').length) {
				$('#content #photo img').css("cursor", "pointer").click(function() {
					$('#pagination .next').click();
					return false;
				});
			} else if($('#pagination a.video').length) {
				$('#content #photo img').css("cursor", "pointer").click(function() {
					$('#pagination .video').click();
					return false;
				});
			}
			$('#pagination a').click(function() {
				var clicked = this.href;
				$('#content').fadeOut(400).remove();
				$.ajax({
					url: clicked,
					success: function(data) {
						//window.log(data);
						var pending_content = $(innerShiv(data, false)).hide();
						pending_content.appendTo($('#main'));
						
						self.setup_nav();
						
						if(pending_content.find('img').length) {
							pending_content.find('img').load(function() {
							pending_content.fadeIn(600);
							});
						} else {
							// for video 
							pending_content.fadeIn(600);
						}
					}
				});
				return false;
			});
		} //setup_nav
	}, //PortfolioPage
	NewsPage: {
		init: function() {
			$('<div id="photos"><div id="loading" style="display:none;" /></div>').insertAfter($('#articles'));
			$('.article-photos a')
				.click(function() { return false; })
				.hover(function() {
					$('#photos img, #photos iframe').remove();
					$('#loading').show();
					$('<img src="'+this.href+'" />')
						.hide()
						.appendTo($('#photos'))
						.load(function() {
							$('#loading').hide();
							$(this).show();
						});
				}, function() {
					$('#loading').hide();
					$('#photos img').remove();
				});
			$('.article-video a').click(function() {
				var video_id = this.href.split("vimeo.com/");
				if(video_id.length < 1) return;

				video_id = video_id[1];
				$('#photos img').remove();
				$('#photos').append("<iframe src=\"http://player.vimeo.com/video/"+video_id+"?title=0&amp;byline=0&amp;portrait=0&amp;color=5B9B98\" width=\"400\" height=\"295\" frameborder=\"0\"></iframe>");

				return false;
			});
		} //init
	}, //NewsPage
	AwardsPage: {
		awards_loading: {},
		displaying_id: 0,
		init: function() {
			if($('#award').length < 1) {
				$('<div id="award" />').appendTo($("#content"));
			}
			$('<div id="loading" style="display:none;" />').appendTo($('#award'));
			
			//cached ajax awards
			$('<div id="awards" />').hide().appendTo($("#content"));
			
			this.setup_nav();
		}, //init
		setup_nav: function() {
			var self = this;
			$('#content > nav a')
				.click(function() {
					$('#content > nav a.current').attr("class", "link");
					self.show_loading();
					self.displaying_id = this.id;

					$award = $('#awards #'+this.id+'_slide');
					if($award.length) {
						$('#loading').hide();
						$('#award').append($award.clone().show());
					} else {
						//console.log(self.awards_loading);
						// don't run if request has already been made
						if(typeof(eval("self.awards_loading."+this.id)) == "undefined") {
							var request = $.ajax({
								url: this.href,
								success: function(data) {
									$('#awards').append(innerShiv(data, false));
									$('#loading').hide();
									if($(innerShiv(data, false)).attr("id") == self.displaying_id+"_slide") {
										$('#award').append(innerShiv(data, false));
									}
								}
							});
							self.awards_loading[this.id] = request;
						}
						//self.awards_loading.push(request);
					}
					return false;
				});
		}, //setup_nav
		show_loading: function() {
			this.hide_award();
			$('#loading').show();
		}, //show_loading
		hide_award: function() {
			$('#award').children(':not(#loading)').remove();
		}
	} //AwardsPage
};

(function($){
	
    // Creating custom :external selector
    $.expr[':'].external = function(obj){
        return !obj.href.match(/^mailto\:/)
                && (obj.hostname != location.hostname);
    };
    $('a:external').attr('target', '_blank').addClass("external");

	jQuery.support.cors = true;
	(function() {
	    if ( jQuery.ajaxPrefilter ) {
	        
	        var rURL = /^([^\/]+)/,
	            rEsc = /(\-|\.)/,
	            protocol = rURL.exec( document.location.href )[ 1 ].replace( rEsc, "\\$1" ),
	            rDomains = {};
	        
	        jQuery.ajaxPrefilter(function( options ) {
	            var strip = options.stripDomain,
	                rDomain,
	                sDomain;
	            if( strip ) {
	                rDomain = rDomains[ strip ];
	                if ( !rDomain ) {
	                    sDomain = "^(?:" + protocol + ")?\\/\\/" + strip.replace( rEsc, "\\$1" );
	                    rDomains[ strip ] = rDomain = new RegExp( sDomain, "i" )
	                }
	                options.url = options.url.replace( rDomain, "" );
	            }
	        });
	    }
	
	})( jQuery );
	
	// In your app, after you loaded jQuery and the plugin
	jQuery.ajaxSetup({
	    stripDomain: "www.andysturgeon.com"
	});
	cd.init();
    
})(jQuery);
