/**
 * @author Ian Wetherbee
 * @date 6/11/2010
 */
/*
 * Colors: B9D4F9, 3B619C, 436EB1
 */
$(document).ready(function () {
	// console.group("Creating MenuRoots");
	$("#header-bottom li.ajax").each(function () { /* generate roots for all ajax menu items */
		$this = $(this);
		m = new MenuRoot;
		// console.debug(m);
		m.me = this;

		$container = $("<div class='scroll'></div>").css({position: "relative"});
		id = $this.attr("data-src").split("g=");
		$outer = $("<div class='menu'><div class='shadow'/></div>").attr("id", "menu-" + id[1]).css({position: "relative", overflow: "hidden"}).append($container).hide();
		$("#header").after($outer); /* add a new container for each root menu */
		m.container = $container;
		m.outer = $outer;
		$this.data("menuobj", m); /* store MenuRoot instance in each li element */
		$this.click(function () {
			// console.debug("MenuRoot clicked");
			$(this).data("menuobj").open();
		});
		$("a", $this).each(function () {
			$(this).click(function () {
				$(this).parent().click();
				return false;
			});
		});
	});
	// console.groupEnd();
	$("#header-bottom li.ajaxsearch").each(function () {
		s = new SearchRoot;
		s.me = this;
		s.init();
	});
	
	/* close menus on click off */
	$('body').click(function (event) {
	    if (!$(event.target).closest('.menu').length && !$(event.target).closest('.active-menu-root').length) {
	    	$(".active-menu-root").each(function () {
	    		$(this).data("menuobj").closeself();
	    	});
	    };
	});
	
});

jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
    return this.each(function(){
      var clicks = 0, self = this;
      jQuery(this).click(function(event){
        clicks++;
        if (clicks == 1) {
          setTimeout(function(){
            if(clicks == 1) {
              single_click_callback.call(self, event);
            } else {
              double_click_callback.call(self, event);
            }
            clicks = 0;
          }, timeout || 300);
        }
      });
    });
  }

animatetime = 1000;

function MenuRoot() {
	this.activemenu = null;
	this.me = null; /* link to the parent li element */
	this.container = null; /* div.menu > div.scroll */
	this.outer = null; /* div.menu */
	this.loaded = false;
	this.down = function () {
		$(this.container).animate({
			top: "-=" + $(this.activemenu).data("parent").height()
		}, {
			queue: true,
			duration: animatetime
		});
		$(this.outer).animate({
			height: $(this.activemenu).height()
		}, {
			queue: true,
			duration: animatetime
		}, null, refresh_all_bubbles);
	};
	this.up = function () {
		if (this.activemenu) {
			$active = $(this.activemenu);
			$(this.container).animate({
				top: "+=" + $active.data("parent").height()
			}, {
				queue: true,
				duration: animatetime
			}, function () {
				$active.hide();
			});
			$(this.outer).animate({
				height: $active.data("parent").height()
			}, {
				queue: true,
				duration: animatetime
			}, null, refresh_all_bubbles);
			this.activemenu = $active.data("parent");
		}
	};
	this.open = function () {
		if (this.active) {
			this.closeself();
			return;
		}

		this.active = true;
		/* close other active menus */
		$(".active-menu-root").each(function () {
			//console.log("Closing menu", this, $(this).data("menuobj"));
			$(this).data("menuobj").close();
		});
		$(this.me).addClass("active-menu-root");
		$(this.container).css({top: "0px"});
		/* populate if necessary */
		_menuroot = this;
		
		if (!this.loaded) {
			this.loaded = true;
			
			$.ajax({
				url: $(this.me).attr("data-src"), 
				dataType: "text",
				error: function() {/*console.error("Ajax error")*/},
				success: function (data) {
					// console.log(_menuroot);
					/* load json into the container wrapped in <div id="menu-item">...</div>
					 * {
					 *     title: "Heading",
					 *     create: function(){},
					 *     items: [
					 *         {
					 *             title: "Sub 1",
					 *             
					 *         },
					 *         {
					 *             title: "Sub 2",
					 *             items: [
					 *                 {title: "Link 1", link: "ajax.php?dept=InfoSys", ajax: 1},
					 *                 {}
					 *             ]
					 *         }
					 *     ]
					 * }
					 */
					try {
						data = $.parseJSON(data);
					} catch (e) {
						// console.error(e);
					}
					// console.log(data);
					$menubody = $("<div/>").addClass("menu-body");
					_menuroot.activemenu = $menubody;
					$wrapper = $("<div/>").addClass("links");
					if ("title" in data) {
						$menubody.append("<h1>" + data.title + "</h1>");
					}
					$.each(data.items, function(i, lists) {
						$list = $("<ul/>");
						if ("title" in lists) {
							$list.append("<h2>" + lists.title + "</h2>");
						}
						$.each(lists.items, function (k, links) {
							if (links['ajax'] == "1") {
								$a = $("<a/>").attr("href", links.link).text(links.title).click(function(){
									$(this).parent().click();
									return false;
								});
								if ("teaser" in links) {
									$a.attr("title", links.teaser);
								}
								$link = $("<li/>").attr("data-src", links.link).addClass("ajax").click(function(){
									$this_link = $(this);
									// console.log("ajax link");
									/* attach event handlers to children */
									$.getJSON($(this).attr("data-src"), function(data2){
										// console.log(data.create);
										fn = eval(data.create);
										fn(data2, _menuroot, $this_link); /* call the creation handler */
									});
								}).append($a);
							} else {
								$a = $("<a/>").attr("href", links.link).text(links.title);
								if ("teaser" in links) {
									$a.attr("title", links.teaser);
								}
								
								$link = $("<li/>").append($a);
							}
							if ("depth" in links) {
								$link.addClass("sublink");
							}
							$list.append($link);
						});
						
						$wrapper.append($list);
					});
					width = 100 / $("ul", $wrapper).length;
					if (width > 35) {
						width = 35;
					}
					$("ul", $wrapper).css({width: width + "%"});
					
					$wrapper.append("<div class='break'/>");
					$menubody.append($wrapper);
					
					$(_menuroot.container).append($menubody);
					$(_menuroot.outer).show("blind", refresh_all_bubbles);
					$(_menuroot.outer).css({height: $menubody.height()});
					
					// console.log(_menuroot.container);
					// console.log($menubody);
				}
			});
			
		} else {
			$(this.outer).show("blind");
		}
		
	};
	this.close = function () {
		this.cleanup();
		$(this.outer).stop(true, true).hide();
		refresh_all_bubbles();
	};
	this.closeself = function(){
		this.cleanup();
		$(this.outer).stop(true, true).hide("blind");
		refresh_all_bubbles();
	};
	this.cleanup = function() {
		this.active = false;
		$(this.me).removeClass("active-menu-root");
		$(".menu-body", this.outer).stop(true, true).hide();
		$(this.container).css({top: "0px"});
		this.activemenu = $(".menu-body:first", this.outer);
		$(this.outer).css({height: this.activemenu.show().height()});
	};
}

function SearchRoot() {
	this.activemenu = null;
	this.me = null; /* link to the parent li element */
	this.container = null; /* div.menu > div.scroll */
	this.outer = null; /* div.menu */
	this.loaded = false;
	this.timeout = null;
	this.init = function () {
		$this = $(this.me);
		$this.data("menuobj", s);
		$this.click(function () {
			$(this).data("menuobj").open();
		});
		$("a", $this).each(function () {
			$(this).click(function () {
				$(this).parent().click();
				return false;
			});
		});
		$container = $("<div class='scroll'></div>").css({position: "relative"});
		$outer = $("<div class='menu'><div class='shadow'/></div>").attr("id", "menu-search").css({position: "relative", overflow: "hidden"}).append($container).hide();
		$("#header").after($outer); /* add a new container for each root menu */
		this.container = $container;
		this.outer = $outer;
		
		$menubody = $("<div/>").addClass("menu-body");
		
		_searchroot = this;
		$search = $('<form action="http://www.google.com/custom" method="GET"><input type="hidden" value="sudbury.ma.us" name="domains"> or <input type="submit" value="Search Google" name="sa"><input type="radio" value="" name="sitesearch"> Web <input type="radio" value="sudbury.ma.us" name="sitesearch"> sudbury.ma.us<input type="hidden" value="LW:676;L:http://www.sudbury.ma.us/graphics/aboutheader.jpg;LH:92;BGC:#ffffff;AH:left;GL:0;AWFID:18f6d03a14910556;" name="cof"></form>');
		$input = $("<input/>").attr("autocomplete", "off").attr("name", "q").addClass("ajaxinput").bind("keypress", $.proxy(function (event) {
			clearTimeout(_searchroot.timeout);
			if (event.keyCode == 13 /* enter */) {
				this.search();
				event.preventDefault();
				event.stopPropagation();
				return false;
			} else {
				_searchroot.timeout = setTimeout($.proxy(function () {
					this.search();
				}, this), 400);
			}
		}, this));
		this.input = $input;
		$all_links = "<span class='view-all'>View All: <a href='/services/all_documents.asp'>Documents</a>, <a href='/services/all_faqs.asp'>FAQs</a>, <a href='/links.asp'>Links</a>, <a href='/services/all_meetings.asp'>Meetings</a>, <a href='/services/allnews.asp'>News</a></span>";
		$search.prepend($input);
		$menubody.append($all_links);
		$menubody.append($search);
		$wrapper = $("<div/>").addClass("links");
		this.wrapper = $wrapper;
		$menubody.append($wrapper);
		$container.append($menubody);
	};
	this.down = function () {
		$(this.container).animate({
			top: "-=" + $(this.activemenu).data("parent").height()
		}, {
			queue: true,
			duration: animatetime
		});
		$(this.outer).animate({
			height: $(this.activemenu).height()
		}, {
			queue: true,
			duration: animatetime
		});
	};
	this.up = function () {
		if (this.activemenu) {
			$active = $(this.activemenu);
			$(this.container).animate({
				top: "+=" + $active.data("parent").height()
			}, {
				queue: true,
				duration: animatetime
			}, function () {
				$active.hide();
			});
			$(this.outer).animate({
				height: $active.data("parent").height()
			}, {
				queue: true,
				duration: animatetime
			});
			this.activemenu = $active.data("parent");
		}
	};
	this.open = function () {
		if (this.active) {
			this.closeself();
			return;
		}
		this.active = true;
		/* close other active menus */
		$(".active-menu-root").each(function () {
			$(this).data("menuobj").close();
		});
		$(this.me).addClass("active-menu-root");
		$(this.outer).show("blind");
		
	};
	this.search = function () {
		_searchroot = this;
		value = $(_searchroot.input).val();

		$.ajax({
			url: "/ajax.php",
			data: {s: value},
			dataType: "text",
			error: function() {/*console.error("Ajax error")*/},
			success: function (data) {
				// console.log(_menuroot);
				/* load json into the container wrapped in <div id="menu-item">...</div>
				 * {
				 *     title: "Heading",
				 *     create: function(){},
				 *     items: [
				 *         {
				 *             title: "Sub 1",
				 *             
				 *         },
				 *         {
				 *             title: "Sub 2",
				 *             items: [
				 *                 {title: "Link 1", link: "ajax.php?dept=InfoSys", ajax: 1},
				 *                 {}
				 *             ]
				 *         }
				 *     ]
				 * }
				 */
				try {
					data = $.parseJSON(data);
				} catch (e) {
					data = false;
				}

				$wrapper = _searchroot.wrapper;
				$wrapper.html("");
				$.each(data.items, function(i, lists) {
					$list = $("<ul/>");
					if ("title" in lists) {
						$list.append("<h2>" + lists.title + "</h2>");
					}
					i = 0;
					$.each(lists.items, function (k, links) {
						$link = $("<li/>").append($("<a/>").attr("href", links.link).text(links.title));
						$list.append($link);
						i++;
					});
					if (!i) {
						$list.append("<li><i>No matches found.</i></li>");
					}
					$wrapper.append($list);
				});
				width = 100 / $("ul", $wrapper).length;
				if (width > 35) {
					width = 35;
				}
				$("ul", $wrapper).css({width: width + "%"});
				
				$wrapper.append("<div class='break'/>");				
				
				$(_searchroot.outer).animate({
					height: _searchroot.container.height()
				}, animatetime, refresh_all_bubbles);
				$(_searchroot.input).focus();
			}
		});
	};
	this.close = function () {
		this.active = false;
		$(this.me).removeClass("active-menu-root");
		$(this.outer).hide();
		refresh_all_bubbles();
	};
	this.closeself = function(){
		this.active = false;
		$(this.me).removeClass("active-menu-root");
		$(this.outer).hide("blind", refresh_all_bubbles);
	};
}


function dept_create(json, menuroot, $this_link) {
	// console.group("Creating department substructure");
	// console.log("Args:", json, menuroot);
	/*
	 * {
	 *     links: [
	 *         {title: "Documents", link: "ajax.php?dept=InfoSys&g=documents", ajax: 1},
	 *         {title: "Home Page", link: "http://sudbury.ma.us/...", ajax: 0}
	 *     ],
	 *     long_name: ,
	 *     office_hours: ,
	 *     email: ,
	 *     telephone: ,
	 *     fax: ,
	 *     address: ,
	 *     description_paragraph: ,
	 *     buildingdirections_url:
	 * }
	 */
	// console.log("Menu root", menuroot);
	// console.log("Parent", menuroot.activemenu);
	$menubody = $("<div/>").addClass("menu-body").data("parent", $(menuroot.activemenu));
	
	$wrapper = $("<div/>").addClass("links");
	$title = $("<h1><a href=\"/departments/" + json.DeptName + "/\">" + json.long_name + "</a><b> &raquo; </b></h1>");

	$("b", $title).append($("<a href='#'>Back</a>").click(function () {
		menuroot.up();
		$menubody.hide();
		return false;
	}));
	$menubody.append($title);
	$info = $("<ul/>").addClass("info");
	$.each(json.links, function (k, link) {
		if ("ajax" in link) {
			if (link.ajax == "1") {
			    click = function(){
			        $this = $(this);
			        if ($this.hasClass("active-link") && (dbl = $this.attr("data-src-dbl"))) {
			            window.location.href = dbl;
			            return false;
			        }
                    $this.parent().children().removeClass("active-link");
                    $this.addClass("active-link");
                    // console.log("dept subinfo ajax link");
                    /* attach event handlers to children */
                    $.getJSON($this.attr("data-src"), function(data2){
                        dept_sub_switch(data2, $menubody); /* switch out info section */
                        /* recalculate height */
                        $(menuroot.outer).animate({
                            height: $(menuroot.activemenu).height()
                        }, animatetime);
                    });
                    return false;
                };
                
				$link = $("<li/>").attr("data-src", link.link).addClass("ajax");
				if ("dblclick" in link) {
				    $link.attr("data-src-dbl", link.dblclick);
				}
				$a = $("<a/>").attr("href", "#").text(link.title);
				
			    $link.click(click);
			    $a.click(function(){
                    $(this).parent().click();
                    return false;
                });
				$link.append($a);
			} else {
				$link = $("<li/>").append($("<a/>").attr("href", link.link).text(link.title));
				if(k == 0) $link.addClass('home'); 
			}
		} else {
			$link = $("<li/>").append($("<a/>").attr("href", link.link).text(link.title));
			if(k == 0) $link.addClass('home');
		}

		$info.append($link);
	});
	$info.append("<i>Contact Information</i>");
	if (json.LandmarkName) {
		if (json.buildingdirections_url) {
			$info.append("<li><a href='" + json.buildingdirections_url + "'>" + json.LandmarkName + "</a></li>");
		} else {
			$info.append("<li>" + json.LandmarkName + "</li>");
		}
		
	}
	if (json.address) {
		$info.append("<li>" + json.address + "</li>");
	}
	if (json.office_hours) {
		$info.append("<li>" + json.office_hours + "</li>");
	}
	if (json.telephone) {
		$info.append("<li>Phone: " + json.telephone + "</li>");
	}
	if (json.fax) {
		$info.append("<li>Fax: " + json.fax + "</li>");
	}
	$info.append("<li><a href='mailto:" + json.email + "'>" + json.email + "</a></li>");
	$desc = $("<div/>").addClass("menu-desc");
	$desc.html(json.description_paragraph);
	
	$wrapper.append($info).append($desc).append($("<div/>").addClass("break"));
	
	$menubody.append($wrapper);
	menuroot.activemenu = $menubody;
	$menubody.data("parentmenu");
	$(menuroot.container).append($menubody);
	$this_link.data("submenu", $menubody);
	/* scroll */
	menuroot.down();
	
	// console.groupEnd();
}

function dept_sub_switch(json, $container) {
	/*
	 * [
	 *     {title: "Link 1", link: "http://..."},
	 *     {}
	 * ]
	 */
	
	$menudesc = $(".menu-desc:first", $container);
	// console.log("Switching department contents", $menudesc);
	$menudesc.html("").hide();
	i = 0;
	$ul = $("<ul/>");
	breakat = json.length / 2;
	broken = 0;
	$.each(json, function (k, link) {
		i++;
		$link = $("<li/>").append($("<a/>").attr("href", link.link).text(link.title));
		$ul.append($link);
		if (i >= breakat && !broken) {
			$menudesc.append($ul);
			broken = 1;
			$ul = $("<ul/>");
		}
	});
	$menudesc.append($ul);
	if (!i) {
		$menudesc.append("<i>No results found.</i>");
	}
	$menudesc.fadeIn();
}

