/*
 * 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.
 *
 */
var imagesString = "<img id=\"image-90-opacity\" src=\"../images/antialiased/logo-09.gif\"/>" + 
			"<img id=\"image-50-opacity\" src=\"../images/antialiased/logo-27.gif\" />" + 
			"<img id=\"image-30-opacity\" src=\"../images/antialiased/logo-53.gif\" />" +
			"<img id=\"image-10-opacity\" src=\"../images/antialiased/logo-90.gif\" />";
var mobileImageString = "<img id=\"image-90-opacity\" src=\"../images/logo-mobile.gif\"/>"

Main = {
  station: null,
  display: null,
  config: null,   
  
  init: function() {
  
    ErrorMessage.init();
    
    Main.config = Config.load();
    
    if (Main.config && Main.config.opts && Main.config.opts.m) {
      Mobile.init();
      $("#logo").html(mobileImageString);
    } else {
      $("#logo").html(imagesString);
    }
    
    ConfigUI.setup();
    
    $(window).resize($.bind(this.resizeHandler, this));
    
    DateTime.initialize(Main.config, new Date(), function() {
      
      Main.urlObserver.start();
      
      if (Main.config && Main.config.isValid()) {
        Main.start();
      } else {
        Main.configure();
      }
    });
  },
  
  start: function() {
    ConfigUI.currentConfig(Main.config);

    this.station = new Station(this.config);
    this.display = new Display(this.config, this.station);
    
    // add the actions that need to be performed on each minute tick
    this.minuteTicker.add(
      this.updateClock,
      $.bind(this.station.update, this.station),
      $.bind(this.display.update, this.display)
    );
  
    // start the minute ticker
    this.minuteTicker.start();
  },
  
  restart: function() {
    this.minuteTicker.reset();
    ErrorMessage.hide();
    if (this.display) {
      this.display.scrap();
    }
    this.display = null;
    this.station = null;

    var c = Config.load();
    if (c && c.isValid()) {
      this.config = c;
      this.setAdditionalStylesheet(this.config.opts.css);

      DateTime.initialize(Main.config, new Date(), function() {      
        Main.start();
      });
    }
  },
  
  configure: function() {
    ConfigUI.show(Main.config);
  },
  
  // Object responsible for executing predefined actions at the start of every minute
  minuteTicker: {
    actions: [],

    start: function() {
      var now = DateTime.now();
      var nextMin = now.clone().setToNextMinute();

      if (nextMin > now) {
        $(document).oneTime(nextMin.getTime() - now.getTime() + 10, "firstMinute", $.bind(function() {
          this.startTicker();
          this.execute();
        }, this));
      } else {
        this.startTicker();
      }

      this.execute();
    },

    reset: function() {
      $(document)
        .stopTime("firstMinute")
        .stopTime("minuteTicker");
      this.actions = [];
    },
    
    startTicker: function() {
      var me = this;
      $(document).everyTime(60000, "minuteTicker", $.bind(this.execute, this));
    },

    execute: function() {
      $.each(this.actions, function(i, action) {
        this(); // calls the action
      });
    },

    add: function() {
      var aArray = $.makeArray(arguments);
      this.actions = this.actions.concat(aArray);
    }
  },
  
  urlObserver: {
    lastHash: undefined,
     
    start: function() {
      this.lastHash = window.location.hash;
      $(document).everyTime(200, "urlObserver", $.bind(this.observe, this));
    },
  
    stop: function() {
      $(document).stopTime("urlObserver");
    },
    
    observe: function() {
      var h = window.location.hash;
      
      if (!h) {
        return;
      }
      
      if (this.lastHash && this.lastHash == h) {
        return;
      }
      
      Main.restart();
      
      this.lastHash = h;
    }
  }, 
  
  setAdditionalStylesheet: function(stylesheet) {
    if (stylesheet) {
      $('#additional-stylesheet').attr('href', stylesheet);
    }
  },
  
  /**
   * Updates the clocks
   */
  updateClock: function() {
    var now = DateTime.now();
    //alert(now); //REMOVE LATER!!!!
    $('#datetime').text(sprintf("%s, %02d.%02d.%4d, %02d:%02d",
      now.getWeekDayString(), 
      now.getDate(), now.getMonth() + 1, now.getFullYear(), 
      now.getHours(), now.getMinutes()));
  },
  
  /**
   * This function is called when a resise is detected.
   * We handle this here because the display instance changes on reconfguration
   */
  resizeHandler: function() {
    if (this.display) {
      this.display.updateSizes();
    }
    ErrorMessage.adjust();
    ConfigUI.adjust();
  }
};

function hideAddressBar() { 
  window.scrollTo(0, 1); 
};

// jQuery idiom for "execute when the document is ready"
$(function() {
  // initialization
  Main.init();
});

