
var Loading = {
    
    loadingElementName: 'loading',
    
    start: function() {
  Notice.clear();
  $(this.loadingElementName).show();
    },
    
  stop: function() {
    AllItems.recolorRows();
    $(this.loadingElementName).hide();
  }
 }
 
 
var Notice = {
    
    noticeElementName: 'notice',
    
    show: function(html, error) {
  $(this.noticeElementName).innerHTML = html;
  $(this.noticeElementName).addClassName(error ? 'error_message' : 'notice');
  $(this.noticeElementName).show();
    },
    
    clear: function() {
  $(this.noticeElementName).hide();
  $(this.noticeElementName).innerHTML = "";
  $(this.noticeElementName).className = "";
    }
}

var Dialog = Class.create();
Dialog.prototype = {
  _elementId: 'dialog_holder',
  _topOffset: 100,
  
  initialize: function(width, height) {
    this.init(width, height);
  },
  
  init: function(width, height) {
    this._height = height;
    this._width = width;
  },
  
  show: function() {
      var dialogHolder = $(this._elementId);
      var top = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
      var windowWidth = window.innerWidth ? window.innerWidth : document.body.scrollWidth;
      var left = Math.max(0, Math.floor((windowWidth - this._width) / 2));
      documentWidth = window.outerWidth ? window.outerWidth : document.body.clientWidth;
      documentHeight = window.outerHeight ? window.outerHeight : document.body.clientHeight;
      
       $('overlay').addClassName('overlay');
        
      dialogHolder.style.width = this._width + "px";
      
      if (this._height > 0)
        dialogHolder.style.height = this._height + "px";
      else
        dialogHolder.style.height = "auto";
    
      dialogHolder.style.left = left + "px";
      dialogHolder.style.top = (top + this._topOffset) + "px";
      dialogHolder.show();
  },
   
  close: function() {
    $('overlay').removeClassName('overlay');
    $(this._elementId).hide();
  }
}

var SupportDialog = Class.create();
SupportDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
  this.init(420, 0);
    }
});

var MyAccountDialog = Class.create();
MyAccountDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
  this.init(420, 390);
    }
});

var RemindersDialog = Class.create();
RemindersDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
  this.init(420, 0);
    }
});

var SharingDialog = Class.create();
SharingDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
  this.init(420, 420);
    }
});

var NewListDialog = Class.create();
NewListDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
      this.init(420, 0);
    }
});

var EditListDialog = Class.create();
EditListDialog.prototype = Object.extend(new NewListDialog(), {});

var AddDateRangeDialog = Class.create();
AddDateRangeDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
      this.init(360, 0);
    }
});

var AddFromListDialog = Class.create();
AddFromListDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
      this.init(360, 0);
    }
});

var MessageDialog = Class.create();
MessageDialog.prototype = Object.extend(new Dialog(), {
    initialize: function() {
  this.init(420, 0);
    }
});

var ItemSelect = {
    showAll: function() {
        this._items().each(function(i) { i.show(); });
            
        this._complete();
        $('select_menu_all').addClassName('selected');
    },
    
    showUnreserved: function() {
        this._items().each(function(i) { 
            if (!i.hasClassName('reserved'))
                i.show();
            else 
                i.hide(); 
        }.bind(this));
            
        this._complete();
        $('select_menu_unreserved').addClassName('selected');
    },
    
    showReserved: function() {
        this._items().each(function(i) { 
            if (i.hasClassName('reserved'))
                i.show();
            else 
                i.hide(); 
        }.bind(this));
        
        this._complete();
        $('select_menu_reserved').addClassName('selected');
    },

   showUncompleted: function() {
        this._items().each(function(i) { 
            if (!i.hasClassName('completed'))
                i.show();
            else 
                i.hide(); 
        }.bind(this));
            
        this._complete();
        $('select_menu_uncompleted').addClassName('selected');
    },
    
    showCompleted: function() {
        this._items().each(function(i) { 
            if (i.hasClassName('completed'))
                i.show();
            else 
                i.hide(); 
        }.bind(this));
        
        this._complete();
        $('select_menu_completed').addClassName('selected');
    },

    showNone: function() {
        this._items().each(function(i) { i.hide(); });
            
        this._complete();
        $('select_menu_none').addClassName('selected');
    },
    
    showToday: function() {
        var today = this._today();

        this._items().each(function(i) { 
            var dueDate = i.dueDate();

    if (dueDate != null && this._areSameDay(dueDate, today))
                i.show();
            else 
                i.hide(); 
        }.bind(this));
            
        this._complete();
        $('select_menu_today').addClassName('selected');
    },

   showTomorrow: function() {
        var tomorrow = new Date();
        tomorrow.setDate(this._today().getDate() + 1);
        
        this._items().each(function(i) { 
            var dueDate = i.dueDate();

            if (dueDate != null && this._areSameDay(dueDate, tomorrow))
                i.show();
            else
                i.hide(); 
        }.bind(this));
            
        this._complete();
        $('select_menu_tomorrow').addClassName('selected');
    },

   showOverdue: function() {
        var today = this._today();
        this._items().each(function(i) { 
            var dueDate = i.dueDate();

            if (dueDate != null && dueDate < today)
                i.show();
            else
                i.hide(); 
        }.bind(this));
        
        this._complete();
        $('select_menu_overdue').addClassName('selected');
    },
    
    showNever: function() {
        this._items().each(function(i) { 
            var dueDate = i.dueDate();

            if (dueDate == null)
                i.show();
            else
                i.hide(); 
        }.bind(this));
        
        this._complete();
        $('select_menu_never').addClassName('selected');
    },
    
    expandNone: function() {
        this._items().each(function(i) { if (!i.hasClassName("collapsed")) i.addClassName("collapsed"); });
    },
    
    expandAll: function() {
        this._items().each(function(i) { if (i.hasClassName("collapsed")) i.removeClassName("collapsed"); });
    },

    _items: function() {
        return $$('li.item');
    },
    
    _today: function() {
        var now = new Date();
        return new Date(now.getMonth() + 1 + "/" + now.getDate() + "/" + now.getFullYear());
    },
    
    _areSameDay: function(left, right) {
        return left.getDate() == right.getDate() && left.getMonth() == right.getMonth() && left.getFullYear() == right.getFullYear();
    },
    
    _complete: function() {
        AllItems.recolorRows();
        $$('#select_menu a').each(function(a) { a.removeClassName('selected');});
    }    
}

var AllItems = {
    recolorRows: function() {
        var odd = true;
        $$('ul#item_list li.item').each(function(i) {
            if (i.style.display != 'none')
            {
                odd = !odd;
                i.removeClassName('odd');
                if (odd) i.addClassName('odd');
            }
        });
    }
}



var PopupMenu = Object.extend(Class.create(), {
  
  _showingMenu: null,
  
  AddOpenMenu: function(menu) {
    this._showingMenu = menu;
  },
  
  CloseAll: function() {
    if (this._showingMenu != null)
      this._showingMenu.close();
    this._showingMenu = null;
  },
    
  IsMenuOpen: function(menu) {
    return this._showingMenu != null && this._showingMenu.isSame(menu);
  }  
  
});

PopupMenu.prototype = {
  
  initialize: function(element) {
    this._element = element;
  },
  
  show: function() {
    if (PopupMenu.IsMenuOpen(this))
    {
      PopupMenu.CloseAll();
      return;
    }
    
    PopupMenu.CloseAll();
  this._element.show();
  PopupMenu.AddOpenMenu(this);
  },
   
  close: function() {
  this._element.hide();
  },
  
  isSame: function(menu) {
    return this._element == menu._element;
  }
}

var Reordering = {
  is_reordering: false,

  start: function(elem) {
      $('start_reordering').hide();
      $('stop_reordering').show();

      $$('li.item').each(function(d) { d.addClassName('dragging') });

      Sortable.create("item_list", {onUpdate:function(){new Ajax.Request(elem.getUpdatePath(),  {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("item_list")})}})
      this.is_reordering = true;
  },

    stop: function() {
      $('stop_reordering').hide();
      $('start_reordering').show();
      
      $$('li.item').each(function(d) { d.removeClassName('dragging') });
      AllItems.recolorRows();

      Sortable.destroy("item_list");
      this.is_reordering = false;
  }
}


var LeftDashboardNav = {
  _currentSelection: null,
  
  SelectItem: function(element) {
      document.body.focus();
      
      if (this._currentSelection != null)
        this._currentSelection.removeClassName('selected');
        
      element.addClassName('selected');
    this._currentSelection = element;    
  },
  
  IsListItemSelected: function(listItem) {
    listItem = $(listItem);
    return listItem.select('a.selected').length > 0;
  }
}

var Rules = {
  
  'A.action_link:click': function() {
    Loading.start();
  },
  
  'A.remote_action_link:click': function(element) {
      Loading.start();
      element.replace('<img src="/images/progerssbar_editnplace.gif"/>');
  },
    
  'INPUT.submit:click': function(element, e) {
    if (typeof(element.validate) != 'function' || element.validate() == true)
    {
      Loading.start();

      if (element.disableButton == undefined || element.disableButton)
        setTimeout(function() { element.disable(); }, 0);
    }
    else
      Event.stop(e);
  },
  
  'DIV#overlay:click': function() {
    new Dialog().close();
  },
  
  'LI.item DIV.title:click, LI.item DIV.show_notes:click, LI.item DIV.item_due:click': function(element, e) {
    if (Reordering.is_reordering) return;
    
    var item = Event.findElement(e, 'li');
    if (item.hasClassName('collapsed'))
        item.removeClassName('collapsed');
    else
        item.addClassName('collapsed');
  },
  
  'div.popup_menu a.show_menu_link:click': function(element, e) {
    new PopupMenu(element.nextSiblings()[0]).show();
    Event.stop(e);
  },

  'body:click': function(element, e) {
    if (!Reordering.is_reordering)
    PopupMenu.CloseAll();
  },
  
  'a#start_reordering:click': function(element, e) {
    Reordering.start(element);
    Event.stop(e);
  },
  
  'div#dashboard_left a.task_set:click': function(element) {
    LeftDashboardNav.SelectItem(element);
  },
  
  'DIV#dashboard_left div.expandable_section H3 a:click': function(element) {
    var expandable_section = element.parentNode.parentNode;
  
    ExpandableSection.expand(expandable_section)
  },
  
  'DIV#dashboard_left div.expandable_section H3 a div:click': function(element) {
    var expandable_section = element.parentNode.parentNode.parentNode;
  
    ExpandableSection.expand(expandable_section)
  },
  
  'div.panel_select ul.menu li a:click': function(element) {
    var item = element.parentNode;
    var panel_select = item.parentNode.parentNode;
    Element.select(panel_select, "ul li").each(function(li) { li.removeClassName("selected"); });
    item.addClassName("selected");
    
    Element.select(panel_select, "div.panel").each(function(panel) { panel.hide(); });
    
    var showElement = panel_select.id + "_" + element.innerHTML.toLowerCase().replace(/ /, "_");
    $(showElement).show();
    
    document.body.focus();
    
    if (item.onSelect != undefined)
      item.onSelect();
  },
  
  'input#list_link:focus, input#list_link:click': function(element) {
    element.select();
  },

	'a#show_help:click': function(element) {
		Dashboard.showHelp();
	},
	
	'a#hide_help:click': function(element) {
		Dashboard.hideHelp();
	}
	
}

EventSelectors.register(Rules);

var ExpandableSection = {
  expand: function(expandable_section) {    
      if (Element.hasClassName(expandable_section, "collapsed"))
      {
        expandable_section.removeClassName("collapsed");
        expandable_section.addClassName("expanded");
      }
      else
      {
        expandable_section.removeClassName("expanded");
        expandable_section.addClassName("collapsed");
      }
    
    document.body.focus();
  }
}

// NOTE: this should be able to be achieved with position: fixed on the overlay, but FF has a bug which hides the cursor 
// when the overlay is fixed, so, doing it this way for all browswers
Event.observe(window, "scroll", function() {
  $('overlay').style.top = (window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop) + "px";
}, false);

Event.observe(window, "load", function() {
  Dashboard.resize();
}, false);

Event.observe(window, "resize", function() {
  Dashboard.resize();
}, false);

function GetWindowDimensions() {
  var myWidth = 0, myHeight = 0;
  
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

  return {Height: myHeight, Width: myWidth};
}

var Dashboard = {
  resize: function() {
    if (!$('dashboard')) return;
    $('dashboard').style.height = (GetWindowDimensions().Height - $('dashboard').offsetTop) + "px";
    $$('div#dashboard_left div.panel').each(
      function(panel) { panel.style.height = ($('dashboard_left').clientHeight - 56) + "px"; });
  }, 
  
  sortByDate: function() {
        var items = $$('ul#item_list li.item').reverse().sort(
        function(left, right) {
          var dateLeft = left.dueDate();
          var dateRight = right.dueDate();
          
          if (dateLeft == null && dateRight == null)
              return left.position() < right.position() ? -1 : 1;
          else if (dateLeft != null && dateRight == null)
              return -1;
          else if (dateLeft == null && dateRight != null)
              return 1;
          else
              return dateLeft < dateRight ? -1 : (dateLeft > dateRight ? 1 : 0)
        });

      var item_list = $('item_list');
      
      items.each(function(item) { Insertion.Bottom(item_list, item); });
      
      AllItems.recolorRows();
  },

	showHelp: function() {
		$("dashboard_main_items").hide();
		$("dashboard_main_help").show();
		$("show_help").hide();
		$("hide_help").show();
	},
	
	hideHelp: function() {
		$("dashboard_main_help").hide();
		$("dashboard_main_items").show();
		$("hide_help").hide();
		$("show_help").show();
	}
}

function OnListChanged()
{
  $("list_description").value += $("list_id").value;
  $("list_id").value = "[empty]";
  $("list_description").focus();
}

