/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-14 23:57:10 -0600 (Fri, 14 Dec 2007) $
 * $Rev: 4163 $
 *
 * Version: @VERSION
 * 
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
	
		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};
		
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);

// 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($(".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
        	  var num_tweets = $("body.homepage").length > 0 ? 4 : 3;
          	for(i=0; i<num_tweets; 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"});
    });
  
    if($("body.schedule").length>0)
    {
      $(".slots").draggable({
        axis: "x",
        grid: [60,60],
        stop: function(event, ui)
        {
          // if(parseInt(ui.helper.css("left")) > 0)
          // {
          //   ui.helper.draggable("option", "revert", true)
          // }
          // else
          // {
          //   ui.helper.draggable("option", "revert", false)
          // }
        }
      });
    }
  
  if($(".tabs").length)
  {
    $(".tabs").tabs();
  }
  
  if($("body.homepage").length > 0)
  {
    flickr_feed = "http://api.flickr.com/services/feeds/photos_public.gne?id=54142074@N05&lang=en-us&format=json&jsoncallback=?"
    
    $.getJSON(flickr_feed,
        function(data)
        {
          if(data.items.length > 0)
          {
            for(i=0; i<8; i++)
            {
              var image = $("<img/>").attr({
                "alt": data.items[i].title,
                "src": data.items[i].media.m.replace("_m", "_s"),
              })
              
              $(".gallery").append($("<a/>").attr({
                "href": data.items[i].link
              }).append(image))
            }
          }
        })
  }
});
