var Order = Class.create();
Order.prototype = {
  initialize: function(q_pre, s_pre, t_ele, f_ele) {
    this.q_pre = q_pre;
		this.s_pre = s_pre;
    this.t_ele = t_ele;
		this.f_ele = f_ele;
		this.products = new Array();
		this.total_price = 0;
  },
	addProduct: function(sku, myname, prd, quantity, unit_price, thumbnail) {
		var product = new Product(sku, myname, prd, quantity, unit_price);
		product.thumb = new Image();
		product.thumb.src = thumbnail;
		this.products.push(product);
		Event.observe('desc'+sku, 'mouseover', show_thumb.bindAsEventListener({thumb:product.thumb, ele:'desc'+sku}), false);
		Event.observe('desc'+sku, 'mousemove', move_thumb.bindAsEventListener({thumb:product.thumb}), false);
		Event.observe('desc'+sku, 'mouseout', hide_thumb.bindAsEventListener({thumb:product.thumb, ele:'desc'+sku}), false);
		this.total_price += parseFloat(unit_price * quantity);
	},
	updatePrices: function() {
		this.total_price = 0;
		for(var i=0; i<this.products.length; i++) {
			var q = parseInt($F(this.q_pre + this.products[i].sku));
			var subtotal = ((isNaN(q))?0:q) * this.products[i].unitPrice;
			this.total_price += subtotal;
			Element.update(this.s_pre + this.products[i].sku, subtotal.toFixed(2));
		}
		Element.update(this.t_ele, this.total_price.toFixed(2));
	},
	removeProduct: function(prd) {
		$('remove_prd').value = prd;
		$('redir').value = "";
		$(this.f_ele).submit();
	},
	submitTo: function(url) {
		$('redir').value = url;
		$(this.f_ele).submit();
	},
	placeOrder: function(url) {
		for(var i=0; i<this.products.length; i++) {
			var q = parseInt($F(this.q_pre + this.products[i].sku));
			if (q<6 || isNaN(q)) {
				alert('Minimum order per design is 6.\nPlease adjust the quantity for item number '+this.products[i].sku+'.');
				return void(0);
			}
		}
		$(this.f_ele).submit();
	}
}

var Product = Class.create();
Product.prototype = {
  initialize: function(sku, myname, prd, quantity, unit_price) {
    this.sku = sku;
		this.myname = myname;
    this.prd = prd;
		if (quantity == '') quantity = '0';
    this.quantity = quantity;
		this.quantityField = 'q'+this.sku;
		this.unitPrice = unit_price;
  },
	getPreText: function() {
		return (this.quantity >= 6) ? 'THIS ITEM HAS BEEN<br />ADDED TO YOUR ORDER' : 'ORDER THIS ITEM';
	},
	getOrderText: function(is_long) {
		if (is_long) return ((this.quantity >= 6) ? 'UPDATE' : 'ADD TO') + ' ORDER';
		else return (this.quantity >= 6) ? 'UPDATE' : 'ADD';
	},
  getPreHtml: function() {
		var html = '<b><a href="#" id="pre-'+this.sku+'-link">';
		html += this.getPreText();
		html += '</a></b>';
		return html;
  },
	getOrderHtml: function() {
		var html = '<form action="product_handler.php" method="POST"><input type="hidden" name="p" value="add" /><input type="hidden" name="prd" value="'+this.prd+'" />Quantity: &nbsp;<input type="text" name="quantity" value="6" class="quantity" maxlength="3" id="q'+this.sku+'" /> <b><a href="#" onclick="' + this.myname +'.post();return false;" id="order-'+this.sku+'-link">';
		html += this.getOrderText(false);
		html += '</a></b></form>';
		return html;
	},
	getOrderPopHtml: function() {
		var html = '<form action="product_handler.php" method="GET"><input type="hidden" name="p" value="add" /><input type="hidden" name="prd" value="'+this.prd+'" /><br />Quantity: &nbsp;<input type="text" name="quantity" value="6" class="quantity" maxlength="3" id="q'+this.sku+'" /><br /><br /><b><a href="#" onclick="' + this.myname +'.post();return false;" id="order-'+this.sku+'-link">';
		html += this.getOrderText(true);
		html += '</a><br /><a href="#" onclick="qPop.close(4);return false;">CANCEL</a></b></form>';
		return html;
	},
	getWaitHtml: function() {
		var html = 'Please wait...';
		return html;
	},
	resizePop: function() {
	},
	start: function() {
		document.write('<div id="pre-'+this.sku+'">' + this.getPreHtml() + '</div>');
		document.write('<div id="order-'+this.sku+'" style="display:none;">' + this.getOrderHtml() + '</div>');
		document.write('<div id="wait-'+this.sku+'" style="display:none;">' + this.getWaitHtml() + '</div>');
		this.hasOrderDiv = true;
		Event.observe('pre-'+this.sku+'-link', 'click', this.order.bindAsEventListener(this), true);
	},
	order: function(e) {
		if (typeof(qPop) == 'undefined') {
			Element.update('order-'+this.sku+'-link', this.getOrderText());
			Element.hide('pre-'+this.sku);
			Element.show('order-'+this.sku);
		} else {
			if (this.hasOrderDiv) {
				Element.remove('order-'+this.sku);
				this.hasOrderDiv = false;
			}
			qPop.clonePositionFrom('pre-'+this.sku+'-link');
			qPop.showText(this.getOrderPopHtml());
			qPop.expandTo(200, 112, 4, '');
		}
		Event.observe('q'+this.sku, 'keypress', no_submit_on_enter, true);
		$(this.quantityField).value = Math.max(this.quantity, 6);
		Event.stop(e);
	},
	post: function() {
		if ((parseInt($F(this.quantityField)) >= 6) && (parseInt($F(this.quantityField)) <= 999)) {
			this.quantity = $F(this.quantityField);
			add_product(this.prd, this.quantity, this.myname);
			if (typeof(qPop) == 'undefined' || !qPop.isOpen) {
				Element.hide('order-'+this.sku);
			} else {
				qPop.close(4);
				Element.hide('pre-'+this.sku);
			}
			Element.show('wait-'+this.sku);
		} else {
			alert("Quantity must be a number between 6 and 999");
			this.reset();
		}
	},
	reset: function() {
		Element.update('pre-'+this.sku+'-link', this.getPreText());
		Element.hide('wait-'+this.sku);
		if ((typeof(qPop) == 'undefined' || !qPop.isOpen) && ($('order-'+this.sku) != null)) {
			Element.hide('order-'+this.sku);
		}
		Element.show('pre-'+this.sku);
	}
}
var Popup = Class.create();
Popup.prototype = {
  initialize: function(ele, contentContainer) {
		this.ele = ele;
		this.isOpen = false;
		this.contentContainer = contentContainer;
		this.framesLeft = 0;
		this.timeoutId = 0;
	},
	clonePositionFrom: function(ele) {
		Position.clone(ele, this.ele);
		var dims = Element.getDimensions(this.ele);
		this.old_w = dims.width;
		this.old_h = dims.height;
	},
	showText: function(txt) {
		Element.update(this.contentContainer, txt);
	},
	expandTo: function(w, h, frames, afterExpand) {
		Element.show(this.ele)
		this.isOpen = true;
		if (this.framesLeft == 0) {
			this.totalFrames = frames;
			this.originalY = parseInt($(this.ele).style.top);
		}
		this.framesLeft = frames;
		if (this.framesLeft > 0) {
			var dims = Element.getDimensions(this.ele);
			var new_w = Math.round((w - dims.width) / this.framesLeft) + dims.width;
			var new_h = Math.round((h - dims.height) / this.framesLeft) + dims.height;
			$(this.ele).style.width = new_w + "px";
			$(this.ele).style.height = new_h + "px";
			var new_y = Math.round(((h - this.old_h) * ((this.framesLeft-1)-this.totalFrames) / (2*this.totalFrames)) + this.originalY);
			//$(this.ele).style.left = (parseInt($(this.ele).style.left) - dx) + "px";
			$(this.ele).style.top = new_y + "px";
			this.timeoutId = window.setTimeout(this.expandTo.bind(this, w, h, this.framesLeft - 1, afterExpand), 20);
		} else {
			if (afterExpand.length > 0) eval(afterExpand);
		}
	},
	close: function(frames) {
		this.expandTo(this.old_w, this.old_h, frames, 'Element.hide(this.ele);qPop.isOpen=false;');
	}
}

function add_product(prd, quantity, field) {
  new Ajax.Request('/wholesale/add_to_cart', {
    method: 'post',
    parameters: 'prd=' + encodeURIComponent(prd) + 
      '&quantity=' + encodeURIComponent(quantity) +
      '&field=' + encodeURIComponent(field),
    onComplete: function(x) {
      Element.show('nav-order');
      eval(x.responseText).reset();
    }
  });
}

function no_submit_on_enter(e) {
	if (e.keyCode == Event.KEY_RETURN) {
		Event.stop(e);
	}
}

function show_thumb(e) {
	if (this.thumb.complete && (qPop != "undefined")) {
		Element.show(qPop.ele);
		qPop.showText('<img src="'+this.thumb.src+'" />');
		qPop.old_w = $(qPop.ele).style.width = 12;
		qPop.old_h = $(qPop.ele).style.height = 12;
		$(qPop.ele).style.left = (Event.pointerX(e) + 20) + "px";
		$(qPop.ele).style.top = (Event.pointerY(e) + 20) + "px";
		qPop.expandTo(this.thumb.width, this.thumb.height, 4, '');
		$(this.ele).style.textDecoration = "underline";
		$(this.ele).style.cursor = "pointer";
	}
}

function move_thumb(e) {
	if (qPop.isOpen) {
		var new_top = Math.round(((this.thumb.height - qPop.old_h) * ((qPop.framesLeft)-qPop.totalFrames) / (2*qPop.totalFrames)) + Event.pointerY(e) + 20);
		$(qPop.ele).style.left = (Event.pointerX(e) + 20) + "px";
		$(qPop.ele).style.top = new_top + "px";
	}
}

function hide_thumb(e) {
	qPop.framesLeft = 0;
	window.clearTimeout(qPop.timeoutId);
	Element.hide(qPop.ele);
	$(this.ele).style.textDecoration = "none";
	$(this.ele).style.cursor = "";
}

function update_price(sku) {
}

function prepare_quantity_pop(e) {
	new Insertion.Bottom(document.body, '<div id="quantity_pop" style="display:none;"><div id="quantity_shade" style="display:none;"></div><div id="quantity_over"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td align="center"><div id="quantity_form"></div></td></tr></table></div></div>');
	qPop = new Popup('quantity_pop', 'quantity_form');
}
Event.observe(window, 'load', prepare_quantity_pop, false);

