/*
 * Copyright (C) by Netcetera AG.
 * All rights reserved.
 *
 * The copyright to the computer program(s) herein is the property of
 * Netcetera AG, Switzerland.  The program(s) may be used and/or copied
 * only with the written permission of Netcetera AG or in accordance
 * with the terms and conditions stipulated in the agreement/contract
 * under which the program(s) have been supplied.
 *
 */

/**
 * Manages the configuration ui 
 */

ConfigUI = {
  REL_TRAMDROID_NETWORK_API_ROOT: "http://netcetera.biz/tramdroid/restapi/network",
  
  _initialized: false,
  _callback: null,
  
  _editing: false,
  
  _config: undefined,
  
  init: function() {
    $('#config select#city').options({
      url: ConfigUI.apiURL('station_groups'),
      resultMapper: {label: 'name',  key: 'href' },
      selected: "/networks/lba/station_groups/13"
    });
    
    
    $('#config select#station').options({
      url: function() { return ConfigUI.withFromTime($('#config select#city').val()) || null },
      
      resultMapper: function(result) {
        return $.map(result.stations, function(s) { return [[s['name'], s['href'], s]] });
      },
      selected: "/networks/lba/stations/350"
      
    }).dependsOn('#config select#city');
    
    $('#config select#edge').options({
      url: function() { 
        var d = $('#config select#station').options('selected-data');
        if (d) {
          if (d.edges) {
            return ConfigUI.withFromTime(d.edges.href);
          }
        } else {
          return null;
        }
      },
      
      resultMapper: {key: 'href', label: 'name'},
      prepend: ['Alle', "ALL"]
      
    }).dependsOn('#config select#station');
    
    $('#config #numDepartures').empty().options(this.rangeArray(5, 26)).val(5);
    
    $('#config #numDepartures,#config select#edge,#config select#city,#config select#station')
      .change(this.updateUrl);
      
    $('#config .drawer a').empty();
    
    $('#config form').submit(function() {
      ConfigUI.reconfigure();
      return false;
    });

    $('#cancelButton').click(function() {
      ConfigUI.hide();
      ConfigUI._editing = false;
      return false;
    });
    
    $('#config .version span').text(Version.version_string);
    this._initialized = true;
  },
  
  setup: function() {
    //return;
    
    $('#config')
      .css('visibility', 'hidden')
      .css('top', - $('#config').height());
    
    $('#header').hover(
      this.showTab, 
      function(ev) {
        if (ConfigUI._editing) {
          return;
        }
        
        var cfg = $(ev.relatedTarget).closest('#config');
        if (!cfg || cfg.size() == 0) {
          ConfigUI.hide();
        }
      });
    
    $('#config .drawer a,#config .drawer span,#config .drawer')
      .click(function(e) { ConfigUI.show(); e.preventDefault(); });
  },
  
  showTab: function() {
    $('#config .drawer a')
      .attr('href', window.location.href) 
      .text(window.location.href);    
      
    if ($('#config:animated').size() == 0) {
      $('#config')
        .css('visibility', 'visible')
        .animate({
          top: - $('#config').height() + $('#config .drawer').height() + 15
        }, "normal", "swing");

        $('#config').stopTime("hider");        
        $('#config').oneTime(3000, "hider", function() {
          ConfigUI.hide();
        });
    } 
  },
  
  hide: function(ev) {
    if ($('#config:animated').size() == 0) {
      $('#config')
        .animate({
          top: - $('#config').height()
        }, "normal", "swing", function() { $('#config').css('visibility', 'hidden') });    
    } 
  },
  
  adjust: function() {
    if (!this._editing) {
      var c = $('#config');
      c.css('top', - c.height());
    }
  },

  currentConfig: function(config) {
    this._config = config;
  },
  
  show: function(config) {
    
    if (config) {
      this.currentConfig(config);
    }
    
    if (!this._initialized) {
      this.init();
    }
    
    
     $('#config').stopTime("hider");
     
//    this.populate();
    
    // populate
 
    this._editing = true;

    if ($('#config:animated').size() == 0) {
      $('#config')
        .css('visibility', 'visible')
        .animate({
          top: 0
        }, "normal", "swing");      
    }
  },
  
  populate: function() {
    if (this._config) {
      if (this._config.stationUrl) {
        
        var m = this._config.stationUrl.match(/(\d+)(\/e\/(\d+))?/);
        
        if (m) {
          $.getJSON(this.apiURL("station_groups", "find?station_id=" + m[1]),
            function(data) {
              if (data.length > 0) {
                $("#config select#city").val(data[0].href).trigger('change');
                
              }
            });
          }
          //$('#config select#station').val(m[1]);
      }
      
      if (this._config.opts) {
        $('#config #numDepartures').val(this._config.opts.numDepartures);
      }
    }
  },
  
  reconfigure: function() {
    var h = ConfigUI.composeHash();
    
    this._editing = false;
    
    if (h) {
      window.location.hash = h;
      this.hide();
    }
  },
  
  updateUrl: function() {
    var u = ConfigUI.composeURL();
    if (!u) {
      u = window.location.href;
    } 
    
    $('#config .drawer a')
      .attr('href', encodeURI(u)) 
      .text(u);
  },

  composeHash: function() {
    var station = $("#station").val();
    var edge = $("#edge").val();
    var numDepartures = parseInt($("#numDepartures").val());
    var ctime = ConfigUI._config && ConfigUI._config.opts ? ConfigUI._config.opts.ctime : undefined;
    
    var sUrl = edge == "ALL" ? station : edge;
    
    if (sUrl) {
      return "#" + sUrl + 
        (numDepartures && !isNaN(numDepartures) ? ";numDepartures=" + numDepartures : "") +
        (ctime ? ";ctime=" + ctime.toISOString() : "")
    }
    
    return undefined;
  },
  
  composeURL: function() {
    
    var prefix;
    if (window.location.hash.length > 0) {
      prefix = window.location.href.substring(0, 
        window.location.href.indexOf(window.location.hash));
    } else {
      prefix = window.location.href;
    }
    
    var hash = ConfigUI.composeHash();
    
    if (hash) {
      return prefix + hash;
    }
    
    return undefined;
    
  },
  
  apiURL: function() {
    var subUrl;
    
    if (arguments.length > 0) {
      subUrl = $.makeArray(arguments).join('/');
    }
    
    return ConfigUI.withFromTime(
      $("html>head>link[rel='" + this.REL_TRAMDROID_NETWORK_API_ROOT + "']").attr('href') +
      (subUrl ? ("/" + subUrl) : ""));
      
  },
  
  withFromTime: function(url) {
    if (!url) {
      return undefined;
    }
    
    return url + (url.indexOf("?") >= 0 ? "&" : "?") + "from=" + DateTime.now().toISOString();
  },
  
  rangeArray: function(from, to) {
    var r = [];
    for (var i = from; i < to; i++) {
      r.push(["" + i, i]);
    }
    
    return r;
  }
}