// Object.prototype.beget = function () { // thanks Crockford
//     function F() {};
//     F.prototype = this;
//     return new F();
// };

$(function(){
  // Select just Firefox 3.1 and below
  if ($.browser.mozilla && jQuery.browser.version <= '1.9.1')
  {
    $("html").addClass("no-fontface");
  }
  
  if($(".tabs").length)
  {
    $(".tabs").tabs();
  }
  
  if($(".accordion").length)
  {
    $(".accordion").accordion({
      "autoHeight": false,
      "active": false,
      "collapsible": false,
      "animated": false
    });
  }
    
  if($("select").length)
  {
    var width = $("select", this).outerWidth();
    $("select").selectmenu({
      style:"dropdown",
      maxHeight: 170,
      width: width,
      handleWidth: 56
    });
  }

  $("input[type='text'], select, textarea").hover(function(){
    $(this).prev("label").css({"color": "#FFF"});
  }, function(){
    $(this).prev("label").css({"color": "#C8C6C7"});
  });
	/*******************************************************
	 Populate delegate order form when promo code is entered 
	*******************************************************/
	
  delegate_colours = {
    "DEL": {"color": "red", "name": "Delegate"},
    "ART": {"color": "green",  "name": "Artist"},
    "PRS": {"color": "#5F8AFF",  "name": "Press"},
    "SDT": {"color": "#FF4F98",  "name": "Student"},
    "PNL": {"color": "orange",  "name": "Panelist"}
	}
	
	// Only execute if we have 'promocode' fields available
	var $code_input = $("input[id$='-code']");
	if($code_input.length)
	{
	  $($code_input).live("keyup", function(){
	    // Find which formset this input belongs to
	    // 0-indexed
	    var re = new RegExp(/\d+/);
	    formset_index = re.exec(this.id);

	    if($(this).attr("value").length > 5)
	    {
  	    $.getJSON("/register/json/promocode/", {"code": $(this).attr("value")}, function(response){
          if(response.code)
          {
            var $this_code_input = $("input#id_form-"+formset_index+"-code");
            var code_exists = false;
            $code_input.not($this_code_input).each(function(i){
              if($(this).attr("value") == response.code.code) code_exists = true;
            });
            
            if (!code_exists)
            {
              // Change background color to colour associated with pass type
              $this_code_input.parents("div.promo").css({"background": delegate_colours[response.code.ticket_type]["color"]});
              // Populate form
              $.each(response.user, function(key, value){
                $("input#id_form-"+formset_index+"-"+key).attr("value", value);
              });
              $this_code_input.parents("div.register_lozenge").find("h3.ticket_meta").html(delegate_colours[response.code.ticket_type]["name"]+" Ticket : &pound;"+response.code.price);
            }
          }
  	    });
      }
	  });
	}
	/*** EOF Populate delegate order form when promo code is entered ***/
	
	/* BOF Class TwitterFeed */
	function TwitterFeed()
	{
  	// Store all tweets in array
    this.tweets = new Array();
  	this.tweet_pointer = 0;
  	this.page = 1;
  	
  	this.init = function(keyword, refresh_rate)
  	{
  	  /* Whether to add the first 3 tweets or not */
  	  this.add = true;
  	  this.keyword = keyword;
  	  this.get_tweets();
  	  
  	  var instance = this;
  	  setInterval(function(){instance.slide()}, refresh_rate*1000);
      return this;
  	}
  	
  	this.get_tweets = function()
  	{
    	var url = "http://search.twitter.com/search.json?q=%23"+this.keyword+"&page="+this.page+"&callback=?";
      instance = this;
    	$.getJSON(url, function(data)
    	{
    	  if(data.results[0])
    	  {
      	  $.each(data.results, function(i, item)
      	  {
      	    instance.tweets.push(item);
      	  });
	      
  	      if(instance.add)
  	      {
  	        $("#twitter_tweets #loader").remove();
        	  // Populate twitter feed
          	for(i=0; i<3; i++)
          	{
          	  instance.add_tweet(instance.tweets[i]);
          	  instance.tweet_pointer++;
          	}
          }
        }
        else
        {
          instance.tweet_pointer = 0;
        }
    	});
    	
      return instance;
    }
    
    this.slide = function()
    {
      if(this.tweet_pointer < this.tweets.length-1)
      {
        instance = this;
        $("div#twitter_tweets div:first-child").fadeOut("slow", function(){
          $("div#twitter_tweets div:first-child").remove();
          instance.tweet_pointer++;
          instance.add_tweet();
          return instance;
        });
      }
      else
      {
        this.add = false;
        this.get_tweets(this);
      }
      return this;
    };

    this.add_tweet = function()
    {
      this.tweet = this.tweets[this.tweet_pointer];
      var $tweet_div = $("<div/>").attr({"id": this.tweet.id}).css({"display": "none"});
      $tweet_div.append($("<img/>").attr({"src": this.tweet.profile_image_url, "alt": this.tweet.from_user}));
      $tweet_div.append($("<p>").html(this.tweet.text.replace(/@(\w*)/, "<a href=\"http://www.twitter.com/$1\">@$1</a>")));
      $tweet_div.append($("<p>").html("Posted " + this.time_since(this.tweet.created_at) + " by " + this.tweet.from_user).attr({"class": "since"})).fadeIn("slow");
      //  + " via " + tweet.source.replace(/<a\b[^>]*>(.*?)<\/a>/i,"$1")
      $("div#twitter_tweets").append($tweet_div);
    }
 
    this.time_since = function(a)
    {
        var b = new Date();
        var c = new Date(a);
        if (navigator.userAgent.match(/MSIE\s([^;]*)/)) {
            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"
        }
    };
  }
  /* EOF Class TwitterFeed */
  
  // Initiate twitter class!
  new TwitterFeed().init("inthecity", 6);
  
  // Nice bubble for help text alt
  $("a.help_text").hover(function(e){
    e.preventDefault();
    var div = $("<div/>").text($(this).attr("title"));
    $(this).append(div);
    div.fadeIn();
  }, function(){
    $("div", this).remove();
  });
  
  // Front page bubble animation
  var earlybird = $("#earlybird");
  $("a#full_price_ticket").hover(function(){
    earlybird.css({"background-position": "0 -353.5px"});
  }, function(){
    earlybird.css({"background-position": "0 -0"});
  });
  
  $("a#wristband").hover(function(){
    earlybird.css({"background-position": "0 -707px"});
  }, function(){
    earlybird.css({"background-position": "0 -0"});
  });
});
