﻿/// <reference path="../json2.js" />
/// <reference path="../enviro.js" />
/// <reference path="../jquery/jquery-1.3.2.js" />
/// <reference path="../jquery/jquery.pan.js" />
/// <reference path="../swfobject-redux.js" />
/// <reference path="../template.js" />

window.$section = function() {
	// Constants
	var c_images = "images.section";
	var c_page = "page.section";
	var c_overNav = "over_nav.section";
	var c_timeout = "timeout.section";
	var c_idx = "idx.section";

	// Private Variables
	var _loaded = false;

	// Private Methods
	var _nextIndex = function(current, length, increment) {
		for (var i = 0; i < (increment !== undefined ? increment : 1); i++) {
			if (++current >= length) {
				current = 0;
			}
		}

		return current;
	};

	var _createPages = function() {
		var nav = $("#nav");
		var pages = $("<div id=\"" + e_pagesId + "\"><div id=\"ctl00_cphContent_page_back\"><div class=\"panel\">"
            + "<div class=\"left\"><div class=\"inner\" id=\"page_inner\"><h1></h1></div></div><div class=\"middle\">"
            + "<div id=\"lp\"></div></div><div class=\"right\"><a id=\"ctl00_cphContent_gt\" href=\"#0\">Gallery</a>"
            + "<ul class=\"nav\"></ul></div></div></div></div>").insertBefore(nav);

		if ($.browser.msie && $.browser.version < 7) {
			pages.find(".left").before("<div class=\"left_back_ie6\"></div>");
			pages.find(".right").before("<div class=\"right_back_ie6\"></div>");
		}

		return pages;
	};

	var _createGallery = function() {
		return $("<div class=\"gallery\"><div class=\"slide\"></div><div class=\"context\"><a href=\"#\" class=\"close\">close</a>"
            + "<div class=\"thumb\"></div><ul></ul></div></div>").appendTo("#" + e_pagesId + " .panel");
	};

	var _changePageContent = function(name, description, flashUrl) {
		var inner = $("#" + e_pagesId + " div.panel div.left div.inner");
		inner.children().remove();
		inner.text("");

		inner.append("<h1>" + name + "</h1>");
		inner.append(description);

		inner.find("a[rel='new'], a[rel='flash'], a[rel='360']")
		    .attr("title", "This link will open in a new window")
		    .append("<img src=\"/images/nw.gif\" width=\"16\" height=\"12\" alt=\"New Window Icon\" />");

		inner.find("a[rel='new']").click(function(evt) {
			evt.preventDefault();

			window.open(this.href);

			logEvent("external", this.href.replace("http://", ""));
		});

		inner.find("a[rel='int']").click(function(evt) {
			evt.preventDefault();

			var href = $(this).attr("href").split("/");
			if (href.length > 0) {
				goTo(href[href.length - 1]);
			}
		});

		inner.find("a[rel='flash']").click(function(evt) {
			evt.preventDefault();

			var features = "links=no, scrollbars=no, toolbar=no, menubar=no, status=no, height=536, width=950, top=50, left=50";
			window.open(this.href, "", features);

			var href = this.href.split("?f=");
			var flash = (href.length == 2 ? href[1] : "unknown");

			logEvent("flash", flash);
		});

		inner.find("a[rel='360']").click(function(evt) {
			evt.preventDefault();

			var features = "links=no, scrollbars=no, toolbar=no, menubar=no, status=no, height=550, width=950, top=50, left=50";
			window.open(this.href, "", features);

			logEvent("popup", "360");
		});

		var pages = $("#" + e_pagesId);
		if (pages.css("display") != "block") {
			pages.css({
				"display": "block"
			});
			_animateSection();
		}

		$("#" + e_page_backId).css({ backgroundPosition: "-950px 0" })
            .animate({ backgroundPosition: "(0px 0px)" }, { duration: 1000 });

		setTimeout(function() {
			var lp = $("#lp");
			lp.children().remove();

			if (flashIsGood() && flashUrl != "plans") {
				var lpChild = $("<div id=\"lp_child\"></div>").appendTo(lp);
				$so.createSWF({
					data: "/flash/" + flashUrl + "/lp.swf",
					width: 100,
					height: 70
				}, {
					menu: false,
					wmode: "transparent",
					loop: false,
					quality: "high"
				}, "lp_child");
			}
		}, 1);
	};

	// Ajax Calls
	var _getSection = function(section, page, error) {
		getSection(section, _buildSection, error, page);
	};

	var _getPage = function(page, error) {
		var url = "/Service.asmx/GetPage";
		var data = {};

		if (isNaN(page)) {
			url += "ByCode";
			data.pageCode = page;
		}
		else {
			data.pageId = page;
		}

		$.ajaxDotNet(url, {
			verb: "GET",
			data: data,
			success: _buildPage,
			error: error
		});
	};

	var _getImages = function(page, error) {
		$.ajaxDotNet("/Service.asmx/GetPageImages", {
			verb: "GET",
			data: {
				pageId: page
			},
			success: _buildImages
		});
	};

	var _getNavigation = function(section, page, error) {
		$.ajaxDotNet("/Service.asmx/GetPages", {
			verb: "GET",
			data: {
				sectionId: section.ID
			},
			success: _buildNavigation,
			error: error,
			context: { section: section.Code, page: page }
		});
	};

	// Callbacks
	var _buildSection = function(obj, status, statusText, page) {
		if (!obj || !obj.d) {
			return;
		}

		var section = obj.d;
		var pages = $("#" + e_pagesId);
		var pageBack = $("#" + e_page_backId);

		if (!page && section.OverrideCode != "") {
			page = section.OverrideCode;
		}

		// Reset Document
		changeTitle(section.MetaTitle);

		// Clear Sub Section
		pageBack.removeClass();

		// Reset Section
		pages.removeClass().addClass(section.Code);
		pages.find(".middle").children("a").remove();
		$("#" + e_gtId).css("display", "none");

		_getNavigation(section, page);

		if (page) {
			_getPage(page);
		}
		else {
			_changePageContent(section.Name, section.Description, section.Code);
		}
	};

	var _buildPage = function(obj) {
		if (!obj || !obj.d) {
			return;
		}

		var page = obj.d;
		var pageBack = $("#" + e_page_backId);

		changeTitle(page.MetaTitle);
		pageBack.removeClass().addClass(page.Code);
		_changePageContent(page.Name, page.Description, (page.SectionCode == "facilities" ? page.SectionCode + "/" + page.Code : page.SectionCode));
		_getImages(page.ID);
	};

	var _buildImages = function(obj) {
		if (!obj || !obj.d) {
			return;
		}

		var images = obj.d;
		var pages = $("#" + e_pagesId);
		var middle = pages.find(".middle");
		var gallery = pages.find(".gallery");
		var galleryNav = pages.find(".context ul");
		var slides = pages.find(".slide");
		var thumbs = pages.find(".thumb");

		middle.children("a").remove();
		galleryNav.children().remove();
		slides.children().remove();
		thumbs.children().remove();

		if (images.length > 0) {
			$("#" + e_gtId).css("display", "block");
			gallery.data(c_images, images);

			$.each(images, function(i) {
				if (i < 2) {
					middle.append("<a href=\"#" + i + "\"><img src=\"/gallery.ashx?h=95&w=95&id=" + this.ID
						+ "&e=" + this.Extension + "\" /></a>");
				}

				galleryNav.append("<li><a href=\"#" + i + "\">" + this.ID + "</a></li>");
			});

			galleryNav.css("left", 96 - (images.length * 10));

			middle.children("a").click(_gallery_open);
			galleryNav.find("a").hover(_galleryNav_over, _galleryNav_off).click(_galleryNav_click);
		}
		else {
			$("#" + e_gtId).css("display", "none");
		}
	};

	var _buildNavigation = function(obj, status, statusText, context) {
		if (!obj || !obj.d) {
			return;
		}

		var pages = $("#" + e_pagesId);
		var nav = pages.find("div.right ul.nav");
		var pageBack = $("#" + e_page_backId);
		var pageCollection = obj.d;

		nav.children().remove();

		$.each(pageCollection, function(i) {
			var li = $("<li><a href=\"/" + context.section + "/" + this.Code
                + "\" class=\"" + this.Code + (this.Code == context.page ? " active" : "")
				+ "\">" + this.Name + "</a></li>").appendTo(nav);
			li.data(c_page, this);
		});

		pages.find("ul.nav a").click(_nav_click);
	};

	// Animations
	var _animateSection = function(callback) {
		var pages = $("#" + e_pagesId);
		var left = pages.find("div.panel div.left, div.left_back_ie6");
		var middle = pages.find("div.panel div.middle");
		var right = pages.find("div.panel div.right, div.right_back_ie6");

		middle.animate({
			"left": "395px"
		}, function() {
			right.css({
				"display": "block"
			});
		});

		middle.animate({
			"width": "129px"
		});

		left.animate({
			"left": "0px"
		});

		if ($.isFunction(callback)) {
			callback();
		}
	};

	var _showGallery = function(idx) {
		var pages = $("#" + e_pagesId);
		var middle = pages.find(".middle");
		var gallery = pages.find(".gallery");
		var galleryNav = pages.find(".context ul");
		var slides = pages.find(".slide");
		var thumbs = pages.find(".thumb");
		var images = gallery.data(c_images);

		if (!images || !(idx >= 0)) {
			return;
		}

		var timeout = gallery.data(c_timeout);
		if (!isNaN(timeout)) {
			clearTimeout(timeout);
			gallery.data(c_timeout, null);
		}

		var current = images[idx];
		var next = images[_nextIndex(idx, images.length)];

		var s_path = "/gallery.ashx?h=314&w=506&id=";
		var t_path = "/gallery.ashx?h=130&w=130&id=";

		var cs_img = new Image();
		var ns_img = new Image();
		var ct_img = new Image();
		var nt_img = new Image();

		var cs_path, ns_path, ct_path, nt_path;

		cs_img.src = cs_path = s_path + current.ID + "&e=" + current.Extension;
		ns_img.src = ns_path = s_path + next.ID + "&e=" + next.Extension;

		var slide = $("<img src=\"" + cs_path + "\" />").appendTo(slides);
		slides.css("background-image", "url(" + ns_path + ")");

		current = next;
		next = images[_nextIndex(idx, images.length, 2)];

		ct_img.src = ct_path = t_path + current.ID + "&e=" + current.Extension;
		nt_img.src = nt_path = t_path + next.ID + "&e=" + next.Extension;

		thumbs.append("<img src=\"" + nt_path + "\" />");
		thumbs.append("<img src=\"" + ct_path + "\" />");

		galleryNav.children("li").removeClass("on");
		galleryNav.children("li:eq(" + _nextIndex(idx, images.length) + ")").addClass("on");

		gallery.animate({
			"left": "0px"
		}, function() {
			gallery.data(c_idx, idx);
			gallery.data(c_timeout, setTimeout(_galleryTransition, 3000));
		});
	};

	var _hideGallery = function() {
		var pages = $("#" + e_pagesId);
		var gallery = pages.find("div.gallery");
		var slides = pages.find("div.slide");

		if (gallery.css("left") != "-730px") {
			gallery.animate({
				"left": "-730px"
			}, function() {
				var timeout = gallery.data(c_timeout);
				if (!isNaN(timeout)) {
					clearTimeout(timeout);
					gallery.data(c_timeout, null);
				}

				slides.children().remove();
				gallery.data(c_overNav, false);
			});
		}
	};

	var _galleryTransition = function() {
		var pages = $("#" + e_pagesId);
		var gallery = pages.find(".gallery");
		var galleryNav = pages.find(".context ul");
		var slides = pages.find(".slide");
		var thumbs = pages.find(".thumb");
		var idx = gallery.data(c_idx);
		var images = gallery.data(c_images);

		if (isNaN(idx) || !images) {
			return;
		}

		var timeout = gallery.data(c_timeout);
		if (!isNaN(timeout)) {
			clearTimeout(timeout);
			gallery.data(c_timeout, null);
		}

		idx = _nextIndex(idx, images.length);
		var current = images[idx];
		var next = images[_nextIndex(idx, images.length)];

		var s_path = "/gallery.ashx?h=314&w=506&id=";
		var t_path = "/gallery.ashx?h=130&w=130&id=";

		var cs_img = new Image();
		var ns_img = new Image();
		var ct_img = new Image();
		var nt_img = new Image();

		var cs_path, ns_path, ct_path, nt_path;

		cs_img.src = cs_path = s_path + current.ID + "&e=" + current.Extension;
		ns_img.src = ns_path = s_path + next.ID + "&e=" + next.Extension;

		var slideChildren = slides.children("img");
		//slideChildren.stop(true, true);
		slideChildren.fadeOut("slow");
		slideChildren.queue(function() {
			$(this).attr("src", cs_path);
			$(this).dequeue();
		});
		slideChildren.fadeIn("slow", function() {
			slides.css({
				"background-image": "url(" + ns_path + ")"
			});
			gallery.data(c_idx, idx);
			gallery.data(c_timeout, setTimeout(_galleryTransition, 3000));
		});

		if (!gallery.data(c_overNav)) {
			current = next;
			next = images[_nextIndex(idx, images.length, 2)];

			ct_img.src = ct_path = t_path + current.ID + "&e=" + current.Extension;
			nt_img.src = nt_path = t_path + next.ID + "&e=" + next.Extension;

			var first = thumbs.find("img:first");
			var last = thumbs.find("img:last");

			first.attr("src", ct_path);

			last.stop().css({ display: "block", opacity: 1 }).fadeOut("slow");
			last.queue(function() {
				$(this).attr("src", ct_path);
				$(this).dequeue();
			});
			last.fadeIn("slow", function() {
				first.attr("src", nt_path);
			});

			galleryNav.children("li").removeClass("on");
			galleryNav.children("li:eq(" + _nextIndex(idx, images.length) + ")").addClass("on");
		}
	};

	// Event Handlers
	var _nav_click = function(evt) {
		evt.preventDefault();

		var a = $(this);
		var li = a.parent();
		var page = li.data(c_page);

		if (page) {
			goTo(page.SectionCode, page.Code);
		}
		else {
			var href = a.attr("href").split("/");
			var i = (href[0] == "" ? 1 : 0);
			goTo(href[i], (href.length > ++i ? href[i] : null));
		}
	};

	var _gallery_open = function(evt) {
		evt.preventDefault();

		_showGallery(Number($(this).hash()));
	};

	var _gallery_close = function(evt) {
		evt.preventDefault();

		_hideGallery();
	};

	var _galleryNav_over = function(evt) {
		var $this = $(this);
		var idx = Number($this.hash());
		var pages = $("#" + e_pagesId);
		var gallery = pages.find(".gallery");
		var thumbs = pages.find("div.thumb");
		var galleryNav = pages.find(".context ul");
		var images = gallery.data(c_images);

		if (isNaN(idx) || !images) {
			return;
		}

		var current = images[idx];
		var next = images[_nextIndex(idx, images.length)];

		gallery.data(c_overNav, true);

		var first = thumbs.find("img:first");
		var last = thumbs.find("img:last");

		first.attr("src", "/gallery.ashx?h=130&w=130&id=" + current.ID + "&e=" + current.Extension);

		last.stop().css({ display: "block", opacity: 1 }).fadeOut("slow");
		last.queue(function() {
			$(this).attr("src", "/gallery.ashx?h=130&w=130&id=" + current.ID + "&e=" + current.Extension);
			$(this).dequeue();
		});
		last.fadeIn("slow", function() {
			first.attr("src", "/gallery.ashx?h=130&w=130&id=" + next.ID + "&e=" + next.Extension);
		});

		galleryNav.children("li").removeClass("on");
		$this.parent("li").addClass("on");
	};

	var _galleryNav_off = function(evt) {
		var pages = $("#" + e_pagesId);
		var gallery = pages.find(".gallery");
		gallery.data(c_overNav, false);
	};

	var _galleryNav_click = function(evt) {
		evt.preventDefault();

		var $this = $(this);
		var idx = Number($this.hash());
		var pages = $("#" + e_pagesId);
		var gallery = pages.find(".gallery");
		var slides = pages.find(".slide");
		var images = gallery.data(c_images);

		if (isNaN(idx) || !images) {
			return;
		}

		var timeout = gallery.data(c_timeout);
		if (!isNaN(timeout)) {
			clearTimeout(timeout);
			gallery.data(c_timeout, null);
		}

		var current = images[idx];
		var next = images[_nextIndex(idx, images.length)];

		var s_path = "/gallery.ashx?h=314&w=506&id=";
		var t_path = "/gallery.ashx?h=130&w=130&id=";

		var cs_img = new Image();
		var ns_img = new Image();
		var ct_img = new Image();
		var nt_img = new Image();

		var cs_path, ns_path, ct_path, nt_path;

		cs_img.src = cs_path = s_path + current.ID + "&e=" + current.Extension;
		ns_img.src = ns_path = s_path + next.ID + "&e=" + next.Extension;

		var slideChildren = slides.children("img");

		slides.stop(true, true).css({
			"display": "none",
			"opacity": 1
		});

		slideChildren.stop().css({
			"display": "inline",
			"opacity": 1
		});

		slideChildren.attr("src", cs_path);

		slides.css({
			"background-image": "url(" + ns_path + ")"
		}).fadeIn(function() {
			gallery.data(c_idx, idx);
			gallery.data(c_timeout, setTimeout(_galleryTransition, 3000));
		});
	};

	var _init = function() {
		var pages = $("#" + e_pagesId);
		if (pages.length < 1) {
			pages = _createPages();
		}

		_createGallery();

		$("#" + e_gtId).click(_gallery_open);
		pages.find(".gallery .close").click(_gallery_close);
	};

	var _show = function(section, page, envOnly) {
		var pages = $("#" + e_pagesId);

		_hideGallery();

		if (!envOnly) {
			_getSection(section, page);
		}
		else {
			pages.css({
				"display": "block"
			});
			_animateSection();
			pages.find("ul.nav a").click(_nav_click);
		}
	};

	var _hide = function() {
		var pages = $("#" + e_pagesId);
		var pageBack = $("#" + e_page_backId);

		_hideGallery();

		pages.find("ul.nav a").unbind("click");

		pages.css({
			"display": "none"
		});

		$("#" + e_gtId).css("display", "none");

		pages.find("div.panel div.left, div.left_back_ie6").css({
			"left": "-395px"
		});

		pages.find("div.panel div.middle").css({
			"width": "335px",
			"left": "-325px"
		});

		pages.find("div.panel div.right, div.right_back_ie6").css({
			"display": "none"
		});

		pages.removeClass();
		pageBack.removeClass();
	};

	return {
		// Public Properties
		isLoaded: function() {
			return _loaded;
		},
		type: "section",
		// Public Methods
		load: function(section, page, envOnly) {
			if (!_loaded) {
				_init();
				_loaded = true;
			}
			_show(section, page, envOnly);
		},
		show: _show,
		hide: _hide
	};
} ();