jQuery(document).ready(function() {
	// reset form value on page reload
	document.getElementById("productOptionForm").reset();
	
	jQuery("#maintab a").click(initializeTabs);
	
	jQuery("a[rel='bubble']").each(initializeBenefitBubble);
	
	jQuery("#ymal input").click(initializeYMAL);
	
	jQuery(".productoptions .matrix").each(initializeMatrix);
	
	jQuery(".productoptions .list input").click(initializeOptionList);
	
	jQuery(".productoptions").each(initializeOptions);
});

function initializeTabs() {
	jQuery("#maintab a").removeClass("selected");
	jQuery(this).addClass("selected");
	var contentID = jQuery(this).attr("rel");
	jQuery(".tabcontent").hide();
	jQuery("#" + contentID).show();
}

function initializeMatrix() {
	jQuery("img", this).hover(
		function() {
			var selectedName = jQuery(this).attr("alt");
			var parent = jQuery(this).parents(".productoptions");
			parent.children(".selectedName").html(selectedName);
		},
		function() {
			var parent = jQuery(this).parents(".productoptions");
			var selectedName = "";
			if (jQuery(".selected", parent).is("li"))
				selectedName = jQuery(".selected", parent).children("img").attr("alt");
			parent.children(".selectedName").html(selectedName);
		}
	);
	jQuery("img", this).click(
		function() {
			jQuery(this).parent("li").siblings().removeClass("selected");
			jQuery(this).parent("li").addClass("selected");
			var id = jQuery(this).parent("li").attr("id");
			var type = id.split("_")[0];
			var cd = id.split("_").pop();
			jQuery(this).parents(".productoptions").children("input").val(id.trim());
			
			product.options[type] = cd;
			updateSelected();
		}
	);
}

function initializeOptionList() {
	var name = jQuery(this).attr("name");
	var value = jQuery(this).val();
	
	product.options[name] = value;
	
	var selectedName = jQuery(this).siblings("span").html();
	var parent = jQuery(this).parents(".productoptions");
	parent.children(".selectedName").html(selectedName);
			
	updateSelected();
}

function initializeOptions() {
	// don't hide 1st option
	if (jQuery(".productoptions").get(0) != this) jQuery("ul", this).hide();
	
	jQuery("h5", this).click(function() {
		var parent = jQuery(this).parent(".productoptions");
		
		if (jQuery("ul", parent).css("display") == "block") {
			jQuery("ul", parent).slideUp("fast");
		}
		else {
			parent.siblings(".productoptions").children("ul").slideUp("fast");
			jQuery("ul", parent).slideDown("fast");
		}
	});
}

function initializeYMAL() {
	if (this.checked) {
		for (i = 0; i < product.ymal.length; i++) {
			if (product.ymal[i] == this.value) return;
		}
		product.ymal.push(this.value);
	}
	else {
		var temp_ymal = new Array();
		for (i = 0; i < product.ymal.length; i++) {
			if (product.ymal[i] != this.value) {
				temp_ymal.push(product.ymal[i]);
			}
		}
		product.ymal = temp_ymal;
	}
}

function initializeBenefitBubble() {
	var largeImageSRC = jQuery(this).attr("href");
	var altText = jQuery("span", this).html();
	jQuery(this).removeAttr("href");
	jQuery(this).hover(
		function() {
			var bubbleDiv = '<div class="benefitBubble"><img src="' + largeImageSRC + '" alt="' + altText + '" /></div>';
			jQuery("body").append(bubbleDiv);
			
			var width = jQuery("img", this).width();
			var height = jQuery("img", this).height();
			var offset = jQuery("img", this).offset();
			
			var infoBubbleWidth = 300;
			var infoBubbleHeight = 335;
			
			var top = offset.top - infoBubbleHeight;
			var left = offset.left - (infoBubbleWidth - width) / 2;
			
			jQuery(".benefitBubble").css({opacity: 0.9, top: top, left: left});
			jQuery(".benefitBubble").fadeIn();	
		},
		function() {
			jQuery(".benefitBubble").remove();
		}
	);
}

var currentimagemode = 'product';
function productimageview(action,imageobj,newimage, imagemode){
    if (action == 'swap') {
        MM_swapImage(imageobj,'',newimage,1);
        currentimagemode = imagemode;
    }
}

function updateSelected() {
	jQuery("#productprice").addClass("loading");
	product.selectedsku = product.currentmodel 
						+ product.options.upholstery 
						+ product.options.material 
						+ product.options.color 
						+ product.options.woodfinish 
						+ product.options.size 
						+ product.options.thickness 
						+ product.options.gender
						+ product.options.piping;
						
	// hack
	if (product.selectedsku == 'HEC-DR7700KBKSL')
		product.selectedsku = 'HEC-DR7700K';
								
						
	var params = new Object();				
	params.method = "getSKUDetail";
	params.DSN = DSN;
	params.item_cd = product.selectedsku;
	
	jQuery.post(componentURL, params, function(data, textStatus) {
		if (textStatus == "success") {
			var jsonObject = wddxToJSON(data);
			product.selecteditemid = jsonObject.ITEM_ID;

			jQuery("#price").html(jsonObject.ITEM_AT);
			if (jsonObject.ITEM_AT != jsonObject.SALE_AT) {
				jQuery("#salesprice").css("display", "inline");
				jQuery("#sale_at").html(jsonObject.SALE_AT);
				jQuery("#discountpercent").html(parseInt(jsonObject.DISCOUNT));
			}
			else {
				jQuery("#salesprice").css("display", "none");
			}
			if (jsonObject.ITEM_ID != 0) {
				jQuery("#addcartbutton").css("display", "inline");
				jQuery("#seemoreoptions").css("display", "none");
			}
			else {
				jQuery("#price").html("$0.00");
				jQuery("#addcartbutton").css("display", "none");
				jQuery("#seemoreoptions").css("display", "inline");
			}
			jQuery("#productprice").removeClass("loading");
		}
	});
}

function wddxToJSON(xmlString) {
	var parser = new DOMParser();
	var doc = parser.parseFromString(xmlString, "text/xml");
	var variables = doc.getElementsByTagName("var");
	var jsonObject = new Object();

	for (i = 0; i < variables.length; i++) {
		var key = variables[i].getAttribute("name");
		if (typeof(variables[i].text) != "undefined") {
			jsonObject[key] = variables[i].text.trim(); // ie
		}
		else {
			jsonObject[key] = variables[i].textContent.trim();
		}
	}
	return jsonObject;
}

/* *******************************
	add to cart
******************************* */

function addtocart() {
	jQuery("#productprice").addClass("loading");
	
    // when user add item to cart, turn off the cache of the mini shopping cart 
    enableCache = false;
    
	var params = new Object();
	params.method = "addToCart";
    params.OMS = OMS;
    params.DSN = DSN;	
    params.TID = TID;
	params.item_id = product.selecteditemid;
	params.group_id = product.selectedmodelid;
	params.ymals = product.ymal.join(",");
	for (option in product.options) {
		params[option] = product.options[option];
	}
	params.flag_cd = "YES";

	jQuery.post(componentURL, params, function(data, textStatus) {
		jQuery("#productprice").removeClass("loading");
		if (textStatus == "success") {
			var cartElem = jQuery("#shoppingCart a").get(0);
			ajax_showTooltip(miniCartURL, cartElem);
			/*
			if (params.ymals.trim() == '') {
				displayMsgBox("Item Added", "The selected product has been added to your shopping cart.");
			}
			else {
				displayMsgBox("Item Added", "The selected product and the selected associated products have been added to your shopping cart.");
			}
			*/
		}
	});
}   

/* *******************************
	utility functions
******************************* */

function displayMsgBox(title, msg) {
	var boxWidth = 300;
	var boxHeight = 150;
	
	var msgBoxBG = jQuery('<div id="msgBoxBG"></div>');
	var msgBox = jQuery('<div id="msgBox"><h1></h1><p></p><a id="msgBoxClose" href="javascript:closeMsgBox()">Close</a></div>');
	var bgWidth = jQuery(document).width();
	var bgHeight = jQuery(document).height();

	var bodyWidth = jQuery("body").width();
	var leftOffset = (bodyWidth - boxWidth) / 2;
	var topOffset = getViewpointTop() + ((getViewpointHeight() - boxHeight) / 2);
	
	msgBoxBG.css({"position": "absolute"
				, "z-index": 100
				, "left": 0
				, "top": 0
				, "background-color": "black"
				, "width": bgWidth
				, "height": bgHeight
				, "opacity": 0.7});
	msgBox.css({"position": "absolute"
				, "z-index": 101
				, "left": leftOffset
				, "top": topOffset
				, "background-color": "white"
				, "width": boxWidth
				, "height": boxHeight
				, "border": "1px solid black"});
	msgBox.children("h1").html(title);
	msgBox.children("p").html(msg);
	msgBox.children("#msgBoxClose").css({"float": "right", "margin-top": "30px", "padding": "10px"});
	jQuery("body").append(msgBoxBG);
	jQuery("body").append(msgBox);
}

function closeMsgBox() {
	jQuery("#msgBoxBG").remove();
	jQuery("#msgBox").remove();
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

if (typeof(DOMParser) == 'undefined') {
	DOMParser = function() {}
	DOMParser.prototype.parseFromString = function(str, contentType) {
		if(typeof(ActiveXObject) != 'undefined') {
			var xmldata = new ActiveXObject('MSXML.DomDocument');
			xmldata.async = false;
			xmldata.loadXML(str);
			return xmldata;
		} else if(typeof(XMLHttpRequest) != 'undefined') {
			var xmldata = new XMLHttpRequest;
			if(!contentType) {
				contentType = 'application/xml';
			}
			xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);
			if(xmldata.overrideMimeType) {
				xmldata.overrideMimeType(contentType);
			}
			xmldata.send(null);
			return xmldata.responseXML;
		}
	}
}