var Campaign = (function() {
	return {
		/**
		 *	Initialize
		 */
		init: function() {
			Berghs.addAnchors.init([
				{ element: ".vevent", include: [".dtstart"], add: false }
			]);
			Campaign.twitterList.init([
				{ element: ".twitter-ticker", amount: 10, includeHashTag: "arbetsprov2012" }
			]);
			Berghs.video.init();
			$(".responsive-blog-list-expand").live("click", function(e) {
			   e.preventDefault();
			   $(this).remove();
			   $(".blog").css("max-height", "none");
			})
		}
	};
}());

Campaign.twitterList = (function() {
	var options;
	var tweets;
	
	//Parse Twitter created_at value into friendly time format; relative time; time ago
	var H = function (a) {
	    var b = new Date();
	    var c = new Date(a);
	    if ($.browser.ie) {
			c = Date.parse(a.replace(/( \+)/, ' UTC$1'));
	    }
	    var d = b - c;
	    var e = 1000,
	        minute = e * 60,
	        hour = minute * 60,
	        day = hour * 24,
	        week = day * 7;
	    if (isNaN(d) || d < 0) {
	        return "";
	    }
	    if (d < e * 7) {
	        return "right now";
	    }
	    if (d < minute) {
	        return Math.floor(d / e) + " seconds ago";
	    }
	    if (d < minute * 2) {
	        return "about 1 minute ago";
	    }
	    if (d < hour) {
	        return Math.floor(d / minute) + " minutes ago";
	    }
	    if (d < hour * 2) {
	        return "about 1 hour ago";
	    }
	    if (d < day) {
	        return Math.floor(d / hour) + " hours ago";
	    }
	    if (d > day && d < day * 2) {
	        return "yesterday";
	    }
	    if (d < day * 365) {
	        return Math.floor(d / day) + " days ago";
	    } else {
	        return "over a year ago";
	    }
	};
	
	var DOMReady = function() {
		for (i = 0, ln = options.length; i < ln; i++) {
			$(options[i].element).each(function() {
				var $self = $(this);
				var currentOptions = options[i];
				var url = $self.find("a")[0].href;
				var userName = url.substr(url.lastIndexOf(".com/") + ".com/".length);
				//var q = "http://twitter.com/status/user_timeline/" + userName + ".json?trim_user=true&include_rts=true&callback=?";
				if (currentOptions.includeHashTag) {
  	     			//var q = "http://search.twitter.com/search.json?q=%23" + currentOptions.includeHashTag + "%20OR%20from%3A" + userName + "&rpp=" + (currentOptions.amount + 10) + "&callback=?";
      				var q = "http://search.twitter.com/search.json?q=%23" + currentOptions.includeHashTag + "&rpp=" + (currentOptions.amount + 10) + "&callback=?";
				} else {
   		       		var q = "http://search.twitter.com/search.json?q=from%3A" + userName + "&rpp=" + (currentOptions.amount + 10) + "&callback=?";
				}
				$.getJSON(q, function(data) {
					var html = "";
					var j = 0;
					var n = 0;
					var results = data.results;
					if (results.length > 0) {
						html += "<div class=\"tweetwrapper\"><ul>";
						for (j = 0, l = results.length; j < l; j++) {
							if (!results[j].in_reply_to_status_id_str) {
								results[j].text = results[j].text.replace(/(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))/i, function(url) {
									return " <a href=\"" + url + "\">" + (url.length > 30 ? url.substr(0, 30) + "..." : url) + "</a>";
								});
								html += "<li>";
  							if (currentOptions.includeHashTag) {
  								var twuser = results[j].from_user;
  								var twuserName = twuser;
  						    if (results[j].from_user_name != "") {
    								twuserName = results[j].from_user_name;
  						    }
   								html += "<a href=\"http://twitter.com/#!/" + twuser + "\">" + twuserName + "</a>: ";
  							}
								html += results[j].text;
								html += " <span class=\"source\">" + H(results[j].created_at) + "</span>";
								html += "</li>";
								n++;
							}
							if (n == currentOptions.amount) {
						      break;
							}
						}
					}
					html += "</ul></div>";
					if(j > 0) {
						$self.append(html);
						var $elms = $self.find("li");
						var $list = $self.find("ul");
						var $wrapper = $self.find(".tweetwrapper");
						var totalLength = 0;
						var wrapperWidth = $wrapper.outerWidth();
						$elms.each(function() {
						  totalLength += $(this).outerWidth();
						});
						$list.css({
						  padding: "0px " + wrapperWidth + "px",
						  width: totalLength + "px"
						});
						cycle($list, totalLength + wrapperWidth*2);
						$self.find(".tweetwrapper").live("mouseenter", function() {
						  $list.stop();
						});
						$self.find(".tweetwrapper").live("mouseleave", function() {
						  cycle($list, totalLength + wrapperWidth*2);
						});
					} else {
					   $(".twitter-ticker").remove();
					}		
				});
			});
		}
	};
	var cycle = function($elm, length) {
    var currentOffset = parseInt($elm.css("marginLeft")) + length;
    $elm.animate({
      marginLeft: "-" + length + "px"
    }, currentOffset*15, "linear", function() {
      $elm.css({
        marginLeft: "0px"
      });
      cycle($elm, length);
    });
	};
	return {
		init: function(initOptions) {
			options = initOptions;
			$(document).ready(DOMReady);
		}	
	};
}());

Berghs.video = (function() {
  var $overlay;
	var DOMReady = function() {
    $(".media-trigger").find("a, img, span").click(function(e) {
      e.preventDefault();
      var html = [];
      var mediaUrl = $(this).closest(".media-trigger").attr("data-media-src");
      html.push('<div class="media-content media-content-popover"><div class="video-and-slide">');
      html.push('<iframe frameBorder="0" src="' + mediaUrl + '" scrolling="no" style="overflow-x: 0px; overflow-y: 0px; width:900px; height:565px; background: #000;"></iframe>');
      html.push('<a href="#" class="close button">Stäng</a>');
      html.push('</div></div>');
      $overlay = $(html.join(""));
      cover.show();
      $("body").append($overlay);
      $overlay.fadeIn();
      $(".media-content a.close").bind("click", function(e) {
        e.preventDefault();
        cover.hide();
        $(".media-content a.close").unbind();
        $overlay.remove();
      });
    });
	};
	return {
		init: function() {
			$(document).ready(DOMReady);
		}
	};
}());

/** @class
 * Creates a semi transparent cover over the screen.
 */
var cover = function() {
	var setSize = function() {
    var el = $("#ui-cover");
    var height = Math.max($("body").outerHeight(), $(window).height());
    el.css({
        "height": height + "px",
        "display": "block"
    });
  };
  return {
		/**
		 * Shows the cover.
		 */
    show: function(callback) {
      var el = $("#ui-cover");
      if (!el[0]) {
        el = $("<div id=\"ui-cover\"></div>");
        $("body").append(el);
        el.css({
          "position": "absolute",
          "left": "0px",
          "top": "0px",
          "width": "100%",
          "zIndex": "999",
          "background": "black",
          "opacity": "0"
        });
      }
      if (callback) { el.animate({"opacity": 0.7}, "normal", "swing", callback); } 
      else { el.animate({"opacity": 0.7}, "normal"); }
      $(window).bind("resize.cover", setSize);
      $(window).trigger("resize.cover");
    },
		/**
		 * Hides the cover.
		 */
    hide: function() {
      var el = $("#ui-cover");
      if (el.length > 0) {
        el.animate({"opacity": 0}, 600, "swing", function() { el.css("display", "none"); });
	      $(window).unbind("resize.cover");
      }
    }
  };
}();



Campaign.init();
