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

crumbs.Modal.SixPack = Class.create(crumbs.Modal, {
	/**
	 * Constructor
	 */
	initialize: function () {
		this.containerId = "sixpack-modal";
		this.container = $(this.containerId);
		this.windowIsShowing = false;
		this.isFirstTime = true;
		this.zIndex = 200;
		
		this.anchor = $('sixpack_inline');
		var windowPos = this.anchor.cumulativeOffset();
		this.modalPadding = { top: 22, left: 28 };
		windowPos.top = windowPos.top - this.modalPadding.top - 10;
		windowPos.left = windowPos.left - this.modalPadding.left;
		//console.dir(windowPos);
		var options = {
			className: "sixpack-modal",
			top: windowPos.top,
			left: windowPos.left,
			width: 187,
			height: 455,
			zIndex: this.zIndex,
			showEffect: Effect.Appear,
			hideEffect: Effect.Fade
		};

		var myOptions = Object.clone(this.options);
		// set Object options
		for (var i in options) {
			myOptions[i] = options[i];
		}
		myOptions['destroyOnClose'] = false;
		myOptions['onClose'] = this.onHideModal.bind(this);
		
		this.window = new Window(this.containerId, myOptions);
		
		this.initialOffset = windowPos;
		//if (!navigator.appVersion.match('MSIE 6.')) {  // this seems to work in IE6
			//console.log("Initial Offset:"+this.initialOffset.top + ","+this.initialOffset.left);
			//this.initialOffset = this.element.positionedOffset();
			this.eventScrollResize = this.monitorScrollLocation.bindAsEventListener(this);
			Event.observe(window, 'scroll', this.eventScrollResize);
	    	Event.observe(window, 'resize', this.eventScrollResize);
		//}
		
		this.numProducts = 0;
		this.productArray = null;
		
		this.dragOptions = {
					onHover: this.dragHover,
					hoverclass:'target_hover',
					onDrop: this.dragDrop  };
		this.droppable = Droppables.add($(this.containerId), this.dragOptions);
		
		this.eventClearAll = null;
		this.eventAddToOrder = null;
		this.window.setContent('sixpack_template_empty');
	},

	/*
	setContent: function() {
		this.window.getContent().innerHTML = "";
		if(this.filterTags)
			this.window.getContent().appendChild(this.filterTags);
		if(this.popularTags)
			this.window.getContent().appendChild(this.popularTags);
	},*/

	showModal: function () {
		this.addingToCart = 0;
		this.window.show();
		screenManager.trackEvent("SixPack Modal", "Open");
		$(this.containerId + "_content").setStyle({width: "auto"});
		$(this.containerId).setStyle({zIndex: this.zIndex});
		this.monitorScrollLocation();
		this.hideNonconfigurables();
	},
	
	onHideModal: function () {
		this.showAllProducts();
	},
	
	hideNonconfigurables: function () {
		var products = screenManager.getCatalog().getProducts();
		var count = parseInt($('number-products').innerHTML);
		
		Effect.Squish('category-description');
		for(var x=0; x<products.length; x++) {
			if(!this.canAddProduct(products[x])) {
				products[x].element.addClassName('nonconfigurable');
				count--;
			}
		}
		
		//this "tricks" the person into thinking the products are sliding out
		setTimeout("$$('.nonconfigurable').invoke('hide');", 500);
		$('number-products').update(count);
	},
	
	showAllProducts: function () {
		var products = screenManager.getCatalog().getProducts();
		$('number-products').update(products.length);	
		
		//this "tricks" the person into thinking the products are sliding in
		Effect.Grow('category-description', { direction:'top-left' });		
		setTimeout("$$('.nonconfigurable').invoke('show');", 500);
	},
	
	addProduct: function(product) {
		if(this.numProducts==6) 
			return false;
		else if(this.numProducts==0) {
			this.productArray = new Array();
		}

		if (this.canAddProduct(product)) { 
			screenManager.trackEvent("SixPack Modal", "Product Added", product.properties.name);
			this.productArray[this.numProducts] = product;
			this.updateModal();
			this.numProducts++;
			return true;
		}
		return false;
	},

	canAddProduct: function (product) {
		if (product && product.properties && product.properties.signature_id && !product.properties.is_collection) {
			return true;
		}
		return false;
	},
	
	clearProducts: function() {
		this.numProducts = 0;
		this.productArray = null;
		
		var windowElm = $(this.containerId);
		var imageList = windowElm.select(".sixpack-pan");
		var nameList = windowElm.select(".sixpack-list");
		imageList = imageList[0];
		nameList = nameList[0];
		
		imageList.innerHTML = "";
		nameList.innerHTML = "";
		
		this.updateQuantities();
	},
	
	addToOrder: function() {
		if(this.addingToCart) return false;
		if(this.numProducts != 6) return false;		
		Effect.Fade($(this.containerId));
		this.addingToCart = 1;
		screenManager.trackEvent("SixPack Modal", "Add to Cart");
		screenManager.getCart().addBundleToCart(this.productArray);
	},
	
	updateModal: function() {
		if(this.isFirstTime) {
			//switch to the other template
			this.window.setContent("sixpack_template");
			//attach listener to "Clear All"
			var elmClearAll = $(this.containerId).select(".clearall");
			elmClearAll = elmClearAll[0];
			this.eventClearAll = this.clearProducts.bindAsEventListener(this);
			Event.observe(elmClearAll, "click", this.eventClearAll);
			
			var elmAddToOrder = $(this.containerId).select(".add-to-order");
			elmAddToOrder = elmAddToOrder[0];
			//attach listener to Add To Order button
			this.eventAddToOrder = this.addToOrder.bindAsEventListener(this);
			Event.observe(elmAddToOrder, "click", this.eventAddToOrder);
			
			/* Suppress non-numeric input values. Doesn't work, so
			i'm just assuming 1 if you put NaN
			var elmInput = $("sixpack_quantity");
			this.eventInputKeyPress = this.inputKeyPress.bindAsEventListener(this);
			Event.observe(elmInput, 'keydown', this.eventInputKeyPress);
			*/
			this.isFirstTime = false;
		}
		if(this.numProducts==0) {
		}
		this.drawProductArray();
		
		this.updateQuantities(true);
		
		/*
		var imageList = $(this.containerId).select(".sixpack-pan");
		imageList = imageList[0];
		screenManager.getSixpack().setInlineContent("<ul>"+imageList.innerHTML+"</ul>");
		*/
	},
	
	drawProductArray: function() {
		var product = this.productArray[this.numProducts];
		//console.dir(product);
		
		var windowElm = $(this.containerId);
		var imageList = windowElm.select(".sixpack-pan");
		var nameList = windowElm.select(".sixpack-list");
		imageList = imageList[0];
		nameList = nameList[0];
		
		var imgLiNode = document.createElement('li');
		var imgNode = document.createElement('img');
		imgNode.setAttribute('src', product.properties.image_white);
		imgLiNode.appendChild(imgNode);
		imgLiNode.className = "cupcake";
		imageList.appendChild(imgLiNode);
		
		var nameLiNode = document.createElement('li');
		var nameSpanNode = document.createElement('span');
		var priceSpanNode = document.createElement('span');
		nameSpanNode.className = "name";
		priceSpanNode.className = "price";
		nameSpanNode.innerHTML = product.properties.name;
		priceSpanNode.innerHTML = "$"+product.properties.price;
		nameLiNode.appendChild(nameSpanNode);
		nameLiNode.appendChild(priceSpanNode);
		nameList.appendChild(nameLiNode);
	},
	
	updateQuantities: function(newAdded) {
		
		var windowElm = $(this.containerId);
		var elmNeeded = windowElm.select(".num-needed span");
		var elmHave = windowElm.select(".total-amount span");
		var elmCost = windowElm.select(".total-cost");
		elmNeeded = elmNeeded[0];
		elmHave = elmHave[0];
		elmCost = elmCost[0];
		
		if(newAdded)
			quant = this.numProducts+1;
		else
			quant = 0;
			
		elmNeeded.innerHTML = 6 - quant;
		elmHave.innerHTML = quant;
		
		var totalCost = 0;
		for(var i=0; i<quant; i++) {
			totalCost = totalCost + parseFloat(this.productArray[i].properties.price);
		}
		//console.log(totalCost.toFixed(2));
		elmCost.innerHTML = "$"+totalCost.toFixed(2);
		
		/*
		if(this.numProducts+1==6) {
			var elmAddToOrder = windowElm.select(".add-to-order");
			elmAddToOrder = elmAddToOrder[0];
			//attach listener to Add To Order button
			this.eventAddToOrder = this.addToOrder.bindAsEventListener(this);
			Event.observe(elmAddToOrder, "click", this.eventAddToOrder);
		}
		*/
	},

	/**
	 * Not supported for this modal type.
	 */
	load: function() {
		return false;
	}, 
	
	monitorScrollLocation: function() {
		if(!this.window.visible) return;
		
		var elm = $(this.containerId);
        var modalPos = Element.cumulativeScrollOffset(elm);
        //console.log("Cumulative Offset (top,left): " + modalPos.top + "," + modalPos.left);
        
        var anchorPos = this.anchor.cumulativeOffset();
        
        var newPos = { top: modalPos.top, left: anchorPos.left - this.modalPadding.left };
        
//		if (!this.initialOffset)
//			this.initialOffset = {top: 0, left: 0};

        if(anchorPos.top < modalPos.top+this.modalPadding.top) {
        	newPos.top = modalPos.top - this.initialOffset.top + this.modalPadding.top + 20;
        } else if (anchorPos.top >= modalPos.top+this.modalPadding.top) {
        	newPos.top = this.initialOffset.top;
        }

		new Effect.Move(elm, { x: newPos.left, y: newPos.top, mode:'absolute', duration: 0.3});
	},
	
	dragHover: function(dragElm, dropElm, evt) {
		
	},
	
	dragDrop: function(dragElm, dropElm, evt) {
		var products = screenManager.getCatalog().getProducts();
		var product = products[parseInt(dragElm.getAttribute('index'))];
		//if (screenManager.getSixpack().modal.canAddProduct(product)) 
		screenManager.getSixpack().modal.addProduct(product);
	},
	
	inputKeyPress: function(event) {
		if(!((event.keyCode >= 48 && event.keyCode <= 57)
				||(event.keyCode >= 96 && event.keyCode <= 105)
				||(event.keyCode == 8 ) ||(event.keyCode == 9)
				|| (event.keyCode == 12) || (event.keyCode == 27)
				|| (event.keyCode == 37) || (event.keyCode == 39)
				|| (event.keyCode == 46) )) {
			//console.log("Alpha-numeric characters and spaces allowed: "+event.keyCode);
			//Event.stop(event);
			return false;
		}
		
		return true;
	}
});
