if(![].indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj) return i;
    }
    return -1;
  };
};


function $keys(hash){
  var ms = [];
  $.each(hash, function(i, obj){ ms.push(i); });
  return ms;
}


$.extend(String.prototype, {

  ellipticise: function(max_length) {
    max_length = max_length || 25;
    if (this.length < max_length) return this;
    else return this.slice(0, max_length) + "...";
  },

  gcify_url: function(){
    if (this.charAt(0) == '/') return "http://groundcrew.us" + this;
    else return this;
  },

  contains: function(x){
    return (this.indexOf(x) >= 0);
  },

  startsWith: function(x){
    return (this.indexOf(x) == 0);
  },
  
  t: function(data) {
    if (data.indexOf) return this.t({x:data});
    return this.replace(/#\{(.*?)\}/g, function(_, p1){ return data[p1]; });
  },

  tt: function(arr) {
    if (!arr) return '';
    var self = this;
    return arr.map(function(x){ return self.t(x); }).join('');
  }

});


$.extend(Array.prototype, {

  compact: function(fn){
    var ms = [];
    $.each(this, function(i, obj){ if (obj) ms.push(obj); });
    return ms;
  },

  flatten: function(fn){
    var ms = [];
    $.each(this, function(i, obj){ ms = ms.concat(obj); });
    return ms;
  },

  contains: function(x){
    return (this.indexOf(x) >= 0);
  },

  startsWith: function(x){
    return (this.indexOf(x) == 0);
  },
  
  map: function(fn){
    //fn = fn.to_func();
    var ms = [];
    $.each(this, function(i, obj){ ms.push(fn(obj)); });
    return ms;
  }

});


var jqplus_activations = {};

$.fn.activate = function(space){
  if (jqplus_activations[space]) jqplus_activations[space].removeClass('active');
  jqplus_activations[space] = this.addClass('active');
  return this;
};



// descends from Klaus Hartl's "cookie plugin"
$.cookie = function(name, value) {
  if (typeof value != 'undefined') {
    // name and value given, set cookie
    document.cookie = [name, '=', encodeURIComponent(value), ';path=/'].join('');
  } else {
    // only name given, get cookie
    if (!document.cookie || document.cookie == '') return null;
    var cookies = document.cookie.split('; ');
    for (var i in cookies) {
      if (cookies[i].split) {
        var part = cookies[i].split('=');
        if (part[0] == name) return decodeURIComponent(part[1].replace(/\+/g, ' '));
      }
    }
    return null;
  }
};


$.fn.paint = function(){
  var data = {};
  this.find('[fill]').each(function(){
    var obj = $(this);
    var method = obj.attr('fill');
    var attr = false;
    if (method.contains(" ")) {
      var parts = method.split(' ');
      method = parts[0];
      attr = parts[1];
    }
    if (!data[method]) {
      if ($.isFunction(window[method])) data[method] = window[method]();
      else data[method] = window[method];
    }
    if (data[method]) {
      if (attr) obj.attr(attr, data[method]);
      else      obj.html(data[method]);
    }
  });
  this.find('[if]').each(function(){
    var obj = $(this);
    var method = obj.attr('if');
    var reverse = false;
    if (method.charAt(0) == '!') {
      method = method.slice(1);
      reverse = true;
    }
    if (!data[method]) {
      if ($.isFunction(window[method])) data[method] = window[method]();
      else data[method] = window[method];
    }
    var value = data[method];
    if (reverse) value = !value;
    if (value) obj.show();
    else obj.hide();
  });
  this.find('input[hint],textarea[hint]').each(function(){
    var self = $(this);
    var hint = self.attr('hint');
    self.val(hint).addClass('prompting');
    self.focus(function(){
      if (self.is('.prompting')) self.val('').removeClass('prompting');
    });
    self.blur(function(){ if (!self.val()) self.val(hint).addClass('prompting'); });
  });
  return this;
};





window.paint = function(){

  var flash = $.cookie('flash');
  if (flash && flash != 'cleared') {
    $('#flash').html(flash).show();
    $.cookie('flash', 'cleared');
  }

  if (window.authority) $('body').addClass( 'logged_in' );
  else $('body').addClass( 'logged_out' );

  $('#ie_js_warning').hide();

  $('a[tab]').live('click', function(){
    $('#tabs li').removeClass('ui-tabs-selected');
    $(this).parent('li').addClass('ui-tabs-selected');
    var parts = $(this).attr('tab').split(' ');
    var tabspace = parts[0];
    var tabname = parts[1];
    $('#' + tabspace + ' div.active').removeClass('active');
    $('#' + tabspace + '_' + tabname).addClass('active');
    return false;
  });

  $(document).paint();
  
  var map_timeout;
  var reload_map = function(val){
    if (map_timeout) clearTimeout(map_timeout);
    $('#static_map img').attr('src', "http://maps.google.com/maps/api/staticmap?sensor=false&key=ABQIAAAAGqp2ukVwjWFfmC-XmCCZFRRGsPIMf82DrFSwJZKzmHDVn9CoiRSfPwbMs9LeX9Qw4ba2CuYyrEQBZw&size=360x130&" + $.param({ markers: "|" + val }));
  };
  
  $('[name=loc]').live('blur', function(){
    reload_map($(this).val());
  }).live('keypress', function(){
    if (map_timeout) clearTimeout(map_timeout);
    var thing = $(this);
    map_timeout = setTimeout(function(){reload_map(thing.val());}, 1000);
  });
};



(function(){

    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    jQuery.event.special.focus = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'focus';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid1, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('focus', handler, true);
                } else {
                    _self.attachEvent('onfocusin', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid1);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('focus', handler, true);
                } else {
                    this.detachEvent('onfocusin', handler);
                }
            }
        }
    };

    jQuery.event.special.blur = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'blur';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid2, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('blur', handler, true);
                } else {
                    _self.attachEvent('onfocusout', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid2);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('blur', handler, true);
                } else {
                    this.detachEvent('onfocusout', handler);
                }
            }
        }
    };

})();

function $long_ago(t){
  var now = Math.floor(new Date().getTime() / 1000);
  var delta = now - Number(t);
  if (delta < 5) delta = 5;
  if (delta < 60) return delta + " seconds";
  var minutes = Math.round(delta / 60);
  if (minutes > 90) {
     var hours = Math.floor(minutes / 6) / 10;
     if (hours > 24) {
       var days = Math.floor(hours / 2.4) / 10;
       return days + " days";
     }
     return hours + " hours";
  } else {
     return minutes + " minutes";
  }
};

function this_squad_uses_mobile(){
  return window.current_stream_systems && window.current_stream_systems.indexOf('m') >= 0;
};

function on_this_squad(){
  return agent_on_this_squad() || organizer_on_this_squad();
};

function agent_on_this_squad(){
  return window.posts_to_streams && window.posts_to_streams.contains(window.current_stream);
};

function organizer_on_this_squad(){
  return window.stream_role;
};

function leader_on_this_squad(){
  return window.stream_role == 'leader';
};

function onmap(){
  return window.latch && (window.latch.indexOf('offmap') == -1);
}

function real_user_name(){
  if (user_name && user_name.indexOf('@') == -1) return user_name;
  return null;
};

function pretty_user_mobile() {
  var m = window.user_mobile;
  if (!m) return '';
  m = m.replace('+1', '');
  if (m.length == 10) {
    m = m.substring(0, 3) + ' ' + m.substring(3, 6) + '-' + m.substring(6, 10);
  }
  return m;
}

function email_confirmed() {
  return window.email_stage == 'confirmed';
}

function mobile_confirmed() {
  return window.mobile_stage == 'confirmed';
}

function need_point_confirmation() {
  return (window.email_stage == 'tentative' || window.mobile_stage == 'tentative');
}
