/* 
** Code copyright © Garry Hill 2008 <garry@tiffl.org>
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 K(){4.o=\'\'}K.P={L:9(s){4.o+=s},Q:9(){f r=\'\',i;X(i=4.o.k-1;i>=0;i--){r+=4.o.u(i)}4.o=r},R:9(){8 4.o}};f B=0,l=1,h=2,m=3;9 v(a,b){4.p=a.C();4.6=[7,7,7,7];4.6[B]=b;4.q=7}9 D(){4.n=7;4.Y=0;4.w=7;4.E=7;4.x=\'\';4.S=1;4.t=7}D.F=9(a,b){f d=9(c){5(c<T){8 c}5(c<Z){8(2*c)-T}5(c<10){8 c+11}5(c<12){8(2*c)-13}8 c};8(d(a)-d(b))};f G=D;D.P={14:9(a,b){a=H(a);f c=4.U(a);5(c!==7){c.q=b}},15:9(a){a=H(a);f b=4.M(a,4.n);5(!b){8 7}8 b.q},U:9(a){5((!a)||(a.k===0)){8 7}5(!4.n){4.n=y v(a.u(0),7)}f b=4.n,g=0;N(V){f c=G.F(a.C(g),b.p);5(c===0){g++;5(g==a.k){8 b}5(b.6[h]===7){b.6[h]=y v(a.u(g),b)}b=b.6[h]}I 5(c<0){5(b.6[l]===7){b.6[l]=y v(a.u(g),b)}b=b.6[l]}I{5(b.6[m]===7){b.6[m]=y v(a.u(g),b)}b=b.6[m]}}},M:9(a,b){5(!a||!b||a.k===0){8 7}f c=b,g=0;N(V){5(!c){8 7}f d=G.F(a.C(g),c.p);5(d===0){g++;5(g==a.k){8 c}c=c.6[h]}I 5(d<0){c=c.6[l]}I{c=c.6[m]}}},16:9(a){f b=4.M(a,4.n);4.w=[];5(b!==7){5(b.q!==7){4.w.O(4.J(b))}4.z(b.6[h])}8 4.w},z:9(a){5(!a){8}4.z(a.6[l]);5(a.q!==7){4.w.O(4.J(a))}4.z(a.6[h]);4.z(a.6[m])},17:9(a){4.E=[];4.x=a;4.A(4.n,0,4.S);8 4.E},A:9(a,b,d){5((!a)||(d<0)||(b>=4.x.k)){8}f c=G.F(4.x.C(b),a.p);5((d>0)||(c<0)){4.A(a.6[l],b,d)}f e=(c===0)?d:d-1;5((4.x.k==(b+1))&&(e===0)&&(a.q!==7)){4.E.O(4.J(a))}4.A(a.6[h],b+1,e);5((d>0)||(c>0)){4.A(a.6[m],b,d)}},J:9(a){4.t=y K();4.t.L(H.W(a.p));f b,j;j=a.6[B];b=a;N(j){5(j.6[h]==b){4.t.L(H.W(j.p))}b=j;j=j.6[B]}4.t.Q();8 4.t.R()}};',62,70,'||||this|if|relatives|null|return|function||||||var|charIndex|EQKID||currentNode|length|LOKID|HIKID|rootNode|string|splitchar|data|||getKeyBuffer|charAt|TSTNode|sortKeysBuffer|matchAlmostKey|new|sortKeysRecursion|matchAlmostRecursion|PARENT|charCodeAt|TernarySearchTree|matchAlmostBuffer|cca|TST|String|else|getKey|StringBuffer|append|getNode|while|push|prototype|reverse|toString|matchAlmostDiff|65|getOrCreateNode|true|fromCharCode|for|sortKeysNumReturnValues|89|97|24|121|128|put|get|matchPrefixString|matchAlmost'.split('|'),0,{}))
/* 
** Code copyright © Garry Hill 2008 <garry@tiffl.org>
*/

var to_i = function(n) { return parseInt(n, 10); };
var TIFFL = {
  _widgets_hidden: false,
  hide_widgets: function() {
    var cs = (function(t) {
      return function(event) {
        t.cancel_search();
        return true;
      };
    })(this);
    $(document).bind('keydown', cs);
    var o = $('#search-overlay');
    if (this.shite_browser()) {
      $('#widget-box').css('visibility', 'hidden');
      o.show();
    } else {
      this.animate_widget_opacity(0.1);
      o.css({'opacity': 0});
      o.show();
      o.animate({'opacity': 1});
    }
    this._widgets_hidden = true;
  },
  show_widgets: function() {
    var o = $('#search-overlay');
    if (this.shite_browser()) {
      $('#widget-box').css('visibility', 'visible');
      o.hide();
    } else {
      this.animate_widget_opacity(1);
      o.animate({'opacity': 0}, function() { $('#search-overlay').hide(); });
    }
    this._widgets_hidden = false;
  },
  toggle_widgets: function() {
    if (this._widgets_hidden) {
      this.show_widgets();
    } else {
      this.hide_widgets();
    }
  },
  cancel_search: function() {
    if (!this._widgets_hidden) { return; }
    if ($.browser.msie) {
      document.execCommand('Stop');
    } else {
      window.stop();
    }
    this.show_widgets();
    this._widgets_hidden = false;
  },
  fade_out_widgets: function() {
    if (this.shite_browser()) {
      $('#widget-box').css('visibility', 'hidden');
    } else {
      this.animate_widget_opacity(0.3);
    }
  },
  fade_in_widgets: function() {
    if (this.shite_browser()) {
      $('#widget-box').css('visibility', 'visible');
    } else {
      this.animate_widget_opacity(1);
    }
  },
  animate_widget_opacity: function(o) {
    $('#widget-box').animate({'opacity': o});
  },
  shite_browser: function() {
    return ($.browser.msie); //&& parseFloat($.browser.version, 10) < 8 // ie 8 is still shite
  }
};

var Updater = (function() {
  return {
    _spring: null,
    _listeners: [],

    start: function() {
      var t = (function(updater) {
        return function() {
          updater.tick();
        };
      })(this);
      this._spring = window.setInterval(t, 1000);
    },

    add_listener: function(c) {
      this._listeners.push(c);
    },

    tick: function() {
      var d = new Date(), h, m, s, i, l;
      h=d.getHours();
      m=d.getMinutes();
      s=d.getSeconds();
      for (i=0; i < this._listeners.length; ++i) {
        l = this._listeners[i];
        l.tick(h, m, s);
      }
    }
  };
})();

var Time = function(h, m, s, negative) {
  if (typeof m === 'undefined') {
    if (typeof h === 'undefined') {
      this.initialize_from_now();
    } else {
      this.initialize_from_string(h);
    }
  } else {
    this.h = h;
    this.m = m;
    if (typeof s == 'undefined') {
      this.s = 0;
    } else {
      this.s = s;
    }
  }
  this.negative = !!negative;
};

Time.prototype = {
  initialize_from_string: function(s) {
    var c = s.split(/:/);
    this.h = to_i(c[0].replace(/^0/, ''));
    this.m = to_i(c[1].replace(/^0/, ''));
    if (c.length > 2) {
      this.s = to_i(c[2].replace(/^0/, ''));
    } else {
      this.s = 0;
    }
  },
  initialize_from_now: function() {
    var d = new Date();
    this.h=d.getHours();
    this.m=d.getMinutes();
    this.s=d.getSeconds();
  },

  to_departure: function() {
    var h = this.h, now = (new Date()).getHours();
    if (h < (now-1)) {h += 24;}
    return (h*60) + this.m;
  },
  to_i: function() {
    return this.h * 3600 + this.m * 60 + this.s;
  },
  to_s: function(seconds) {
    var s = this.pad(this.h) + ':' + this.pad(this.m);
    if (seconds) {
      s += ':' + this.pad(this.s);
    }
    return s;
  },
  to_diff: function() {
    var s = (this.negative ? '-' : ''), min;
    if (this.h > 0) {
      s += this.h + '<span class="units">h</span> ';
    }
    min = this.m;
    if (this.s >= 30) {min++;}
    s += min + '<span class="units">m</span>';
    return s;
  },
  subtract: function(t) {
    var ts, tt, dt, dh, dm, neg = false;
    ts = t.to_i();
    tt = this.to_i();
    dt = tt - ts;
    if (ts > tt) {
      neg = true;
      dt = -dt;
    }
    dh = to_i(dt / 3600);
    dt -= dh * 3600;
    dm = to_i(dt/60);
    dt -= dm * 60;

    return new Time(dh, dm, dt, neg);
  },
  pad: function(t) {
    t = to_i(t);
    if (t < 10) {
      return '0'+t;
    }
    return t;
  }
};


var Timetable = function(form) {
  this.form = $(form);
  this.results = this.form.find('.journey-results');
  this.table = this.results.parents('table');
  this.times = null;
  var r = (function(t) {
    return function() {
      t.get();
      return false;
    };
  })(this);
  this.form.bind('tfl', r);
  if (production) {
    var l = (function(t){
      return function() {
        t.form.trigger('tfl');
      };
    })(this);
    window.setTimeout(l, 100);
  }
};

Timetable.prototype = {
  get: function(silent) {
    if (!silent) {
      this.results.empty();
      this.table.hide();
      this.start_spinner();
    }
    var s = (function(t) {
      return function(times, status) {
        t.timetable(times);
      };
    })(this);
    if (production && typeof pageTracker !== 'undefined') { pageTracker._trackEvent('TFL', 'Timetable Load'); }
    $.ajax({url:'/search/journey', 'dataType':'json', type:'POST', data:this.form.serialize(), success: s });
  },
  from: function() {
    return this.form_value('name_origin');
  },
  to: function() {
    return this.form_value('name_destination');
  },
  form_value: function(n) {
    return this.form.find('input[name="'+n+'"]').attr('value');
  },
  timetable: function(times) {
    this.times = this.parse_times(times);
    this.updated_at = (new Time()).to_s();
    this.show();
  },

  parse_times: function(times) {
    var p = [], i, t, j;
    for (i=0; i < times.length; i++) {
      j = times[i];
      t = new Time(times[i].depart);
      j.depart_time = t.to_departure();
      p.push(j);
    }
    return p;
  },

  show: function() {
    var d = this.results, c = 0, next_depart = false, j, css_classes, tr, i, now, n;
    d.empty();
    if (this._caption) {this._caption.remove();}
    if (this.spinner) {this.spinner.remove();}
    now = this.now();
    n = now.to_departure();
    this.next_expiry = n + 100000;
    d.before(this.caption());
    for (i=0; i < this.times.length; i++) {
      j = this.times[i]
      css_classes = [];
      if (j.depart_time <= n) {
        css_classes.push('gone');
      } else {
        if (!next_depart) {
          next_depart = true;
          css_classes.push('odd');
        }
        if (j.depart_time <= this.next_expiry) {
          this.next_expiry = j.depart_time;
        }
        c += 1;
      }
      css_class = '';
      if (css_classes.length > 0) {
        css_class = ' class="'+css_classes.join(' ')+'"';
      }
      tr = $('<tr'+ css_class +'></tr>');
      tr.append('<td class="in">'+((new Time(j.depart).subtract(now)).to_diff())+'</td>');
      tr.append('<td class="depart">'+j.depart+'</td>');
      tr.append('<td class="arrive">'+j.arrive+'</td>');
      tr.append('<td class="means">'+ this.interchanges(j.interchanges) +'</td>');
      tr.append('<td class="duration">'+j.duration+'</td>');
      d.append(tr);
    }
    this.table.show();
    if (c <= 1) {this.get(true);}
  },
  interchanges: function(interchanges) {
    var i, c = [], max = 4;
    for (i=0; i < Math.min(max, interchanges.length); i++) {
      c.push('<span class="'+interchanges[i]+'" title="'+interchanges[i]+'"></span>')
    };
    return c.join("") + (interchanges.length > max ? '<span class="more"></span>' : '');
  },
  caption: function() {
    this._caption = $('<tfoot><tr>'+this.caption_text()+'</tr></tfoot>');
    return this._caption;
  },
  caption_text: function() {
    return '<td class="time" colspan="3">Updated '+(this.updated_at) + '</td>';
  },
  pad_time: function(t) {
    t = to_i(t);
    if (t < 10) {
      return '0'+t;
    }
    return t;
  },

  now: function() {
    return (new Time());
  },

  start_spinner: function() {
    this.spinner = $('<p class="spinner"></p>');
    this.table.before(this.spinner);
  },
  tick: function(h, m, s) {
    var n = this.now().to_departure();
    // if (this._caption) this._caption.html(this.caption_text());
    if ((this.times && (s === 0 || n >= this.next_expiry))) {this.show();}
  }
};

var JourneyTimeForm = function(fieldset) {
  this.fieldset = $(fieldset);
  var b = (function(jtf) {
    return function() {
      jtf.synchronise();
    };
  })(this);
  this.fieldset.bind('synchronise', b);
  var c = (function(jtf) {
    return function() {
      jtf.manually_set(true);
    };
  })(this);
  this.fieldset.find('select.time').bind('change', c);
  this.synchronise();
}; 

JourneyTimeForm.test_synchronise = function() { // too hard to test this in the browser
  var times = [
    {time:{h:10, m:55}, ex:{h:10, m:55}},
    {time:{h:10, m:56}, ex:{h:11, m:00}},
    {time:{h:10, m:57}, ex:{h:11, m:00}},
    {time:{h:10, m:59}, ex:{h:11, m:00}},
    {time:{h:11, m:00}, ex:{h:11, m:00}},
    {time:{h:11, m:01}, ex:{h:11, m:05}},
    {time:{h:11, m:11}, ex:{h:11, m:15}},
    {time:{h:11, m:24}, ex:{h:11, m:25}}
  ];
  for (var i=0; i < times.length; i++) {
    var t = times[i];
    var v = this.time_select_values(t.time.h, t.time.m);
    if ((v.h !== t.ex.h) || (v.m !== t.ex.m)) {
      console.log('ex ' + t.ex.h  + ':' + t.ex.m + ' but got ' + v.h + ':' + v.m);
    }
  };
};

JourneyTimeForm.time_select_values = function(h, m){
  var rm = Math.ceil(m/5) * 5, rh = h;
  if (rm === 60) { rm = 0; rh += 1; }
  return {h:rh, m: rm};
};

JourneyTimeForm.prototype = {
  is_manually_set: function() {
    return this.fieldset[0].manually_set;
  },
  manually_set: function(b) {
    var i = 'inactive';
    this.fieldset[0].manually_set = b;
    if (b) {
      this.fieldset.find('a.reset_to_now').removeClass(i);
    } else {
      this.fieldset.find('a.reset_to_now').addClass(i);
    }
  },
  tick: function(h, m, s) {
    if (s === 0 && !this.is_manually_set()) {
      this.synchronise();
    }
  },
  synchronise: function() {
    this.manually_set(false);
    var d = new Date(), t = JourneyTimeForm.time_select_values(d.getHours(), d.getMinutes());
    this.set_select('choose-minutes', t.m);
    this.set_select('choose-hour', t.h);
    this.set_select('choose-date', d.getDate());
    this.set_select('choose-month', (d.getYear() + 1900) + '' + (d.getMonth()+1));
  },
  set_select: function(id, value) {
    var select = this.fieldset.find('select#' + id)[0];
    var padded = String(value);
    if (padded.length < 2) {
      padded = "0000".substring(0, 2 - padded.length) + padded;
    }
    for (var i=0; i < select.options.length; i++) {
      var o = select.options[i];
      if (o.value == padded) {o.selected = true;}
    }
  }
};

var Autoloader = function(widget) {
  this.widget = $(widget);
  widget.loader = this;
  this.results = this.widget.find('.results');
  var l = (function(al){
    return function() {
      al.load();
    };
  })(this);
  window.setTimeout(l, 50);
};

Autoloader.prototype = {
  load: function(silent) {
    if (!silent) {
      this.reset();
      this.start_spinner();
    }
    var ref = (function(loader) {
      return function() {
        loader.load();
        return false;
      };
    })(this);
    var w = this.widget;
    this.results.load('/widgets/load/'+this.id(), function (responseText, textStatus, XMLHttpRequest) {
      w.find('a.refresh').bind('click', ref);
    });
  },
  reset: function() {
    this.results.empty();
  },
  start_spinner: function() {
    this.results.append($('<p class="spinner"></p>'));
  },
  id: function() {
    return this.widget.attr('id').split(/_/)[1];
  },
  refresh_at: function(t) {
    this._refresh_at = new Time(t);
  },
  tick: function(h, m, s) {
    if (this._refresh_at) {
      if (h >= this._refresh_at.h && m >= this._refresh_at.m && s === 0) {
        this.load(true);
      }
    }
  }
};

var StationCompletion = function(input) {
  this.input = input;
  this.position = -1;
  this.stations = [];
  var ku = (function(completer) {
    return function(event) {
      return completer.complete(event, this.value);
    };
  })(this);
  var kd = (function(completer) {
    return function(event) {
      return completer.keydown(event);
    };
  })(this);
  var bl = (function(completer) {
    return function() {
      completer.close_list();
    };
  })(this);
  $(this.input).bind('keydown', kd).bind('keyup', ku).bind('blur', bl).attr('autocomplete', 'off');
};

StationCompletion.stations = null;
StationCompletion.postcode_re = /^([A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]?[ABEHMNPRVWXY0-9]?) *([0-9][ABD-HJLN-UW-Z]{2})$/i;

StationCompletion.prototype = {
  complete: function(event, value) {
    var r = true;
    switch(event.keyCode) {
      case 27:
        this.close_list();
        r = false;
        break;
      case 38:
        r = false;
        event.preventDefault();
        this.cursor_up();
        break;
      case 40:
        r = false;
        event.preventDefault();
        this.cursor_down();
        break;
      case 13:
        if (this._listopen) {
          r = false;
          event.preventDefault();
          event.stopPropagation();
          this.list_select();
        }
        break;
      default:
        var m = this.match_prefix(value);
        this.list(m);
        if (m.length === 0) {
          this.match_postcode(value);
        }
        break;
    }
    return r;
  },
  keydown: function(event) {
    switch (event.keyCode) {
      case 38:
        if (this._listopen) {return false;}
        break;
      case 40:
        if (this._listopen) {return false;}
        break;
      case 13: // return
        if (this._listopen) {
          return false;
        }
        break;
      case 9: //tab
        if (this._listopen) {
          this.list_select();
        }
        break;
    }
    return true;
  },  
  match_postcode: function(value) {
    var m, o, i;
    if ((m = StationCompletion.postcode_re.exec(value))) {
      this.fill(m[1].toUpperCase() + ' ' + m[2].toUpperCase());
      this.set_type('locator')
    }
  },
  set_type: function(type) {
    var i, o, s = $(this.input).next('select')[0];
    for (i=0; i < s.options.length; i++) {
      o = s.options[i];
      if (o.value == type) {
        s.selectedIndex = i;
        break;
      }
    }
  },
  list_select: function() {
    var a = this.stations[this.position];
    if (a) {
      this.set_and_close(a.text());
    }
  },
  set_and_close: function(s){
    this.fill(s);
    this.close_list();
    this.set_type('stop');
  },
  cursor_down: function() {
    if (this.position < (this.stations.length-1)) {
      if (this.selected) {
        this.selected.removeClass('high');
      }
      this.position++;
      var a = this.stations[this.position];
      a.addClass('high');
      this.selected = a;
    }
  },
  cursor_up: function() {
    if (this.selected) {
      this.selected.removeClass('high');
    }
    if (this.position >= 0) {
      this.position--;
      if (this.position >= 0) {
        var a = this.stations[this.position];
        a.addClass('high');
        this.selected = a;
      }
    }
  },
  fill: function(s) {
    this.input.value = s;
  },
  focus: function() {
    this.input.focus();
  },
  match_prefix: function(p) {
    return StationCompletion.stations.matchPrefixString(p.toLowerCase());
  },
  station_name: function(k) {
    return StationCompletion.stations.get(k);
  },
  list: function(matches) {
    if (matches.length === 0) {
      if (this._listopen) {this.close_list();}
      return;
    }
    if (!this._listopen) {
      this.open_list();
    }
    this._list.empty();
    var insert = (function(completer) {
      return function(event) {
        completer.set_and_close($(this).text());
      };
    })(this);
    this.stations = [];
    for (var i=0; i < Math.min(16, matches.length); i++) {
      var m = matches[i];
      var a = $('<a>'+this.station_name(m)+'</a>');
      a.bind('mousedown', insert);
      this.stations.push(a);
      this._list.append(a);
    }
  },
  open_list: function() {
    var l = $('<div class="station-list"></div>'), o;
    $('body').append(l);
    o = $(this.input).offset();
    l.css('left', o.left + "px");
    l.css('top', (o.top + $(this.input).height() + 4)+ "px");
    this._list = l;
    this.position = -1;
    this._listopen = true;
  },
  close_list: function() {
    if (this._list) {
      this._list.remove();
      this._list = null;
      this._listopen = false;
    }
  }
};
/* 
** Code copyright © Garry Hill 2008 <garry@tiffl.org>
*/
$(document).ready(function() {
  Updater.start();
	try {
		$('.search-widgets').Sortable({
			accept : 'widget',
			handle: 'h3.handle',
			tolerance: 'pointer',
			ghosting: false,
			helperclass: 'place',
			onChange: function(s) {
				$('.search-widgets .widget.adwords').removeClass('top-row');
				$('.search-widgets .widget.adwords:first-child').addClass('top-row');
				var h = [], i;
				for (i=1; i <= columns; i++) {
					h.push($.SortSerialize('column'+i).hash);
				}
				h = h.join('&');
				$.ajax({url:'/widgets/reorder', type:'POST',data:h});
			}
		});
	} catch (e) { /* embedded */ };

  $('p.user-input input.text').bind('focus', function() {
    $(this).prev('label').hide();
  }).bind('blur', function() {
    if (this.value === "") {
      $(this).prev('label').show();
    }
  }).each(function() {
    var l = $(this).prev('label');
    l.bind('click', function(event) {
      $(this).next('input.text').focus();
    });
    // clear label if form is already filled
    if (this.value !== "") { l.hide(); }
  });

  $('p.location input.text.editable').each(function() {
    return new StationCompletion(this);
  });

  $('form.ajax').each(function(i, e) {
    Updater.add_listener(new Timetable(e));
  }).bind('submit', function() {
    TIFFL.hide_widgets();
    return true;
  });

  $('a.show-advanced').bind('click', function() {
    var cb = (function(a) {
      return function() {
        $(a).toggleClass('shown');
        var s = 'Hide';
        if (!$(a).hasClass('shown')) {s = "Show";}
        $(a).text(s + ' advanced options');
      };
    })(this);
    $(this).parent('p').prev('.advanced-options').slideToggle(300, cb);
    return false;
  });
  // all non-complete forms should record their queries
  $('form.tfl').bind('submit', function() {
    var form = $(this);
    if (production && pageTracker) { pageTracker._trackEvent('TFL', 'New Search'); }
    TIFFL.hide_widgets();
		var sub = function() { form[0].submit(); }
		if(embedded) {
			sub();
		} else {
    $.ajax({url:'/search/save', type:'POST', data:form.serialize(), success: function(reply, status) {
				sub();
    }});
		}
    return false;
  });
  $('.widget.recent_searches form').bind('submit', function() {
    TIFFL.hide_widgets();
    if (production && pageTracker) { pageTracker._trackEvent('TFL', 'Repeat Search'); }
    var form = $(this);
    var id = form.attr('id').split(/_/)[1];
    $.ajax({url:'/search/touch/'+id, type:'POST', success: function(reply, status) {
      form[0].submit();
    }});
    return false;
  });

  $('input.toggleall').bind('click', function() {
    var s = (function(state) {
      return function(i, e) {
        e.checked = state;
      };
    })(this.checked);
    var group = this.className.split(/ /)[1];
    $(this).parents('form').find('input.togglegroup.'+group).each(s);
    return true;
  });

  $('fieldset.when').each(function(i, e) {
    Updater.add_listener(new JourneyTimeForm(e));
  });

  // should move this to the JourneyTimeForm
  $('a.reset_to_now').bind('click', function() {
    var p = $(this).parents('fieldset.when');
    p.trigger('synchronise');
  });

  $('.edit_options a').bind('click', function() {
    TIFFL.fade_out_widgets();
    $('#profile-options').slideToggle();
    return false;
  });

  $('#profile-options a.cancel').bind('click', function() {
    $('#profile-options form')[0].reset();
    TIFFL.fade_in_widgets();
    $('#profile-options').slideUp();
    return false;
  });

  $('#add-widget p.reveal a').bind('click', function() {
    TIFFL.fade_out_widgets();
    $('#add-widget-form').slideToggle();
    return false;
  });
  $('#add-widget a.cancel').bind('click', function() {
    TIFFL.fade_in_widgets();
    $('#add-widget-form').slideUp();
    $('#add-widget form')[0].reset();
    return false;
  });

  $('#add-widget p.show_help a').bind('click', function() {
    TIFFL.fade_out_widgets();
    $('#helpbox').slideToggle();
    return false;
  });

  $('.widget a.delete-widget').bind('click', function() {
    if (confirm('Are you sure you want to delete this widget')) {
      var id = this.id.split(/_/)[1];
      var cb = (function(w) {
        $(w).fadeOut('slow', function() {
          $(w).remove();
        }); })('#widget_'+ id);
      
      $.get('/widgets/destroy/'+id, null, cb);
    }
    return false;
  }).bind('mousedown', function(e) {return false;}); //catch mousedown to stop this passing onto the drag

  $('.widget.autoload').each(function() {Updater.add_listener(new Autoloader(this));});

  $('.wrapper.welcome .myinfo .widget input#work').focus();
  setTimeout(function() {$('#welcomebox').slideDown();}, 300);
  
  
  // $('#ie6-warning .firefox img').each(function() {
  //   
  // })
  // can't do this (at the mo...) cos all the widgets have their
  // options hard wired into the page..
  // $('#profile-options form').bind('submit', function() {
  //   $.post(this.action, $(this).serialize(), function() {
  //     $('#profile-options').slideToggle();
  //   });
  //   return false;
  // });
});
/* 
** Code copyright © Garry Hill 2008 <garry@tiffl.org>
*/

StationCompletion.stations = (function() {
	var tst = new TernarySearchTree();
	var p = function(s) {
		for (var i = 0; i < s.stations.length; i++) {
			var n = s.suffix ? (s.stations[i] +  ' ' + s.suffix) : s.stations[i];
			tst.put(n.toLowerCase(), n);
		}
	}
	
	var rail_stations = {suffix: "Rail Station", stations:["Abbey Wood","Acton Central","Acton Main Line","Albany Park","Alexandra Palace","Amersham","Anerley","Angel Road","Balham","Barbican","Barking","Barnehurst","Barnes","Barnes Bridge","Battersea Park","Beckenham Hill","Beckenham Junction","Bellingham","Belmont","Belvedere","Berrylands","Bethnal Green","Bexley","Bexleyheath","Bickley","Birkbeck","Blackfriars","Blackheath","Blackhorse Road","Bowes Park","Brentford","Brimsdown","Brixton","Brockley","Bromley North","Bromley South","Brondesbury","Brondesbury Park","Bruce Grove","Bush Hill Park","Caledonian Road & Barnsbury","Cambridge Heath","Camden Road","Cannon Street","Canonbury","Carshalton","Carshalton Beeches","Castle Bar Park","Catford","Catford Bridge","Chadwell Heath","Chalfont & Latimer","Charing Cross","Charlton","Cheam","Chelsfield","Chessington North","Chessington South","Chingford","Chislehurst","Chiswick","City Thameslink","Clapham High Street","Clapham Junction","Clapton","Clock House","Coulsdon South","Crayford","Crews Hill","Cricklewood","Crofton Park","Crouch Hill","Crystal Palace","Dagenham Dock","Dalston Kingsland","Dartford","Denmark Hill","Deptford","Drayton Green","Drayton Park","Ealing Broadway","Earlsfield","East Croydon","East Dulwich","Eden Park","Edmonton Green","Elephant & Castle","Elmers End","Elmstead Woods","Elstree & Borehamwood","Eltham","Emerson Park","Enfield Chase","Enfield Lock","Enfield Town","Erith","Essex Road","Euston","Falconwood","Farringdon","Feltham","Fenchurch Street","Finchley Road & Frognal","Finsbury Park","Forest Gate","Forest Hill","Fulwell","Gidea Park","Gipsy Hill","Goodmayes","Gordon Hill","Gospel Oak","Grange Park","Greenford","Greenwich","Grove Park","Gunnersbury","Hackbridge","Hackney Central","Hackney Downs","Hackney Wick","Hadley Wood","Hampstead Heath","Hampton","Hampton Court","Hampton Wick","Hanwell","Harlesden","Harold Wood","Harringay","Harringay Green Lanes","Harrow & Wealdstone","Harrow-on-the-Hill","Hatch End","Haydons Road","Hayes","Hayes & Harlington","Headstone Lane","Hendon","Herne Hill","Highams Park","Highbury & Islington","Hither Green","Homerton","Honor Oak Park","Hornsey","Hounslow","Ilford","Isleworth","Kenley","Kensal Green","Kensal Rise","Kensington (Olympia)","Kent House","Kentish Town","Kentish Town West","Kenton","Kew Bridge","Kew Gardens","Kidbrooke","Kilburn High Road","King's Cross","King's Cross Thameslink","Kingston","Knockholt","Ladywell","Lee","Lewisham","Leyton Midland Road","Leytonstone High Road","Limehouse","Liverpool Street","London Bridge","London Fields","Loughborough Junction","Lower Sydenham","Malden Manor","Manor Park","Maryland","Marylebone","Maze Hill","Mill Hill","Mitcham Junction","Moorgate","Morden South","Mortlake","Motspur Park","Mottingham","New Barnet","New Beckenham","New Cross","New Cross Gate","New Eltham","New Malden","New Southgate","Norbiton","Norbury","North Dulwich","Northolt Park","North Sheen","Northumberland Park","North Wembley","Norwood Junction","Nunhead","Oakleigh Park","Old Street","Orpington","Paddington","Palmers Green","Peckham Rye","Penge East","Penge West","Petts Wood","Plumstead","Ponders End","Purley","Purley Oaks","Putney","Queen's Park","Queens Road Peckham","Queenstown Road (Battersea)","Rainham","Ravensbourne","Raynes Park","Rectory Road","Reedham","Richmond","Riddlesdown","Romford","St. Helier","St James Street","St Johns","St Margarets","St Mary Cray","St Pancras International","Sanderstead","Selhurst","Seven Kings","Seven Sisters","Shortlands","Sidcup","Silver Street","Slade Green","Smitham","South Acton","Southall","South Bermondsey","Southbury","South Greenford","South Hampstead","South Kenton","South Merton","South Ruislip","South Tottenham","Stamford Hill","Stoke Newington","Stonebridge Park","Stoneleigh","Stratford","Stratford International","Strawberry Hill","Streatham","Streatham Common","Streatham Hill","Sudbury & Harrow Road","Sudbury Hill Harrow","Sundridge Park","Surbiton","Sutton","Sutton Common","Sydenham","Sydenham Hill","Syon Lane","Teddington","Thames Ditton","Thornton Heath","Tolworth","Tooting","Tottenham Hale","Tulse Hill","Turkey Street","Twickenham","Upminster","Upper Holloway","Vauxhall","Victoria","Waddon","Wallington","Walthamstow Central","Walthamstow Queens Road","Wandsworth Common","Wandsworth Road","Wandsworth Town","Wanstead Park","Waterloo","Waterloo East","Welling","Wembley Central","Wembley Stadium","West Brompton","Westcombe Park","West Croydon","West Drayton","West Dulwich","West Ealing","West Ham","West Hampstead","W Hampstead Thameslink","West Norwood","West Ruislip","West Sutton","West Wickham","White Hart Lane","Whitton","Willesden Junction","Wimbledon","Wimbledon Chase","Winchmore Hill","Woodgrange Park","Woodmansterne","Wood Street","Woolwich Arsenal","Woolwich Dockyard","Worcester Park"]};
	
	var underground_stations = {suffix: false, stations:["Acton Town","Aldgate","Aldgate East","All Saints","Alperton","Amersham","Angel","Archway","Arnos Grove","Arsenal","Baker Street","Balham","Bank","Barbican","Barking","Barkingside","Barons Court","Bayswater","Beckton","Beckton Park","Becontree","Belsize Park","Bermondsey","Bethnal Green","Blackfriars","Blackhorse Road","Blackwall","Bond Street","Borough","Boston Manor","Bounds Green","Bow Church","Bow Road","Brent Cross","Brixton","Bromley-by-Bow","Buckhurst Hill","Burnt Oak","Caledonian Road","Camden Town","Canada Water","Canary Wharf","Canary Wharf","Canning Town","Cannon Street","Canons Park","Chalfont & Latimer","Chalk Farm","Chancery Lane","Charing Cross","Chesham","Chigwell","Chiswick Park","Chorleywood","Clapham Common","Clapham North","Clapham South","Cockfosters","Colindale","Colliers Wood","Covent Garden","Crossharbour","Croxley","Custom House","Cutty Sark","Cyprus","Dagenham East","Dagenham Heathway","Debden","Deptford Bridge","Devons Road","Dollis Hill","Ealing Broadway","Ealing Common","Earl's Court","East Acton","East Finchley","East Ham","East India","East Putney","Eastcote","Edgware","Edgware Road","Edgware Road","Elephant & Castle","Elm Park","Elverson Road","Embankment","Epping","Euston","Euston Square","Fairlop","Farringdon","Finchley Central","Finchley Road","Finsbury Park","Fulham Broadway","Gallions Reach","Gants Hill","Gloucester Road","Golders Green","Goldhawk Road","Goodge Street","Grange Hill","Great Portland Street","Green Park","Greenford","Greenwich","Gunnersbury","Hainault","Hammersmith","Hammersmith","Hampstead","Hanger Lane","Harlesden","Harrow & Wealdstone","Harrow-on-the-Hill","Hatton Cross","Heathrow Terminals 1, 2, 3","Heathrow Terminal 4","Heathrow Terminal 5","Hendon Central","Heron Quays","High Barnet","High Street Kensington","Highbury & Islington","Highgate","Hillingdon","Holborn","Holland Park","Holloway Road","Hornchurch","Hounslow Central","Hounslow East","Hounslow West","Hyde Park Corner","Ickenham","Island Gardens","Kennington","Kensal Green","Kensington (Olympia)","Kentish Town","Kenton","Kew Gardens","Kilburn","Kilburn Park","King George V","King's Cross St. Pancras","Kingsbury","Knightsbridge","Ladbroke Grove","Lambeth North","Lancaster Gate","Langdon Park","Latimer Road","Leicester Square","Lewisham","Leyton","Leytonstone","Limehouse","Liverpool Street","London Bridge","London City Airport","Loughton","Maida Vale","Manor House","Mansion House","Marble Arch","Marylebone","Mile End","Mill Hill East","Monument","Moor Park","Moorgate","Morden","Mornington Crescent","Mudchute","Neasden","New Cross","New Cross Gate","Newbury Park","North Acton","North Ealing","North Greenwich","North Harrow","North Wembley","Northfields","Northolt","Northwick Park","Northwood","Northwood Hills","Notting Hill Gate","Oakwood","Old Street","Osterley","Oval","Oxford Circus","Paddington","Park Royal","Parsons Green","Perivale","Piccadilly Circus","Pimlico","Pinner","Plaistow","Pontoon Dock","Poplar","Preston Road","Prince Regent","Pudding Mill Lane","Putney Bridge","Queen's Park","Queensbury","Queensway","Ravenscourt Park","Rayners Lane","Redbridge","Regent's Park","Richmond","Rickmansworth","Roding Valley","Rotherhithe","Royal Albert","Royal Oak","Royal Victoria","Ruislip","Ruislip Gardens","Ruislip Manor","Russell Square","Seven Sisters","Shadwell","Shepherd's Bush Central Ln Stn","Shepherd's Bush Market Underground Station","Sloane Square","Snaresbrook","South Ealing","South Harrow","South Kensington","South Kenton","South Quay","South Ruislip","South Wimbledon","South Woodford","Southfields","Southgate","Southwark","St. James's Park","St. John's Wood","St. Paul's","Stamford Brook","Stanmore","Stepney Green","Stockwell","Stonebridge Park","Stratford","Sudbury Hill","Sudbury Town","Surrey Quays","Swiss Cottage","Temple","Theydon Bois","Tooting Bec","Tooting Broadway","Tottenham Court Road","Tottenham Hale","Totteridge & Whetstone","Tower Gateway","Tower Hill","Tufnell Park","Turnham Green","Turnpike Lane","Upminster","Upminster Bridge","Upney","Upton Park","Uxbridge","Vauxhall","Victoria","Walthamstow Central","Wanstead","Wapping","Warren Street","Warwick Avenue","Waterloo","Watford","Wembley Central","Wembley Park","West Acton","West Brompton","West Finchley","West Ham","West Hampstead","West Harrow","West India Quay","West Kensington","West Ruislip","West Silvertown","Westbourne Park","Westferry","Westminster","White City","Whitechapel","Willesden Green","Willesden Junction","Wimbledon","Wimbledon Park","Wood Lane","Wood Green","Woodford","Woodside Park"]};
	
	var dlr_stations = {suffix: false, stations:["Shadwell","Limehouse","Westferry","Poplar","Blackwall","East India","Canning Town","Royal Victoria","Custom House","Prince Regent","Royal Albert","Beckton Park","Cyprus","Gallions Reach","Beckton","West Silvertown","Pontoon Dock","London City Airport","King George V","Woolwich Arsenal","Stratford","Pudding Mill Lane","Bow Church","Devons Road","Langdon Park","All Saints","Poplar","West India Quay","Canary Wharf","Heron Quays","South Quay","Crossharbour","Mudchute","Island Gardens","Cutty Sark","Greenwich","Deptford Bridge","Elverson Road","Lewisham"]};
	
	p(rail_stations);
	p(underground_stations);
	p(dlr_stations);
	return tst;
})()

