jQuery.extend({
  calendar_months: [
	  "Nil", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
	  "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	],
  isReady: false,
  readyList: [],
  // Handle when the DOM is ready
  ready: function() {
    // Make sure that the DOM is not already loaded
    if (!jQuery.isReady) {
      // Remember that the DOM is ready
      jQuery.isReady = true;
      // If there are functions bound, to execute
      if (jQuery.readyList) {
        // Execute all of them
        jQuery.each(jQuery.readyList, function(){
          this.call(document, jQuery);
        });
        // Reset the list of functions
        jQuery.readyList = null;
      }
      // Trigger any bound ready events
      jQuery(document).triggerHandler("ready");
      jQuery.processUpdates();
    }
  },
  updatesList: [],
  processUpdates: function() {
    if (jQuery.updatesList) {
      jQuery.each(jQuery.updatesList, function() {
        this.call(document, jQuery);
      });
    }
  }
});

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
  
  $.fn.found = function(myFunction) {
    if(this.length) {
      myFunction.call(this);
    }
  };
  $.fn.equalizeCols = function(offsets){
		var height = 0,
			reset = $.browser.msie ? "1%" : "auto";
  
		return this
			.css("height", reset)
			.each(function() {
			  height = Math.max(height, (this.offsetHeight + offsets[this.id]));
			})
			.css("height", height)
			.each(function() {
				var h = this.offsetHeight + offsets[this.id];
				if (h > height) {
					$(this).css("height", height - (h - height));
				};
			});	
	};
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};
	
  $.format = (function () {
    var parseMonth = function (value) {
      switch (value.toUpperCase()) {
        case "JAN":
          return "01";
        case "FEB":
          return "02";
        case "MAR":
          return "03";
        case "APR":
          return "04";
        case "MAY":
          return "05";
        case "JUN":
          return "06";
        case "JUL":
          return "07";
        case "AUG":
          return "08";
        case "SEP":
          return "09";
        case "OCT":
          return "10";
        case "NOV":
          return "11";
        case "DEC":
          return "12";
        default:
          return value;
      }
    };
	    
    var getMonthShortName = function(value) {
      return $.calendar_months[parseInt(value, 10)];
    };
    
    var getMonthName = function(value) {
      return $.calendar_months[parseInt(value, 10) + 12];
    }
    
    var parseTime = function (value) {
      var retValue = value;
      if (retValue.indexOf(".") !== -1) {
        retValue = retValue.substring(0, retValue.indexOf("."));
      }
      var values3 = retValue.split(":");
      if (values3.length === 3) {
        hour = values3[0];
        minute = values3[1];
        second = values3[2];
        return {
          time: retValue,
          hour: hour,
          minute: minute,
          second: second
        };
      } else {
        return {
          time: "",
          hour: "",
          minute: "",
          second: ""
        };
      }
    };

    return {
      date: function (value, format) {
        //value = new java.util.Date()
        //2009-12-18 10:54:50.546
        try {
          var year = null;
          var month = null;
          var dayOfMonth = null;
          var time = null; //json, time, hour, minute, second
          if (typeof value.getFullYear === "function") {
            year = value.getFullYear();
            month = value.getMonth() + 1;
            dayOfMonth = value.getDate();
            time = parseTime(value.toTimeString());
          } else {
            var values = value.split(" ");
            switch (values.length) {
              case 6://Wed Jan 13 10:43:41 CET 2010
                year = values[5];
                month = parseMonth(values[1]);
                dayOfMonth = values[2];
                time = parseTime(values[3]);
                break;
              case 2://2009-12-18 10:54:50.546
                var values2 = values[0].split("-");
                year = values2[0];
                month = values2[1];
                dayOfMonth = values2[2];
                time = parseTime(values[1]);
                break;
              default:
                return value;
            }
          }
          var pattern = "";
          var retValue = "";
          for (i = 0; i < format.length; i++) {
            var currentPattern = format.charAt(i);
            pattern += currentPattern;
            switch (pattern) {
              case "dd":
                retValue += dayOfMonth;
                pattern = "";
                break;
              case "LM":
                retValue += getMonthName(month)
                pattern = "";
                break;
              case "SM":
                retValue += getMonthShortName(month)
                pattern = "";
                break;
              case "MM":
                retValue += month;
                pattern = "";
                break;
              case "yyyy":
                retValue += year;
                pattern = "";
                break;
              case "HH":
                retValue += time.hour;
                pattern = "";
                break;
              case "hh":
                retValue += (time.hour === 0 ? 12 : time.hour < 13 ? time.hour : time.hour - 12);
                pattern = "";
                break;
              case "mm":
                retValue += time.minute;
                pattern = "";
                break;
              case "ss":
                retValue += time.second;
                pattern = "";
                break;
              case "aa":
                retValue += time.hour > 12 ? "PM" : "AM";
                pattern = "";
                break;
              case " ":
                retValue += currentPattern;
                pattern = "";
                break;
              case "/":
                retValue += currentPattern;
                pattern = "";
                break;
              case ":":
                retValue += currentPattern;
                pattern = "";
                break;
              default:
                if (pattern.length === 2 && pattern.indexOf("y") !== 0) {
                  retValue += pattern.substring(0, 1);
                  pattern = pattern.substring(1, 2);
                } else if ((pattern.length === 3 && pattern.indexOf("yyy") === -1)) {
                  pattern = "";
                }
            }
          }
          return retValue;
        } catch (e) {
          console.log(e);
          return value;
        }
      }
    };
  }());
})(jQuery); 


jQuery.notifyBar = function(settings) {
  
  (function($) {
    
    var bar = notifyBarNS = {};
    notifyBarNS.shown = false;
     
    if( !settings) {
    settings = {};
    }
    // HTML inside bar
    notifyBarNS.html = settings.html || "Your message here";
     
    //How long bar will be delayed, doesn't count animation time.
    notifyBarNS.delay = settings.delay || 2000;
     
    //How long notifyBarNS bar will be slided up and down
    notifyBarNS.animationSpeed = settings.animationSpeed || 200;
     
    //Use own jquery object usually DIV, or use default
    notifyBarNS.jqObject = settings.jqObject;
     
    //Set up own class
    notifyBarNS.cls = settings.cls || "";
    
    //close button
    notifyBarNS.close = settings.close || false;
    
    if( notifyBarNS.jqObject) {
      bar = notifyBarNS.jqObject;
      notifyBarNS.html = bar.html();
    } else {
      bar = jQuery("<div></div>")
      .addClass("jquery-notify-bar")
      .addClass(notifyBarNS.cls)
      .attr("id", "__notifyBar");
    }
         
    bar.html(notifyBarNS.html).hide();
    var id = bar.attr("id");
    switch (notifyBarNS.animationSpeed) {
      case "slow":
      asTime = 600;
      break;
      case "normal":
      asTime = 400;
      break;
      case "fast":
      asTime = 200;
      break;
      default:
      asTime = notifyBarNS.animationSpeed;
    }
    if( bar != 'object'); {
      jQuery("body").prepend(bar);
    }
    
    // Style close button in CSS file
    if( notifyBarNS.close) {
      bar.append(jQuery("<a href='#' class='notify-bar-close'>Close [X]</a>"));
      jQuery(".notify-bar-close").click(function() {
        if( bar.attr("id") == "__notifyBar") {
          jQuery("#" + id).slideUp(asTime, function() { jQuery("#" + id).remove() });
        } else {
          jQuery("#" + id).slideUp(asTime);
        }
        return false;
      });
    }
    
    bar.slideDown(asTime);
     
    // If taken from DOM dot not remove just hide
    if( bar.attr("id") == "__notifyBar") {
      setTimeout("jQuery('#" + id + "').slideUp(" + asTime +", function() {jQuery('#" + id + "').remove()});", notifyBarNS.delay + asTime);
    } else {
      setTimeout("jQuery('#" + id + "').slideUp(" + asTime +", function() {jQuery('#" + id + "')});", notifyBarNS.delay + asTime);
    }

})(jQuery) };

function twitter_link_replacer(str, p1, p2, offset, s) {
  return '<a href="' + str + '" target="_blank">' + str + '</a>'
}

function twitter_username_link_replacer(str, p1, p2, offset, s) {
  return '@<a onclick="javascript:pageTracker(\'/outgoing/twitter.com/' + p2 + '\');" href="http://twitter.com/' + p2 + '" target="_blank">' + p2 + '</a>'
}

function twitter_hashtag_link_replacer(str, p1, p2, offset, s) {
  return '#<a onclick="javascript:pageTracker(\'/outgoing/search.twitter.com/search?q=%23\');" href="http://search.twitter.com/search?q=%23' + p2 + '" target="_blank">' + p2 + '</a>'
}

function format_tweets(target) {
  $("." + target).each(function() {
    ct = $(this).text();
    ct = ct.replace(/http:\/\/\S+/g, twitter_link_replacer);
    ct = ct.replace(/(@)(\w+)/g, twitter_username_link_replacer);
    $(this).html(ct);
  });
}

function get_twitter(username, count, target, callback) {
  $.getJSON("/feeds/twitter.json?username=" + username + "&count=" + count + "&callback=?", function(data) {
    var row = 'even';
    $.each(data, function(i,item) {
      date = $.format.date(item.date_posted, "SM dd, yyyy hh:mmaa")
      ct = item.text;
      ct = ct.replace(/http:\/\/\S+/g, twitter_link_replacer);
      ct = ct.replace(/(@)(\w+)/g, twitter_username_link_replacer);
      //ct = ct.replace(/\s(#)(\w+)/g, twitter_hashtag_link_replacer);
      $(target).append('<div class="tweet-item ' + row + '" id="tweet-' + item.id + '"><div class="tweet-date">' + date + '</div><div class="tweet-text">' + ct + '</div><div class="clear"> </div></div>');
      row = (row == 'even' ? 'odd' : 'even');
    });
    callback();
  }); 
}
