// ===========================================================================

var KSG = new Site();

// ===========================================================================

var DHTMLMenu = Class.create(PageWidget, {
	initialize : function(menu_id, config) {
		this.node = $(menu_id);

		// bail out if the menu doesn't exist on this page
		if (!this.node || this.initialized) return;

		this.setOptions(config);

		this.submenus = { };

		// get all the top-level LIs in the menu and iterate over them, adding event handlers
		$(menu_id).immediateDescendants().each(function(item){
			item.observe("mouseover", this.mouseoverHandler.bindAsEventListener(this, item));
			item.observe("mouseout", this.mouseoutHandler.bindAsEventListener(this, item));

			this.submenus[item.id] = item.down().next();
			/* console.log(this.submenus[item.id]); */
		}.bind(this));

	},

	initialized : false,
	node : null,              // holds the DOM node of the menu
	menu_hide_timeout : null, // the JS timeout ID for hiding the menu
	menu_show_timeout : null, // the JS timeout ID for showing the menu
	last_menu_on : null,      // the DOM object of the waiting to close

	mouseoverHandler : function(e, item) {
		/* console.log(arguments);  */
		// stop the menu from closing/opening (this gets called a lot)
		clearTimeout(this.menu_hide_timeout);
		clearTimeout(this.menu_show_timeout);

		// if we're mousing over the menu for the first time, set a timeout so the menu doesn't show up accidentally.
		if (this.last_menu_on == null) {
			this.menu_show_timeout = setTimeout(this.showMenu.bind(this, item),	this.CONFIG["menu_show_time"]);

		// if there's already a menu on, then we know the user is expecting to see another one, so show it immediately.
		} else if (this.last_menu_on != item) {
			this.showMenu(item);
		}
	},

	mouseoutHandler : function(e, item) {
		/* console.log(arguments);  */
		// clear the existing show/hide timeouts (this gets called a lot)
		clearTimeout(this.menu_hide_timeout);
		clearTimeout(this.menu_show_timeout);

		// only "close" the menu in a little bit if we're over a menu with submenus, otherwise, close it right now
		if (this.submenus[item.id]) {
			this.menu_hide_timeout = setTimeout(this.hideMenu.bind(this, item),	this.CONFIG["menu_hide_time"]);

		} else {
			this.hideMenu(item);
		}
	},

	// shows the menu
	showMenu : function(item) {
		// hide the last menu shown
		if (this.last_menu_on != null) { this.hideMenu(this.last_menu_on); }

		// adding the "hover" class turns on the menu
		item.addClassName(this.CONFIG['hover_class']);

		// insert the IFRAME for IE
		if (Prototype.Browser.IE6) {
			// get at the submenu for dimension info
			var submenu = this.submenus[item.id];
			if (submenu) {
				var iframe = submenu.next();

				if (submenu && !iframe) {
					this.createIframe(item, {
						'left'   : submenu.offsetLeft + "px",
						'height' : submenu.offsetHeight + "px",
						'width'  : submenu.offsetWidth + "px"
					});
				}
			}
		}

		// store the last item on
		this.last_menu_on = item;

	}, // END: showMenu()

	// hide the menu
	hideMenu : function(item) {	
		// nothing to hide
		if (item == null) return;

		// removing the "hover" class turns off the menu
		item.removeClassName(this.CONFIG['hover_class']);

		// remove the IFRAME for IE
		if (Prototype.Browser.IE6) {
			var submenu = this.submenus[item.id];
			if (submenu) {
				var iframe = submenu.next();
				if (submenu && iframe) {
					item.removeChild(iframe);
				}
			}
		}

		this.last_menu_on = null;
	}, // END: hideMenu()

	// makes an IFRAME the exact size of the menu so elements underneath it are covered
	// (IE-only)
	createIframe : function(node, style) {
		new Insertion.Bottom(node, (new Template('<iframe class="' + this.CONFIG['iframe_class'] + '" frameborder="0" scrolling="no" style="width: #{width}; height: #{height}; left: #{left};"><\/iframe>')).evaluate(style));
	}
});

DHTMLMenu.CONFIG = {
	submenu_class : "SubNav", // the DOM class of the menu container
	hover_class : "Hover", // the class to give the top-level LI to "activate" the menu
	menu_hide_time : 500, // time to keep the menus on after mouseout; in ms
	menu_show_time : 100, // threshold o
	iframe_class : "IframeFix"
};

fixWebKitInheritanceBug(DHTMLMenu);

// ---------------------------------------------------------------------------

KSG.addFeature('DHTMLMenus', {
	setupElements : function(scope) {
		$$S(scope, ".DHTMLMenu").each(function(menu) {
			this.storeWidgetInstance(menu.id, new DHTMLMenu(menu.id));
		}.bind(this));
	}
});


// ===========================================================================


KSG.addFeature('TestLinkInterceptor', {
	setupElements : function() {
		var alert_msg = function() { alert("Sorry, this link is not implemented yet."); return false; };
		var all_links = document.getElementsByTagName("A");
		for (var i=0; i < all_links.length; i++) {
			if (all_links[i].href.toUpperCase().indexOf("KSG_TEST") < 0) { continue; }
			all_links[i].onclick = alert_msg;
		}
	}
});


// ============================================================================


var DetailBubble = Class.create(PageWidget, {
	initialize : function(bubble_el, config) {
		this.node = $(bubble_el);
		if (!this.node) { return; }
		this.setOptions(config);

		this.nodes = {};

		$$S(this.node, '.CloseLink a').each(function(link) {
			link.observe('click', this.closeLinkClickHandler.bindAsEventListener(this));
		}.bind(this));
		
		this.node.observe('mouseover', this.mouseOverLinkHandler.bindAsEventListener(this));
		this.node.observe('mouseout', this.mouseOutLinkHandler.bindAsEventListener(this));

        this.nodes['detailLink'] = this.node.up().previous('dt').down('a');
		this.nodes['detailLink'].observe('mouseover', this.mouseOverLinkHandler.bindAsEventListener(this));
		this.nodes['detailLink'].observe('mouseout', this.mouseOutLinkHandler.bindAsEventListener(this));

	},
	
	node : null,              // holds the DOM node of the menu
	db_hide_timeout : null, // the JS timeout ID for hiding the menu
	db_show_timeout : null, // the JS timeout ID for showing the menu

	mouseOverLinkHandler : function(e) {
		clearTimeout(this.db_hide_timeout);
		clearTimeout(this.db_show_timeout);

		if (this.constructor.currently_open == null) {
			this.db_show_timeout = setTimeout(this.show.bind(this), this.CONFIG["db_show_time"]);
			this.constructor.currently_open = this; // pre-populate this var to prevent a second menu from showing up before this one is shown

		} else if (this.constructor.currently_open != this) { 
			this.constructor.currently_open.hide();
			this.show();
			this.constructor.currently_open = this;
		}
	},
	
	mouseOutLinkHandler : function(e) {
		clearTimeout(this.db_hide_timeout);
		clearTimeout(this.db_show_timeout);

		this.db_hide_timeout = setTimeout(this.hide.bind(this), this.CONFIG["db_hide_time"]);
	},
	
	closeLinkClickHandler : function(e) {
		clearTimeout(this.db_hide_timeout);
		clearTimeout(this.db_show_timeout);

		e.stop();
		e.element().blur();

		this.hide();
	},

	show : function() { 
        winMiddle = parseInt(document.viewport.getDimensions().height/2);
		thisHeight = this.nodes['detailLink'].viewportOffset().top;
		if (thisHeight > winMiddle) {
			this.node.addClassName('Above');
		} else {
			this.node.addClassName('Below');
		} 
		this.node.show();
	},

	hide : function() {
		this.node.hide();
		this.node.removeClassName('Above');
		this.node.removeClassName('Below');
		this.constructor.currently_open = null;
	}

});

DetailBubble.currently_open = null;

DetailBubble.CONFIG = {
	db_hide_time : 500, // time to keep displayed after mouseout; in ms
	db_show_time : 50 // threshold of hover behavior; in ms
};

fixWebKitInheritanceBug(DetailBubble);


KSG.addFeature('DetailBubble', {
	setupElements : function() {
		$$('dl.event-details dd div.DetailBubble').each(function(bubble, i) {
			bubble.id = "detail-bubble_" + (i + 1);
			this.storeWidgetInstance(bubble.id, new DetailBubble(bubble));
		}.bind(this));
	}
});


	 // ===========================================================================

var FacultyDirectorySelection = Class.create(PageWidget, 	{
	  initialize : function(select_id) {
	    // bail out if the select doesn't exist on this page
	    if (!$(select_id) || this.initialized) return;

			this.node = $(select_id);

			this.createMenu($(select_id));

			this.hide_timeout = null;
			this.show_timeout = null;
	  },

	  createMenu: function() {
	    this.node.hide();

	    var menu = this.menuShell();
	    this.department_menu = menu.appendChild(new Element('div', {id: "department_menu",
	                                                     className: 'Front',
	                                                     style: "display: none"}));

	    menu.observe('mouseover', this.mouseOverLinkHandler.bindAsEventListener(this, true));
			menu.observe('mouseout', this.mouseOutLinkHandler.bindAsEventListener(this, false));

		//menu.observe('click', this.clickLinkHandler.bindAsEventListener(this));
		//dropdown-menu.onmouseout = this.toggleMenu.bindAsEventListener(this);
	    menu.appendChild(this.department_menu);
	    this.selectionPages(this.department_menu);
	    //front.appendChild(this.menuFooter());
	    new Insertion.Before(this.node, menu);
	  },
	
	  clickLinkHandler : function(e) {
			Event.stop(e);
			console.log('ok click');
	  },

	  mouseOverLinkHandler : function(e) {
			Event.stop(e);

			clearTimeout(this.hide_timeout);

			this.show_timeout = setTimeout(this.toggleMenu.bind(this, true), 50);
	  },
	
	  mouseOutLinkHandler : function(e) {
			Event.stop(e);

			clearTimeout(this.show_timeout);

			this.hide_timeout = setTimeout(this.toggleMenu.bind(this, false), 250);
	  },

	  toggleMenu: function(show) {
			if (show) {
				this.department_menu.show();

			} else {
				this.department_menu.hide();
				this.clearPage();
			}
	  },

	  // return the text content of the currently selected option or "All"
	  selectedOptionText: function() {
	    var text = "Select";
	    if (this.node.selectedIndex != -1)
	      text = this.node.options[this.node.selectedIndex].text;

	    return text;
	  },

	  // return the outer div and selected option
	  menuShell: function() {
	    var shell = new Element('div', {id: 'dhtml-menu-department',
	                                     className: 'DhtmlMenu'});
	    var dropdown_field = new Element('span', {id: 'dropdown-field',
	                                           className: 'Link'});
		
	    dropdown_field.appendChild(document.createTextNode(this.selectedOptionText()));
	    shell.appendChild(dropdown_field);
	    return shell;
	  },
	
	  changePage: function(ev, page_label) {
		$$("#selection_pages li.Active").each(function(page) {page.removeClassName("Active");});
	    $$("#AlphaSortPagination a.Active").each(function(page) {page.removeClassName("Active");});
	    $(page_label + "_tab").addClassName("Active");
	    $(page_label + "_page").addClassName("Active");
	    Event.stop(ev);
	  },
	  

	  clearPage: function() {
			
				$$("#selection_pages li.Active").each(function(page) {page.removeClassName("Active");});
			    $$("#AlphaSortPagination a.Active").each(function(page) {page.removeClassName("Active");});
				$("A-C_tab").addClassName("Active");
			    $("A-C_page").addClassName("Active");	
			
	  },

	  selectionPages: function(wrapper) {
	    var pagination = new Element('div', {id: "AlphaSortPagination",
	                                         className: "AlphaSort"});
	    var pages = new Element('ul', {id: 'selection_pages'});
	    var groups = $$S(this.select_element, "optgroup");
	    var anchor;
	    var page;
	    var options;
	    var page_list;
	    var list_option;
	    var list_option_anchor;
	    var faculty_directory_select = this;

	    // Iterate over each option group in the select, create the pagination
	    // element "A-C" and the page (li id="A-C_page") for each
	    groups.each(function(group) {
	      anchor = new Element('a', {id: group.label + "_tab",
	                                 href: "#"});
	      anchor.onclick = faculty_directory_select.changePage.bindAsEventListener(this, group.label);
	      anchor.appendChild(document.createTextNode(group.label));
	      pagination.appendChild(anchor);

	      // | delimit the groups
	      if (!(groups.last() == group))
	        pagination.appendChild(document.createTextNode(" | "));

	      page = new Element('li', {id: group.label + '_page'});
	      page_list = new Element('ul');

	      // Iterate over the options in this group and create the list in the
	      // page.
	      $$S(group, "option").each(function(opt) {
	        list_option = new Element('li');
	        list_option_anchor = new Element('a', {href: FacultyDirectorySelection.CONFIG["path"] + FacultyDirectorySelection.CONFIG["request_prefix"] + opt.value});
	        list_option_anchor.appendChild(document.createTextNode(opt.text));
	        list_option.appendChild(list_option_anchor);
	        page_list.appendChild(list_option);
	        page.appendChild(page_list);
	      });
	      pages.appendChild(page);
	    });
	    wrapper.appendChild(pagination);
	    pages.firstChild.addClassName("Active");
	    wrapper.appendChild(pages);
	  }
	});

FacultyDirectorySelection.CONFIG = {
	path: "/about/faculty-staff-directory/",
	request_prefix: "(department)/"};


fixWebKitInheritanceBug(FacultyDirectorySelection);

// ---------------------------------------------------------------------------

KSG.addFeature('FacultyDirectorySelection', {
	setupElements : function(scope) {
		new FacultyDirectorySelection('sort-by-department');
	}
});
