$(document).ready(function(){
	global.init()
	newsletter.init();
	pagination.init();
	twitter.init();
	photo_nav.init();
});


// !GLOBAL
var global = {};

global.init = function() {
	if ($.browser.safari) {
		$('body').addClass('webkit');
		global.browser = "webkit";
	}
	
	// FIXME: Have to sniff for Chrome (I know), but it returns true when checking for backfaceVisibility, but doesn't actually support it
	// Naughty Chrome!
	global.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
	
	global.backface = getStyleProperty('backfaceVisibility');
	
	if (!global.chrome && global.backface) {
		$('body').addClass('backfaceVisibility');
	}
	
	// Add transition class to body if they're supported
	global.transitions = getStyleProperty('transition');
	if (global.transitions) { $('body').addClass('transitions'); }
	
	$(".news .post img, .photography .post").before($("<div>").attr('class', 'img_overlay'));
	
	// Check if border image CSS property is supported.
	if (typeof getStyleProperty('borderImage') == 'string') {
		$('.design').addClass('border-image');
	}
};


// !Twitter
var twitter = {};
twitter.data = Array();

twitter.init = function() {	
	// Get twitter reactions for this post
	var canonical = document.getElementById('canonical');
	var url = canonical ? canonical.href : location.href;
	//<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="realmacsoftware" data-related="dancounsell:The Big Cheif at Realmac Software.">Tweet</a>
	$("a.twitter-share-button").attr({
		'data-url' : url,
		'data-text' : document.title
	}).text("Tweet");
};


// !NEWSLETTER
var newsletter = {};

newsletter.init = function() {
	var top_wrapper = $("#newsletter-wrapper");
	var wrapper = $("#newsletter");
	var form = wrapper.find("form");
	var button = wrapper.find("button");
	var inputs = form.find('li input');
	var required_inputs = form.find('input[required]');
	
	// Create close button
	$("<div>").attr('class', 'close').appendTo("form");
	var button_close = form.find(".close");
	
	// Create back side.
	$("<section>").attr('class', 'back').html('<h1>You\'re Signed Up!</h1><p>Thanks for signing up. We\'ll be sending you a confirmation email shortly.</p><div class="button close">Close</div>').appendTo(wrapper);
	var back = wrapper.find('.back');
	var button_finished = back.find(".close");
	
	// Hide newsletter in all browsers
	if (global.browser != "webkit") {
		wrapper.css({"opacity": '0', 'z-index':0});
	}
	
	// click on news navigation link
	$("li.news a").click(function(e) {
		// check if newsletter is currently shown or not
		if (wrapper.hasClass("show")) {
			// hide newsletter
			wrapper.removeClass("show");
			setTimeout(function() { top_wrapper.removeClass("show"); }, 300);
			
			if (!global.transitions) {
				hideNewsletter();
			}
		} else {
			// show newsletter
			top_wrapper.addClass("show");
			setTimeout(function() { wrapper.addClass("show"); }, 0);
			
			if (!global.transitions ) {
				wrapper.css('z-index', 100);
				wrapper.css("display","block").animate({ opacity : 1, top : 10 }, 200);
			}
		}
		e.preventDefault();
	});
	
	// Hide newsletter when close button clicked
	button_close.click(function() {
		wrapper.removeClass("show");
		setTimeout(function() { top_wrapper.removeClass("show"); }, 300);
		if (!global.transitions) {
			hideNewsletter()
		}
	});
	
	// Hide newsletter when finished button is clicked
	// Then reset the form to original state
	button_finished.click(function() {
		// Hide
		wrapper.removeClass("show");
		setTimeout(function() { top_wrapper.removeClass("show"); }, 300);
		if (!global.transitions || global.chrome) {
			hideNewsletter();
		}
		
		// Reset
		window.setTimeout(function() {
			wrapper.removeClass('sent');
			inputs.each(function() {
				$(this).attr('value', $(this).attr('placeholder')).removeClass('valid');
			});
			if (!global.transitions || global.chrome) {
				form.css('z-index', 2);
				button_close.show();
				back.css({'z-index' : 1, 'opacity' : 0});
			}
		}, 800)
	});
	
	var hideNewsletter = function() {
		wrapper.animate({ opacity : 0, top : -10 }, 200, function() {
			wrapper.css({"display": 'none', 'z-index':0});
		});
	}
	
	
	// Form Validation
	inputs.each(function() {
		var type = $(this).attr("name");
		switch(type) {
			case "email":
				$(this).bind({
					focus: function() {
						if ($(this).attr("value") == $(this).attr("placeholder"))
							$(this).attr("value", "");
					},
					blur: function() {
						checkEmail($(this).attr('value')) ? $(this).removeClass('invalid').addClass("valid") : $(this).removeClass('valid').addClass("invalid");
						if ($(this).attr('value') == "")
							$(this).attr("value", $(this).attr('placeholder'));
					},
					keyup: function() {
						//checkEmail($(this).attr('value')) ? $(this).removeClass('invalid').addClass("valid") : $(this).removeClass('valid').addClass("invalid");
					}
				});
				break;
			case "first":
			case "last":
				$(this).bind({
					focus: function() {
						if ($(this).attr("value") == $(this).attr("placeholder"))
							$(this).attr("value", "");
					},
					blur: function() {
						if ($(this).attr('value') == "")
							$(this).attr("value", $(this).attr('placeholder'));
					}
				});
				break;
		}
	});
	
	// Email validation
	function checkEmail(email) {
		var reg = /^([A-Za-z0-9_\-\.\+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test(email)) {
			return true;
		}
	}
	
	// Form submission
	form.submit(function(event) {
		event.preventDefault();
		required_inputs.each(function() {
			if (!$(this).hasClass('valid')) {
				$(this).focus();
				return false;
			}
		});
		
		inputs.each(function() {
			if ($(this).attr('value') == "First Name" || $(this).attr('value') == "Last Name") {
				$(this).attr('value', '');
			}
		});
		
		// If form field is valid, send form
		if ($("#newsletter .valid").length) {
			$.ajax({
				type: "post",
				data: $(this).serialize(),
				url: $(this).attr('action'),
				beforeSend: function() {
				},
				error: function(xhr) {
					var json    = $.parseJSON(xhr.responseText);
					var message = 'There has been an error, please try again.';
					if (json) {
						message = json.message;
					}
					wrapper.find('form p').text(message).addClass('error');
				},
				success: function(data){
					if (global.transitions && !global.chrome) {
						wrapper.addClass('sent');
					} else {
						form.css('z-index', 1);
						button_close.hide();
						back.css('z-index', 2).animate({ opacity : 1 }, 200);
					}
				}
			});
		}
		
		// Prevent form submission
		event.preventDefault();
	});
};

// !PAGINATION
var pagination = {};

pagination.init = function() {
	pagination.wrapper = $("#pagination");
	pagination.current = 1;
	pagination.total = 1;
	pagination.button = pagination.wrapper.find("li.next a");

	// Remove any previous page links
	pagination.wrapper.find("li:not(.next)").remove();
	
	if ($(pagination.button).length) {
		pagination.button.text("Load More Posts");
		pagination.button.parent().addClass("ajax");
	} else {
		pagination.wrapper.remove();
	}
	
	pagination.button.click(function(e) {
		pagination.next = pagination.current +1;
		$.ajax({
			url: $(this).attr("href") + '.json',
			dataType: "json",
			beforeSend: function() {
				pagination.button.html("Loading...")
			},
			success: function(request){
				// Set pagination vars
				pagination.next++;
				pagination.current = request.response.pagination.current;
				pagination.total = request.response.pagination.total;
				
				// Create HTML element for next page results
				div = $(innerShiv("<div>" + request.response.html + "</div>",false)).css('opacity', 0).attr("id", "page"+pagination.current);
				div.find(".news .post img").before($("<div>").attr('class', 'img_overlay'));
				// Insert new content
				$(pagination.wrapper).before(div);
				
				// Show new content
				$(div).animate({'opacity' : 1}, 1000);
				
				// Do we have any more pages to display?
				if (pagination.next < pagination.total) {
					pagination.button.html("Load More Posts").attr({"href" : "/blog/page/"+pagination.next});
				} else {
					pagination.wrapper.remove();
				}
				
				// Check if border image CSS property is supported.
				if (typeof getStyleProperty('borderImage') == 'string') {
					div.find('.design').addClass('border-image');
				}
			}
		});
		e.preventDefault();
	});
};

// !PHOTO ALBUM NAVIGATION
var photo_nav = {};

photo_nav.init = function() {
	// create the nav
	var photo_navigation = $('<nav>').attr('class', 'photo-nav').html("<ul></ul>").appendTo('.photography article');
	var photo_list = $(".photography article .post ul");
	
	photo_list.find('li').each(function(i, value) {
		// add id to li
		i++;
		$(this).attr('id', 'image-'+i);
		
		// create link and li for nav
		var link = $('<a>').attr('href', '#image-'+i);
		$("<li>").html(link).appendTo(photo_navigation.find("ul"));
		
		i++;
	});
	
	photo_navigation.find('li:first-child').addClass('current');
	var current = photo_navigation.find('.current');
	
	// Key press events
	$(document).keydown(function(e){
		if (event.target.nodeName != "INPUT" && event.target.nodeName != "TEXTAREA") {
			switch(e.keyCode) {
				case 37: //left arrow
					moveImages(photo_navigation.find('.current').prev().find('a'));
					break;
				case 39: //right arrow
					moveImages(photo_navigation.find('.current').next().find('a'));
					break
			}
		}
	});
	
	photo_navigation.find('a').each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			moveImages($(this))
		});
	});
	
	function moveImages(link) {
		var target = link.attr('href');
		
		// there is either a next / prev image
		if (target) {
			photo_navigation.find('.current').removeClass('current');
			link.parent().addClass('current');
			var target_pos = $(target).position();
			
			if ($('body').hasClass('transitions')) {
				photo_list.css('margin-left', '-'+target_pos.left+'px');
			} else {
				photo_list.animate({
					marginLeft: '-'+target_pos.left
				}, 500);
			}
		}
	}
};

// !CHECK CSS SUPPORT
var getStyleProperty = (function(){
 
  var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];
  var _cache = { };
 
  function getStyleProperty(propName, element) {
    element = element || document.documentElement;
    var style = element.style,
        prefixed,
        uPropName;
 
    // check cache only when no element is given
    if (arguments.length == 1 && typeof _cache[propName] == 'string') {
      return _cache[propName];
    }
    // test standard property first
    if (typeof style[propName] == 'string') {
      return (_cache[propName] = propName);
    }
 
    // capitalize
    uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
 
    // test vendor specific properties
    for (var i=0, l=prefixes.length; i<l; i++) {
      prefixed = prefixes[i] + uPropName;
      if (typeof style[prefixed] == 'string') {
        return (_cache[propName] = prefixed);
      }
    }
  }
 
  return getStyleProperty;
})();

 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-241775-21']);
 _gaq.push(['_trackPageview']);

 (function() {
   var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
   ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();
 
 // !INNERSHIV
 // http://jdbartlett.github.com/innershiv
window.innerShiv = (function() {
	var d, r;
	
	return function(h, u) {
		if (!d) {
			d = document.createElement('div');
			r = document.createDocumentFragment();
			/*@cc_on d.style.display = 'none';@*/
		}
		
		var e = d.cloneNode(true);
		/*@cc_on document.body.appendChild(e);@*/
		e.innerHTML = h;
		/*@cc_on document.body.removeChild(e);@*/
		
		if (u === false) return e.childNodes;
		
		var f = r.cloneNode(true), i = e.childNodes.length;
		while (i--) f.appendChild(e.firstChild);
		
		return f;
	}
}());