// JavaScript Document: Site-wide scripts

$(function () {
	
	var site = {

		mode: "full",
		header: $("#container > header"),
		logo: $("#container > header .logo img"),
		//logoMini: "home.png",
		logoMini: "bw-logo-small.png",
		logoFull: "bw-logo.png",
		
		init: function () {
			var self = this;

			// Get the height of the full header
			this.fullHeaderHeight = this.header.height();
			
			// Set the start mode
			if (this.header.hasClass("mini")) {
				this.mode = "mini";
			}

			// Only switch header if it's not an iOS device
			if (!this.isMobileSafari()) {

				// Switch header mode if the page is scrolled down
				this.scroll($(window).scrollTop());
				
				// Add event handler for the scroll to sense when the page is scrolled a certain amount
				$(window).bind("scroll", function (e) {
					self.scroll.call(self, $(window).scrollTop(), e);
				});
			}

			// Set up translations (mainly for twitter)
			this.setupTranslations();

			// Load latest tweet for the tweet section in the full header
			this.loadLatestTweet();

			// Fix hover effect for social buttons through JavaScript instead of CSS,
			//   because IE doesn't do it correctly when hovering iframes
			this.fixSocialHover();
		},

		isMobileSafari: function () {
			return (navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/));
		},

		scroll: function (distance, e) {

			// Change header mode when the page is scrolled down a certain amount
			if (distance > this.fullHeaderHeight + 10) {
				if (this.mode === "full") {
					this.switchHeader("mini");
				}
			} else if (this.mode === "mini") {
				this.switchHeader("full");
			}

			// If the distance is small enough, instantly switch to the full header
			if (distance < this.fullHeaderHeight / 1) {
				this.switchHeaderFast("full");
			}
		},

		switchHeader: function (mode) {
			var self = this;

			// Set flag
			this.mode = mode;

			// Set the class on the header to switch mode
			if (mode === "mini") {

				// Set start properties to hide it from view
				this.header.css({ opacity: 0, top: -40 });

				// Set class to switch design mode
				this.header.removeClass("full").addClass("mini");

				// Start animation that will show the header
				this.header.animate({ opacity: 1, top: 0 }, 200);

				// Replace the full header with empty space (won't be visible)
				$("body").css("padding-top", this.fullHeaderHeight);

				// Use the home icon as logo
				this.switchLogo();
			} else {

				// Start animation that will hide the header
				this.header.animate({ opacity: 0, top: -40 }, 200, function () {

					// Set class to switch design mode
					$(this).removeClass("mini").addClass("full");

					// Reset properties for the full header
					$(this).css({ opacity: 1, top: 0 });

					// Remove the added space
					$("body").css("padding-top", 0);

					// Use the normal logo
					self.switchLogo();
				});
			}
		},

		switchHeaderFast: function (mode) {
			
			// Stop all running animations and trigger the callback functions
			this.header.stop(true, true);
		},

		switchLogo: function () {
			var image = (this.mode === "mini") ? this.logoMini : this.logoFull;
			this.logo.attr("src", "images/site/main/" + image);
		},

		loadLatestTweet: function () {
			var self = this;
			
			// Set reference to the twitter callback
			window.twitterCallback = function (tweets) {
				self.injectLatestTweet.call(self, tweets)
			};
			$.getScript("http://twitter.com/statuses/user_timeline/bombayworks.json?callback=twitterCallback&amp;count=15");
		},

		injectLatestTweet: function (tweets) {
			var i, tweet, tweetText, timestamp, realtiveTime;

			// Many tweets are fetched and then filtered
			for (i = 0; i < tweets.length; i++) {
				tweet = tweets[i];

				// Only show tweet if it is a normal tweet and not a reply
				if (tweet.in_reply_to_user_id === null) {

					// Replace links with acutal HTML links
					tweetText = tweet.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function (url) {
						return '<a href="'+url+'" target="_blank">'+url+'</a>';
					});

					// Replace usernames with links
					tweetText = tweetText.replace(/\B@([_a-z0-9]+)/ig, function (reply) {
						return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '" target="_blank">' + reply.substring(1) + '</a>';
					});

					// Replace hash tags with links
					tweetText = tweetText.replace(/\B#(.*?)(\s|$)/ig, function (hash) {
						hash = hash.replace(/(\s|#)/ig, "");
						return '<a href="http://twitter.com/search/%23' + hash + '" class="hash" target="_blank">#' + hash + '</a> ';
					});

					// Get time
					timestamp = this.getTimestamp(tweet.created_at);
					relativeTime = '<a href="http://twitter.com/' + tweet.user.screen_name + '/status/' + tweet.id_str + '" target="_blank">' + this.getRelativeTime(tweet.created_at) + '</a>';
					
					// Break out of the loop when a normal tweet is found
					break;
				}
			}

			// Add the tweet to the DOM
			$(".social .latest-tweet .tweet").html(tweetText);
			$(".social .latest-tweet time").html(relativeTime).attr({ datetime: timestamp });

			if ($(".main .latest-tweet").length > 0) {
				$(".main .latest-tweet .tweet").html(tweetText);
				$(".main .latest-tweet time").html(relativeTime).attr({ datetime: timestamp });
			}
		},

		getTimestamp: function (time) {
			
			var values = time.split(" "),
				months = {Jan:'01',Feb:'02',Mar:'03',Apr:'04',May:'05',Jun:'06',Jul:'07',Aug:'08',Sep:'09',Oct:'10',Nov:'11',Dec:'12'},
				year = values[5],
				month = months[values[1]],
				day = values[2],
				time = values[3],
				timeoffset = values[4],
				timestamp = year+'-'+month+'-'+day+'T'+time+timeoffset;
				
			return timestamp;
		},

		getRelativeTime: function (time) {
			var self = this,
				relativeTime, values, parsedDate, relativeTo, delta,
				L = function (name) { return self.translate.call(self, name); };
			
			values = time.split(" ");
			time = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
			parsedDate = Date.parse(time);
			relativeTo = new Date();
			delta = parseInt((relativeTo.getTime() - parsedDate) / 1000);
			delta = delta + (relativeTo.getTimezoneOffset() * 60);

			if (delta < 60) {
				relativeTime = L("LessThanAMinute");
			} else if (delta < 120) {
				relativeTime = L("AboutAMinute");
			} else if (delta < (60*60)) {
				relativeTime = L("NumMinutes").replace("{{num}}", parseInt(delta / 60).toString());
			} else if (delta < (120*60)) {
				relativeTime = L("AboutAnHour");
			} else if (delta < (24*60*60)) {
				relativeTime = L("NumHours").replace("{{num}}", parseInt(delta / 3600).toString());
			} else if (delta < (48*60*60)) {
				relativeTime = L("OneDay");
			} else {
				relativeTime = L("NumDays").replace("{{num}}", parseInt(delta / 86400).toString());
			}
			
			return relativeTime;
		},

		translate: function (name) {
			var lang = this.lang;
			return (this.translations[lang] && this.translations[lang][name]) ? this.translations[lang][name] : "";
		},

		setupTranslations: function () {

			var translations = {

				"sv_SE": {
					LessThanAMinute: "mindre än en minut sedan",
					AboutAMinute: "runt en minut sedan",
					NumMinutes: "{{num}} minuter sedan",
					AboutAnHour: "runt en timme sedan",
					NumHours: "runt {{num}} timmar sedan",
					OneDay: "1 dag sedan",
					NumDays: "{{num}} dagar sedan"
				},
				"en_US": {
					LessThanAMinute: "less than a minute ago",
					AboutAMinute: "about a minute ago",
					NumMinutes: "{{num}} minutes ago",
					AboutAnHour: "about an hour ago",
					NumHours: "about {{num}} hours ago",
					OneDay: "1 day ago",
					NumDays: "{{num}} days ago"
				}
			};

			this.translations = translations;
			this.lang = $("body").data("lang");
		},

		fixSocialHover: function () {
			var self = this;

			// Hide tooltips on load
			//   This is done in JS since IE put a white background on the iframes if it was added in CSS
			$("header .social li").addClass("no-hover");
			
			// Fix hover for the buttons
			$("header .social li").bind("mouseenter", function () {
				$(this).removeClass("no-hover").addClass("hover");
			}).bind("mouseleave", function () {
				$(this).removeClass("hover").addClass("no-hover");
			});

			// Fix hover for the header, mainly for IE
			$("#container > header > div").bind("mouseenter", function () {
				$(this).addClass("hover");
				$(this).parent().addClass("hover");
			}).bind("mouseleave", function () {
				$(this).removeClass("hover");
				$(this).parent().removeClass("hover");
			});
		}
	};

	site.init();
	
});
