// DEPRECATED: This is the js for the old, blue layout
$.ajax({ url: '/js/stacktrace.js', dataType: 'script' });

// bunk out console for non firebug
if (!window.console) window.console = {};
if (!window.console.log) console.log = function(x){};

function report_error(msg, e, place) {
  if (e) console.log(e);
  var report = '';
  report += msg;
  if (place) report += " at " + place;
  if (e) report += "\nException: " + e;
  try {
    report += '\nStack trace:\n' + printStackTrace({e:e}).join('\n') + '\n\n';
  } catch(ee) {}
  console.log(report);
  $.post('/api/bugreport', {issue: report});
};

function handle_error(msg, uri, line) {
  report_error(msg, null, uri + ": " + line);
  return false; // don't suppress the error
};

window.onerror = handle_error;

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 && part[1]) 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').html(flash).show();
    $.cookie('flash', '');
  }

  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 static_map = $('#static_map img');
  var dynamic_map = $('#static_map div');
  var gmaps3_loaded = false;
  var reload_static_map = function(val){
    if (map_timeout) clearTimeout(map_timeout);
    if (gmaps3_loaded) return;
    dynamic_map.hide();
    static_map.attr(
      'src', 
      "http://maps.google.com/maps/api/staticmap?sensor=false"+
      "&size=360x130&" + $.param({ markers: "|" + val })).show();
  };

  var static_map_input = $('[name=loc]');
  static_map_input.live('blur', function(){
    reload_static_map($(this).val());
  }).live('keypress', function(){
    if (map_timeout) clearTimeout(map_timeout);
    var thing = $(this);
    map_timeout = setTimeout(function(){reload_static_map(thing.val());}, 1000);
  });
  
  static_map.live('click', function(){
    if (gmaps3_loaded) return;
    static_map.hide();
    dynamic_map.html("Loading...").show();
    gmaps3_loaded = true;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize_gmaps3";
    document.body.appendChild(script);
  });
  
  if (static_map_input.val()) reload_static_map(static_map_input.val());
  
  window.initialize_gmaps3 = function() {
    var coder = new google.maps.Geocoder();
    console.log("loaded");
    
    coder.geocode({"address": static_map_input.val() || "Earth"}, function(results, status) {
      console.log("geocoded");
      var center = new google.maps.LatLng(-34.397, 150.644);
      var zoom = 1;
      var viewport;
      
      if (status == google.maps.GeocoderStatus.OK) {
        center = results[0].geometry.location;
        viewport = results[0].geometry.viewport;
        zoom = 8;
      }
      
      window.gmap = new google.maps.Map(dynamic_map[0], {
        zoom: zoom,
        center: center,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false
      });
      
      if (viewport) window.gmap.fitBounds(viewport);
      
      google.maps.event.addListener(gmap, 'click', function(e) {
        if (!window.gmap_marker) {
          window.gmap_marker = new google.maps.Marker({
            map: gmap,
            position: e.latLng //new google.maps.LatLng()
          });
        } else {
          gmap_marker.setPosition(e.latLng);
        }
        static_map_input.val(e.latLng.toUrlValue());
      });
    });
  };
};



(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 current_stream_image(){
  return window.current_stream_image_url || window.current_stream_thumb;
}

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 (window.user_name && window.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 mobile_unconfirmed() {
  return window.mobile_stage == 'tentative';
}

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

function email_only_ok(){
  return window.current_stream_flags && window.current_stream_flags.indexOf('email_only_ok') >= 0;
}


function watch_location() {
  navigator.geolocation && navigator.geolocation.watchPosition(function(position) {
    $.get('/api/checkin', {
      no_poll: true, // don't pull down messages, since there's no message handler here
      lat: position.coords.latitude,
      lng: position.coords.longitude
    });
    $('body').addClass('located');
    window.user_loc = position.coords.latitude + ", " + position.coords.longitude;
    $('.magic').paint();
  });
}

