//setup the namespace
if (typeof crumbs == "undefined" || !crumbs) {
    var crumbs = {};
}

crumbs.ScreenManager = Class.create();

crumbs.ScreenManager.prototype = {
	initialize: function() {
		this.dragTargets = new Array();
		this.cart = null;
		this.catalog = null;
		this.sixpack = null;
		this.celebrations = null;
		this.productModal = null;
		this.giftmessageModal = null;
		this.contentModal = null;
		this.locationModal = null;
		this.crossSellProduct = null;
		this.faq = null;
		this.tree = null
		this.filter = null;
		this.staticBlockModalLinks = null;
		this.message = null;
		this.callouts = null;
		this.location = null;
		this.originalPageTitle = document.title;
		
		this.initProductModal();
		this.initGiftmessageModal();
		this.initLocationModal();
		this.initCart();
		this.initCatalog();
		this.initContentModal();
		this.initCollapsibleList();
		this.initTree();
		this.initFilter();
		this.initStaticBlockModals();
		this.initMessage();
		this.initCallouts();
		this.initLocation();

		this.setCmsNavCurrent();
		this.adjustColumnHeights();
		Event.observe(window, "resize", this.adjustColumnHeights.bindAsEventListener(this));
	},
	
	initCart: function() {
		if ($("mini-cart")) {
			//console.log("Mini-cart found, initializing.");
			this.cart = new crumbs.Cart('mini-cart');
			//this.addDragTarget(this.cart);
		}
	},
	
	initCatalog: function() {
		if($("product-list-table")) {
			//console.log("catalog found, initializing.");
			this.catalog = new crumbs.Catalog("product-list-table");
		}
		if($("sixpack_inline")) {
			//console.log("sixpack configurator found, initializing.");
			this.sixpack = new crumbs.SixPack("sixpack_inline");
		}
		if($("celebrations_link")) {
			if($("celebrations_callout")) {
				//console.log("celebrations link and callout found, initializing.")
				this.celebrations = new crumbs.Celebrations("celebrations_callout", "celebrations_link");
			} else {
				$("celebrations_link").setStyle({display: 'none'});
			}
		}
		/*
		if($("celebrations_callout")) {
			//console.log("celebrations found, initializing.");
			this.celebrations = new crumbs.Celebrations("celebrations_callout");
		}
		*/
	},
	
	initProductModal: function() {
		//console.log("Creating new crumbs.Modal.Product");
		this.productModal = new crumbs.Modal.Product();
	},
	
	initGiftmessageModal: function() {
		if($('giftmessage-modal-templates')) {
			//console.log("Creating new crumbs.Modal.Giftmessage");
			this.giftmessageModal = new crumbs.Modal.Giftmessage();
		}
	},

	initContentModal: function() {
		//console.log("Creating new crumbs.Modal.Content");
		this.contentModal = new crumbs.Modal.Content({destroyOnClose: false});
	},

	initLocationModal: function() {
		this.locationModal = new crumbs.Modal.Content.Location();
	},
	
	initCollapsibleList: function () {
		if ($("faq-questions")) {
			//console.log("FAQ found, initializing.");
			this.collapsibleList = new crumbs.CollapsibleList("faq-questions");
		}
	},

	initTree: function () {
		if ($("crumbs-tree")) {
			//console.log("Tree found, initializing.");
			this.tree = new crumbs.Tree("crumbs-tree");
		}
	},
	
	initFilter: function() {
		if($("pager-filter-button")) {
			//console.log("Filter found, initializing.");
			this.filter = new crumbs.Filter();
		}
	},

	initStaticBlockModals: function () {
		this.staticBlockModalLinks = $$("a.open-in-modal");
		for (var i = 0; i < this.staticBlockModalLinks.length; i++) {
			Event.observe(this.staticBlockModalLinks[i], "click", this.openStaticBlockModal.bindAsEventListener(this));
		}
	},

	initMessage: function () {
		if ($("message-container")) {
			//console.log("Message container found, initializing.");
			this.message = new crumbs.Message("message-container");
		}
	},
	
	initCallouts: function() {
		this.callouts = new Array(2);
		this.callouts['left'] = null;
		this.callouts['right'] = null;
	},

	initLocation: function () {
		this.location = new crumbs.Location();
	},

	openStaticBlockModal: function (event) {
		var link = Event.element(event);
		var modalType = link.getAttribute("modaltype") ? link.getAttribute("modaltype") : "content";
		var modal;
		switch (modalType.toLowerCase()) {
			case "location":
				modal = this.getLocationModal();
				break;
			case "content":
			default:
				modal = this.getContentModal();
		}
		modal.setUrl(link.getAttribute("url"));
		modal.load();
	},

	getCart: function() {
		return this.cart;
	},
	getCatalog: function() {
		return this.catalog;
	},
	getSixpack: function() {
		return this.sixpack;
	},
	getProductModal: function() {
		return this.productModal;
	},
	getGiftmessageModal: function() {
		return this.giftmessageModal;
	},
	getContentModal: function() {
		return this.contentModal;
	},
	getLocationModal: function() {
		return this.locationModal;
	},
	getFilter: function() {
		return this.filter;
	},
	getLocation: function() {
		return this.location;
	},
	getCallouts: function(area) {
		var areaId = "";
		if(area=='left') {
			areaId = "left-container";
		} else {
			areaId = "right-col"
		}
		if(this.callouts[area]==null) {
			var calls = $$('#'+areaId+' .box');
			this.callouts[area] = calls
		}
		return this.callouts[area];
	},
	getCelebrations: function () {
		if (this.celebrations)
			return this.celebrations;
		return null;
	},
	getMessage: function () {
		return this.message;
	},
	switchProductModal: function(product_num) {
		this.productModal.window.hide();
		this.catalog.products[product_num].onClick();
	},
	switchProductModalToId: function(myId, myUrl) {
		this.productModal.window.hide();
		modal = this.productModal;
		modal.setId(myId);
		modal.setUrl("/" + myUrl);
		modal.load();
	},
	addDragTarget: function(elm) {
		if(this.dragTargets.indexOf(elm)!=-1) return;
		this.dragTargets[this.dragTargets.size()] = elm;
	},
	removeDragTarget: function(elm) {
		//if(this.dragTargets.indexOf(elm)==-1) return;//don't think this is necessary
		this.dragTargets = this.dragTargets.without(elm);
	},
	getDragTargets: function() {
		return this.dragTargets;
	},

	setPageTitle: function (title) {
		document.title = title;
	},

	appendToPageTitle: function (append) {
		document.title += " - " + append;
	},

	restorePageTitle: function () {
		document.title = this.originalPageTitle;
	},

	/**
	 * Sets a class on the current CMS nav item.
	 */
	setCmsNavCurrent: function () {
		if ($(document.body).hasClassName("cms-page-view")) {
			if (Prototype.Browser.IE)  // see Ticket #210
				var locationPath = window.location.href.replace(/\/+$/,"");
			else
				var locationPath = window.location.pathname.replace(/\/+$/,"");  // chop off trailing slash

			var navLinks = $$("#filter-list li a");
			for (var i = navLinks.length - 1; i >= 0; i--) {
				if (locationPath.indexOf(navLinks[i].getAttribute("href").replace(/\/+$/,"")) === 0) {
					navLinks[i].addClassName("current");
					break;
				}
			}

			var subNavLinks = $$(".filter-list li a");
			for (var i = 0; i < subNavLinks.length; i++) {
				if (subNavLinks[i].getAttribute("href").replace(/\/+$/,"") == locationPath)
					subNavLinks[i].addClassName("current");
			}
		}
	},

	/**
	 * Adjusts the height of the #main or #right-container divs so the left borders on
	 * those elements extend to the bottom of the element with the greatest height.
	 */
	adjustColumnHeights: function () {
		var left = $("left-container");
		var main = $("main");
		var right = $("right-container");

		if (left && main && right) { 
			main.setStyle({minHeight: 0});
			right.setStyle({minHeight: 0});

			var leftPad = parseInt(left.getStyle("padding-top")) + parseInt(left.getStyle("padding-bottom"));
			var leftHeight = left.getHeight() - leftPad;

			var mainPad = parseInt(main.getStyle("padding-top")) + parseInt(main.getStyle("padding-bottom"));
			var mainHeight = main.getHeight() - mainPad;

			var rightPad = parseInt(right.getStyle("padding-top")) + parseInt(right.getStyle("padding-bottom"));
			var rightHeight = right.getHeight() - rightPad;

			if (leftHeight > mainHeight && leftHeight > rightHeight) {
				var newMainH = leftHeight - mainPad;
				var newRightH = leftHeight - rightPad;
				//console.log("new right height " + newH);
				main.setStyle({minHeight: newMainH.toString() + "px"});				
				right.setStyle({minHeight: newRightH.toString() + "px"});				
			}
			else if (mainHeight > rightHeight) {
				var newH = mainHeight - rightPad;
				//console.log("new right height " + newH);
				right.setStyle({minHeight: newH.toString() + "px"});
			}
			else if (mainHeight < rightHeight) {
				var newH = rightHeight - mainPad;
				//console.log("new main height " + newH);
				main.setStyle({minHeight: newH.toString() + "px"});
			}
		}
		/**
		 * Adjust the height of the threeColumnLayout divs within the main section, if present
		 */
		if(main) {
			var cols = main.select(".threeColumnLayout");
			if(cols.length>0) {
				var maxHeight = 0;
				for(var i=0; i<cols.length; i++) {
					var thisColPad = parseInt(cols[i].getStyle("padding-top")) + parseInt(cols[i].getStyle("padding-bottom"));
					var thisColHeight = cols[i].getHeight() - thisColPad;
					if(thisColHeight > maxHeight) maxHeight = thisColHeight;
				}
				for(var j=0; j<cols.length; j++) {
					cols[j].setStyle({minHeight: maxHeight.toString()+"px"});
				}
			}
		}
	},

	/**
	 * Logs an event described by the input parameters to Google Analytics.
	 *
	 * String   category The general event category (e.g. "Videos").
	 * String   action The action for the event (e.g. "Play").
	 * String   opt_label An optional descriptor for the event.
	 * Int      opt_value An optional value to be aggregated with 
	 */
	trackEvent: function (category, action, label, value) {
		if (!Object.isUndefined(pageTracker)) {
			try {
				var success = pageTracker._trackEvent(category, action, label, value);
//				if (success) 
//					console.log("Event Logged: " + category + " - " + action + " / " + label);
//				else
//					console.log("Event logging FAILED");
			}
			catch (e) {}
		}
	},

	/**
	 * Tracks a page view to Google Analytics.
	 *
	 * String   opt_pageURL Optional parameter to indicate what page URL to track metrics under. 
	 *			When using this option, use a beginning slash (/) to indicate the page URL. 
	 */
	trackPageview: function (pageUrl) {
		if (!Object.isUndefined(pageTracker)) {
			var host = window.location.protocol + "//" + window.location.host;
			if (pageUrl && pageUrl.length > host.length && pageUrl.substr(0, host.length) == host) {
				pageUrl = pageUrl.substr(host.length+1);
			}
			try {
				pageTracker._trackPageview(pageUrl);
				//console.log("Page tracked: " + pageUrl);
			}
			catch (e) {}
		}
	}
};
