/**
 * Product.js
 * eFashionSolutions Meteor Library
 * 2008.05.19
 *
 * Description: Handles the JS for the product detail pages
 * TJ Eastmond <tj.eastmond@gmail.com>
 */

EFS.ProductDetail = {};

EFS.ProductDetail.change = function(productid, code) {
	var sizesBox = $(productid + '_size');
	var quantityBox = $(productid + '_quantity');

	if (!code.match(/\/| |-/g)) {
		if (jsonPage[productid]['colors'][code]) {
			code = jsonPage[productid]['colors'][code];
		}
	}

	if ($(productid + '_image')) {
		$(productid + '_image').src = jsonPage[productid][code]['images']['ex'];
	}
	$(productid + '_color').value = code;

	if (sizesBox && sizesBox.type != 'hidden') {
		var selectedSize = sizesBox.value;
		var sizes = jsonPage[productid][code]['sizes'];
		sizesBox.options.length = 0;

		for (var i = 0; i < sizes.length; ++i) {
			sizesBox.options[i] = new Option(sizes[i],sizes[i],(sizes[i] == selectedSize)? true : false);
		}
	}

	if (quantityBox) {
		EFS.ProductDetail.updateQuantity(productid);
	}
};

EFS.ProductDetail.openZoomView = function(productid) {
	var color = $(productid + '_color').value;
	window.open(jsonPage[productid][color]['images']['zoom'], 'zoomViewer', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=495');
};

EFS.ProductDetail.updateQuantity = function(productid) {
	var limit = 20;
	var colorCode = $(productid + '_color').value;
	var sizesValue = $(productid + '_size').value;
	var quantityBox = $(productid + '_quantity');
	var inv = (jsonPage[productid][colorCode]['inv'][sizesValue] > limit)
		? limit
		: jsonPage[productid][colorCode]['inv'][sizesValue];
	var selectedQuantity = (parseInt(quantityBox.value) > inv)? inv : parseInt(quantityBox.value);
	var numOptions = quantityBox.options.length;
	for (var i = 0; i < numOptions; i++) {
		quantityBox.remove(0);
	}
	for (var i = 1; i <= inv; ++i) {
		quantityBox.options[i-1] = new Option(i,i,(i == selectedQuantity)? true : false);
	}
	quantityBox.selectedIndex = selectedQuantity - 1;
};

EFS.ProductDetail.addItemToCart = function(productid, color, size, quantity, optional, callBack) {
	var vars = 'productid=' + productid + '&color=' + color + '&size=' + size + '&quantity=' + quantity + '&optional=' + optional;
	new Ajax.Request('cart/ajaxadd/', {
		method: 'post',
		parameters : vars,
		onSuccess: function(t) { callBack(t); }
	});
};

EFS.ProductDetail.quicklookAdd = function(productInfo) {
	EFS.ProductDetail.addItemToCart(
	productInfo.productid,
	productInfo.color,
	productInfo.size,
	productInfo.quantity,
	productInfo.optional,
	function(t) {

	});
};

EFS.ProductDetail.submitMulti = function() {
	$$('.productForm').each(function(element) {
		var parts = element.id.split('_');
		$('color_' + parts[1]).value = $(parts[1] + '_color').value;
		$('size_' + parts[1]).value = $(parts[1] + '_size').value;
		$('quantity_' + parts[1]).value = $(parts[1] + '_quantity').value;
	});

	$('multiProductForm').submit();
}

EFS.ProductDetail.refreshFlash = function(productid, oldcolor, color) {
	if (flashRefreshOldColor) {
		oldcolor = flashRefreshOldColor;
	}
	var objectFlashVars = '';
	if ($('refreshFlashOnColor') && $($('refreshFlashOnColor').value) ) {
		$$('object#'+$('refreshFlashOnColor').value+' param').each(function(el){
			var paramName = el.readAttribute('name');
			if (paramName == 'flashvars' || paramName == 'FlashVars') {
				el.writeAttribute('value', el.readAttribute('value').replace(oldcolor,color));
				objectFlashVars = el.readAttribute('value');
			} else if (el.readAttribute('name') == 'Movie') {
				el.writeAttribute('value', el.readAttribute('value').replace(oldcolor,color));
			} else if (el.readAttribute('name') == 'Src') {
                                el.writeAttribute('value', el.readAttribute('value').replace(oldcolor,color));
                        } else if (el.readAttribute('name') == 'Play') {
                                el.writeAttribute('value', 1);
                        }
		});
		var ancestors = $($('refreshFlashOnColor').value).ancestors();
		var flashContent = ancestors[0].innerHTML;
		if (Prototype.Browser.IE && objectFlashVars) {
			flashContent = flashContent.replace("\"FlashVars\" VALUE=\"\"","\"FlashVars\" VALUE=\"" + objectFlashVars + "\"");
                }
		ancestors[0].update(flashContent);
		flashRefreshOldColor = color;
	}
}

EFS.ProductDetail.init = function() {
	$$('.detailSwatch').each(function(element) {
		var parts = element.id.split("_");
		var numParts = parts.length;

		// account for underscores in product_id
		if (numParts > 2) {
			numParts--;
			var compositeProductId = '';
			for (var i = 0; i < numParts; i++) {
				compositeProductId = compositeProductId + parts[i] + '_';
			}
			parts[0] = compositeProductId.substr(0,compositeProductId.length-1);
			parts[1] = parts[numParts]
		}
		Event.observe(element, 'click', function(e) {
			var oldcolor = $(parts[0] + '_color').value;
			EFS.ProductDetail.change(parts[0],parts[1]);
			Event.stop(e);
			EFS.ProductDetail.refreshFlash(parts[0],oldcolor,parts[1]);
		});
	});

	$$('.detailColorsDropdown').each(function(element) {
		element.onchange = function() {
			var parts = this.id.split("_");
			var numParts = parts.length;

			// account for underscores in product_id
			if (numParts > 2) {
				numParts--;
				var compositeProductId = '';
				for (var i = 0; i < numParts; i++) {
					compositeProductId = compositeProductId + parts[i] + '_';
				}
				parts[0] = compositeProductId.substr(0,compositeProductId.length-1);
				parts[1] = parts[numParts]
			}
			var color = '';
			if (jsonPage[parts[0]][this.value]['code']) {
				color = jsonPage[parts[0]][this.value]['code'];
			} else {
				color = this.value;
			}
			var oldColor = '';
                        if (jsonPage[parts[0]][this.value]['code']) {
                                oldColor = jsonPage[parts[0]][flashRefreshOldColor]['code'];
                        } else {
                                oldColor = flashRefreshOldColor;
                        }
			EFS.ProductDetail.change(parts[0],color);
			EFS.ProductDetail.refreshFlash(parts[0],oldColor,color);
		};
	});

	$$('.detailSizesDropdown').each(function(element) {
		element.onchange = function() {
			var parts = this.id.split("_");
			var numParts = parts.length;

			// account for underscores in product_id
			if (numParts > 2) {
				numParts--;
				var compositeProductId = '';
				for (var i = 0; i < numParts; i++) {
					compositeProductId = compositeProductId + parts[i] + '_';
				}
				parts[0] = compositeProductId.substr(0,compositeProductId.length-1);
				parts[1] = parts[numParts]
			}
			EFS.ProductDetail.updateQuantity(parts[0]);
		};
	});

	$$('input.purchaseOutfit').each(function(element) {
		Event.observe(element, 'click', function(e) {
			EFS.ProductDetail.submitMulti();
		});
	});

	$$('img.productImage').each(function(element) {
		Event.observe(element, 'click', function(e) {
			var productid = this.id.replace('_image','');
			EFS.ProductDetail.openZoomView(productid);
			Event.stop(e);
		});
	});

	$$('a.zoomLink').each(function(element) {
		Event.observe(element, 'click', function(e) {
			var productid = this.id.replace('_zoom','');
			EFS.ProductDetail.openZoomView(productid);
			Event.stop(e);
		});
	});

	if (typeof(Shadowbox) != 'undefined') {
		Shadowbox.init({'enableKeys': false, 'modal': false});
	}
};

EFS.Products = {

	addToWishlist : function(el, id, shadowbox) {
		a = {};
		a.productid = id;
		a.wishlistMetaId = el.value;
		a.color = $(id + '_color').value;
		a.size =  $(id + '_size').value;
		a.quantity =   $(id + '_quantity').value;
		a.length = '';
		a.optional = '';
		a.fromDetail = true;

		//alert(a.quantity);
		//return;
		//	target = (el.value != 'new') ? '/cart/addwishlistitem/' : '/cart/createwishlist';
		if (a.wishlistMetaId) {
			EFS.doAjax('/cart/addwishlistitem/', 'pars=' + $H(a).toJSON(), function(transport){EFS.Products.addToWishlistCallback(transport, $H(a), shadowbox)});
		}
		//alert($H(a).toJSON())
	},


	addGiftcardToWishlist : function(el, id) {
		a = {};
		a.productid = $('giftcard_productid').value;
		a.wishlistMetaId = el.value;
		a.color = '';
		a.size =  '';
		a.quantity =   $('giftcard_quantity').value;
		a.length = '';
		a.optional = '';
		//a.fromDetail = true;
		a.giftcard = true;

		//alert(a.quantity);
		//return;
		//	target = (el.value != 'new') ? '/cart/addwishlistitem/' : '/cart/createwishlist';
	//	alert($H(a).toJSON());return false;
		EFS.doAjax('/cart/addwishlistitem/', 'pars=' + $H(a).toJSON(), function(transport){EFS.Products.addToWishlistCallback(transport, $H(a), 0)});
		//alert($H(a).toJSON())
	},

	addToWishlistCallback : function(transport, argHash, shadowbox) {
		//alert(transport.responseText)
		if(transport.responseText != 'false'){
			if(transport.responseText == 'new'){
				if(shadowbox == 1) {
					parent.location = '/cart/createwishlist/' + transport.responseText
				} else {
					document.location = '/cart/createwishlist/' + transport.responseText
				}
			} else {
				if(shadowbox == 1) {
					parent.location = '/cart/wishlist/' + transport.responseText
				} else {
					document.location = '/cart/wishlist/' + transport.responseText
				}
			}
		}
	},

	addToWishlistNoSignIn : function(el, id, shadowbox) {
		a = {};
		a.productid = id;
		a.wishlistMetaId = el.value;
		a.color = $(id + '_color').value;
		a.size =  $(id + '_size').value;
		a.quantity =   $(id + '_quantity').value;
		a.length = '';
		a.optional = '';
		a.fromDetail = true;

		EFS.doAjax('/cart/ajaxaddwishlistitem/', 'pars=' + $H(a).toJSON(),function(transport){EFS.Products.addToWishlistNoSignInCallback(transport, shadowbox)});
	},


	addGiftcardToWishlistNoSignIn : function(el, id) {
		a = {};
		a.productid = $('giftcard_productid').value;
		a.wishlistMetaId = el.value;
		a.color = '';
		a.size =  '';
		a.quantity =   $('giftcard_quantity').value;
		a.length = '';
		a.optional = '';
		//a.fromDetail = true;
		a.giftcard = true;

		//alert(a.quantity);
		//return;
		//	target = (el.value != 'new') ? '/cart/addwishlistitem/' : '/cart/createwishlist';
	//	alert($H(a).toJSON());return false;
		EFS.doAjax('/cart/ajaxaddwishlistitem/', 'pars=' + $H(a).toJSON(),EFS.Products.addToWishlistNoSignInCallback);
		//alert($H(a).toJSON())
	},


	tellAFriend : function(id) {
		var win = window.open("/product/0/tellafriend/" + id , "detail", "width=300,height=425,scrollbars=no,resizable=0")
	},

	tellAFriendCustom : function(id, width, height) {
		var win = window.open("/product/0/tellafriend/" + id , "detail", "width=" + width + ",height=" + height + ",scrollbars=no,resizable=0")
	},

	addToWishlistNoSignInCallback : function(transport, shadowbox) {
		//alert(transport.responseText)
		if(transport.responseText == 'true') {
			if(shadowbox == 1) {
				parent.location = '/account/';
			} else {
				document.location = '/account/';
			}

		}
	}
}
EFS.onDomReady(EFS.ProductDetail.init);

