$(function(){

  // superfish
  $('ul.nav').superfish();

  // panel
  $.mn.panels.ul = $('#panel_icons');
  $.mn.panels.add('font_decreaser', $.mn.fontDecreaseAction);
  $.mn.panels.add('font_increaser', $.mn.fontIncreaseAction);
  $.mn.panels.add('quicknav', $.mn.quickNavPanel);
  $.mn.panels.add('timelog', new $.mn.IframePanel({
    id    : 'timelog_panel',
    icon  : '/static/images/clock.png',
    title : 'time log',
    url   : $.mn.session.timeLogURL,
    css   : { width: '260px', backgroundColor: '#111', opacity: 0.90 },
    width : 260
  }));
  $.mn.panels.add('facebook', new $.mn.IframePanel({
    id    : 'facebook_panel',
    icon  : '/static/images/facebook.png',
    title : 'facebook panel',
    url   : 'http://iphone.facebook.com/',
    css   : { width: '320px', backgroundColor: '#3b5998' },
    width : 320
  }));
  $.mn.panels.add('gmail', new $.mn.IframePanel({
    id    : 'gmail_panel',
    icon  : '/static/images/gmail.png',
    title : 'gmail panel',
    url   : 'http://m.gmail.com/',
    css   : { width: '300px', backgroundColor: '#c3d9ff' },
    width : 300
  }));
  $.mn.panels.add('30boxes', new $.mn.IframePanel({
    id    : '30boxes_panel',
    icon  : '/static/images/30boxes.png',
    title : '30boxes panel',
    url   : 'http://iphone.30boxes.com/',
    css   : { width: '340px', backgroundColor: '#ffffff' },
    width : 340
  }));
  $.mn.panels.add('twitter', new $.mn.IframePanel({
    id    : 'twitter_panel',
    icon  : '/static/images/twitter.png',
    title : 'twitter panel',
    url   : 'http://m.twitter.com/',
    css   : { width: '300px', backgroundColor: '#9ae4e8' },
    width : 300
  }));
  $.mn.panels.add('photobucket', new $.mn.IframePanel({
    id    : 'photobucket_panel',
    icon  : '/static/images/photobucket.png',
    title : 'photobucket panel',
    url   : 'http://photobucket.com/svc/jwidget.php?width=250&height=450&largeThumb=true&pbaffsite=272&bg=%23FFFFFF&border=false&bordercolor=%23000000&url=&linkType=url&textcolor=%23000000&linkcolor=%230000FF&media=image&btntxt=&searchenabled=true&searchlinkcolor=&searchbgcolor=',
    css   : { width: '300px', backgroundColor: '#ffffff' },
    width : 300
  }));
  // $.mn.panels.add('preferences', $.mn.preferencesPanel);
  $.mn.panels.add('help', new $.mn.IframePanel({
    id    : 'help_panel',
    icon  : '/static/images/help.png',
    title : 'help panel',
    url   : '/static/text/help.html',
    css   : { width: '420px', backgroundColor: '#111', opacity: 0.90 },
    width : 420
  }));

  // scroll to four corners
  // TODO - move this to $.mn.quickNavPanel.init()
  $('#nw, #menu li.home').click(function(ev){
    $('html,body').animate({ scrollTop: 0, scrollLeft: 0 }, 256);
  });
  $('#ne').click(function(ev){
    var width = $(document).width();
    $('html,body').animate({ scrollTop: 0, scrollLeft: width }, 256);
  });
  $('#se').click(function(ev){
    var width = $(document).width();
    var height = $(document).height();
    $('html,body').animate({ scrollTop: height, scrollLeft: width }, 256);
  });
  $('#sw').click(function(ev){
    var height = $(document).height();
    $('html,body').animate({ scrollTop: height, scrollLeft: 0 }, 256);
  });
  $('#n').click(function(ev){
    var height = $(window).height();
    var x = $(window).scrollTop();
    var nx = x - height;
    if (nx < 0) nx = 0;
    $('html,body').animate({ scrollTop: nx });
  });
  $('#e').click(function(ev){
    var width = $(window).width();
    var y = $(window).scrollLeft();
    var ny = y + width;
    $('html,body').animate({ scrollLeft: ny });
  });
  $('#s').click(function(ev){
    var height = $(window).height();
    var x = $(window).scrollTop();
    var nx = x + height;
    $('html,body').animate({ scrollTop: nx });
  });
  $('#w').click(function(ev){
    var width = $(window).width();
    var y = $(window).scrollLeft();
    var ny = y - width;
    if (ny < 0) ny = 0;
    $('html,body').animate({ scrollLeft: ny });
  });

  // click to navigate to a node
  $('.note_finder').click(function(ev){
    var noteId   = '#note_' + this.id.toString().split('_')[2];
    var position = $(noteId).position();
    var windowWidth  = $(window).width();
    var windowHeight = $(window).height();
    var noteWidth    = $(noteId).width();
    var noteHeight   = $(noteId).height();
    offsetX = (windowWidth / 2)   - (noteWidth / 2);
    offsetY = (windowHeight / 2)  - (noteHeight / 2);
    var newTop = position.top - offsetY;
    var newLeft = position.left - offsetX;
    if (newTop < 0)  newTop = 0;
    if (newLeft < 0) newLeft = 0;
    // window.scrollTo(position.left - offsetX, position.top - offsetY);    
    $('html,body').animate({ scrollTop: newTop, scrollLeft: newLeft }, 256);
  });

  // make metaspace sortable
  $('#metaspace table').tablesorter();
  $('#metaspace img.star').click(function(ev){ 
    if (this.src.match(/star.gif/)) { 
      this.src = '/static/images/star-on.gif';
    } else {
      this.src = '/static/images/star.gif';
    } 
  });
  $('#metaspace input.check').click(function(ev){
    if (this.checked) {
      $(this.parentNode.parentNode).addClass('selected');
    } else {
      $(this.parentNode.parentNode).removeClass('selected');
    }
  });

  // initialize contextualMenu
  $.mn.contextualMenu.init();

  // new metaspace
  $.mn.metaspace.init();

  // scroll via holding Ctrl down and hovering over the edge of the window
  $.autoscroll.init();
 
  // make #workspace draggable
  $('#workspace').dragscroller().click(function(ev) {;
    var targ;
    var e = ev;
    if (!ev) e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
      targ = targ.parentNode;
    if (targ.id == 'workspace') {
      $('div.note input, div.note textarea').blur();
    }
  });

  // make ad hideable
  $('#ad').toggle(
    function(ev){ $('#ad').animate({ width:   0 }) },
    function(ev){ $('#ad').animate({ width: 468 }) }
  );
    
  $('#secret').dblclick(function(ev){
    $.ajax({
      type     : 'POST',
      dataType : 'json',
      url      : '/@secret',
      success  : function(response) {
	if (response.success) {
	  $('#secret').css({ color: 'red', fontSize: '12pt' });
	} else {
	  $('#secret').css({ color: 'blue', fontSize: '6pt' });
	}
      }
    });
  });

  // ajax options for forms
  var formOptionsFor = function(selector) {
    return {
      dataType: 'json',
      beforeSend: function(xhr) {
        $('.spinner', $(selector)).show()
      },
      success: function(response, statusText) {
        $('.spinner', $(selector)).hide();
        if (response.success == true) {
          window.location = response.redirectTo;
        } else {
          // TODO - The json structure should contain error messages
          // and instructions on where to display them
          alert('There was an error.');
        }
      },
      error: function(xhr, message, exception) {
        $('.spinner', $(selector)).hide();
      }
    };
  };

  // forms in modal windows
  $('#login_and_registration_window').jqm({ trigger: '.login_and_registration_trigger' });
  $('#registration_form').ajaxForm(formOptionsFor('#registration_form'));
  $('#login_form').ajaxForm(formOptionsFor('#login_form'));
  $('#workspace_window').jqm({ trigger: '#workspace_trigger' })
  $('#workspace_form').submit(function(ev){
    $.mn.generate('WorkspaceConfiguringEvent', { 
      tags                 : this.tags.value,
      description          : this.tags.description,
      width                : this.width.value,
      height               : this.height.value,
      backgroundColor      : this.background_color.value,
      backgroundImage      : this.background_image.value,
      backgroundAttachment : this.background_attachment.value,
      backgroundRepeat     : this.background_repeat.value,
      backgroundPosition   : this.background_position.value
    });
    return false;
  });
  $('#workspace_creation_window').jqm({ trigger: '#menu .workspace_creation_trigger, #metaspace_header .workspace_creation_trigger' })
  $('#workspace_creation_form').ajaxForm(formOptionsFor('#workspace_creation_form'));
  $('#workspace_creation_form span.toggler').toggle(
    function(ev){ $('#workspace_creation_form .optional').show('fast'); },
    function(ev){ $('#workspace_creation_form .optional').hide('fast'); }
  );

  $('#note_color_window').data('themes', [{}]).jqm({ 
    trigger: '#contextual_menu li.color',
    onShow: function(opt){
      var noteId  = $.mn.contextualMenu.noteId;
      var noteURL = $.mn.session.eventURL.replace(/@events/, 'Note-' + noteId + '.json');
      $('#note_color_form')[0].note_id.value = noteId;
      $('#note_color_form select')[0].selectedIndex = 0;
      $.getJSON(noteURL, function(note){
        var form = $('#note_color_form')[0];
        $('#note_color_window').data('themes')[0] = {
          backgroundColor       : note.background_color,
          color                 : note.color,
          headerBackgroundColor : note.header_background_color,
          headerColor           : note.header_color,
          opacity               : note.opacity
        };
        form.background_color.value        = note.background_color;
        form.color.value                   = note.color;
        form.header_background_color.value = note.header_background_color;
        form.header_color.value            = note.header_color;
        form.opacity.value                 = note.opacity;
      });
      var i;
      var newOption;
      var original;
      if ($('#note_color_form select option').length == 1) {
        $.getJSON($.mn.session.noteThemeURL, { id: noteId }, function(themes){
          original = $('#note_color_window').data('themes');
          for (i = 0; i < themes.length; i++) {
            original.push(themes[i]);
            newOption = $('#note_color_form select option:first')
              .clone()
              .attr({ value: i+1 })
              .html(themes[i].title);
            $('#note_color_form select').append(newOption);
          }
          $('#note_color_form select').change(function(ev){
            var form   = $('#note_color_form')[0];
            var select = $('#note_color_form select')[0];
            var themes = $('#note_color_window').data('themes');
            var t = themes[select.selectedIndex];
            if (t) {
              form.background_color.value        = t.backgroundColor;
              form.color.value                   = t.color;
              form.header_background_color.value = t.headerBackgroundColor;
              form.header_color.value            = t.headerColor;
              form.opacity.value                 = t.opacity;
            }
          });
        });
      }
      opt.w.show();
    }
  });
  $('#note_color_form').submit(function(ev){
    $.mn.generate('NoteColoringEvent', { 
      noteId                : this.note_id.value,
      backgroundColor       : this.background_color.value,
      color                 : this.color.value,
      headerBackgroundColor : this.header_background_color.value,
      headerColor           : this.header_color.value,
      opacity               : this.opacity.value,
      makeDefault           : this.make_default.checked ? this.make_default.value : 0
    });
    return false;
  });
  // $('#picker').farbtastic('#note_background_color');

  // workspace handlers that require authorization
  if ($.mn.session.authorizedToEdit) {
    var session = $.mn.session;
    $('#workspace div.note').mn();
    $('#space_intro').dblclick(function(ev){
      $('#space_intro').html('Ummm....  Double-click the "BACKGROUND", not this little alert.');
    });
    $('#note_creation_trigger').click(function(ev){
      $('#space_intro').hide('slow');
      $.mn.generate('NoteCreatingEvent', {
	x: $(window).scrollLeft() + 100,
	y: $(window).scrollTop()  + 100
      });
    });
    $('#workspace').dblclick(function(ev){
      var el;
      if (!ev) var ev = window.event;
      if (ev.target) el = ev.target;
      else if (ev.srcElement) el = ev.srcElement;
        if (el.nodeType == 3) // defeat Safari bug
          el = el.parentNode;

      if (el.id != 'workspace') { return }
      $('#space_intro').hide('slow');

      // TODO - try to make a NoteCreatingEvent
      var nx = ev.pageX - 8;
      var ny = ev.pageY - 8;
      $.ajax({
        type     : 'POST',
        dataType : 'json',
        url      : session.eventURL,
        data     : {
          eventType : 'NoteCreatingEvent',
          x         : nx,
          y         : ny
        },
        success : function(response) { 
          if (response.success) {
            $.mn.registerSuccessfulEvent(response);
          } else {
            // TODO - report the error somehow
            alert("NoteCreatingEvent didn't work out");
          }
        }
      });
    });
  } else {
    // TODO: make this clause unnecessary because $.mn.Note should eventually be taking care of everything
    $('div.note').hover(
      function(ev){ 
        var oc = $(this).css('backgroundColor'); 
        $(this).css({backgroundColor: '#fc0' }).animate({ backgroundColor: oc }, 'slow') 
      }, 
      function(ev){ }
    );
    $('#workspace').dblclick(function(ev){
      $('#login_and_registration_window').jqmShow();
    });
  }

  // soft realtime updates
  if ($.mn.session.eventURL) {
    $.mn.generate('UserEnteringEvent');
    if ($.mn.session.pollingFrequency) {
      $.mn.startUpdatingEvery($.mn.session.pollingFrequency);
    }
    $(window).unload(function(){ $.mn.generate('UserLeavingEvent') });
  }

});
