var pathToImages = 'images/catalogue/';

function Style(id, parentID, code, name, desc, substyleGroupDesc, option, price, imageThumb, imageDetail, imageAlt, imageThumbZoom, isActive) {
    this.id = id;
    this.parentID = parentID;
    this.code = code;
    this.name = name;
    this.desc = desc;
    this.substyleGroupDesc = substyleGroupDesc;
    this.option = option;
    this.price = price;
    this.imageThumb = imageThumb;
    this.imageDetail = imageDetail;
    this.imageAlt = imageAlt;
    this.imageThumbZoom = imageThumbZoom;
    this.isActive = isActive;
    this.preloadedThumb = new Image();
    this.preloadedThumb.src = pathToImages+this.imageThumb;
    this.preloadedThumbZoom = new Image();
    this.preloadedThumbZoom.src = pathToImages+this.imageThumbZoom;
    this.children = new Array();

    this.addChild = function(childStyle) {
	this.children.push(childStyle);
    }
}

function breadcrumbClick(code) {
	goToStyleCode(code);
}

function popupAlternate(id) {
	var thisStyle = styles.getItem(id);
	var popupText = "";
	popupText += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
	popupText += "<html>\n";
	popupText += "<head>\n";
	popupText += "<title>Anne Sportun • Experimetal Jewellery</title>\n";
	popupText += "<meta http-equiv=\"Content-Language\" content=\"en-us\" />\n";
	popupText += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\" />\n";
	popupText += "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles/main.css\" />\n";
	popupText += "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles/detailView.css\" />\n";
	popupText += "</head>\n";
	popupText += "<body class=\"detailView\">\n";
	popupText += "<div id=\"detailView\">\n";
	popupText += "<div id=\"closeButton\"><a href=\"javascript:window.close();\" onMouseOut=\"document.getElementById('bt-close-window').src='images/buttons/bt-close-window-a.gif';\" onMouseOver=\"document.getElementById('bt-close-window').src='images/buttons/bt-close-window-b.gif';\"><img id=\"bt-close-window\" src=\"images/buttons/bt-close-window-a.gif\" alt=\"\" /></a></div>\n";
	popupText += "<div id=\"logo\"><img src=\"images/menu/annesportun.gif\" alt=\"Anne Sportun\" /></div>\n";
	popupText += "<div id=\"styleInfo\">\n";
	popupText += "<h2 id=\"styleName\">"+thisStyle.name+"</h2>\n";
	popupText += "<div id=\"styleDesc\">"+thisStyle.desc+"</div>\n";
	popupText += "</div> <!-- id=styleInfo -->\n";

        //TODO: Loop through all images except thumbnails
	popupText += "<div id=\"styleThumbs\">\n";
	popupText += "<a href=\"#\" onmouseover=\"document.getElementById('styleImg').src='"+pathToImages+thisStyle.imageDetail+"';return false\"><img src=\""+pathToImages+thisStyle.imageDetail+"\" height=\"70\" alt=\"\" /></a>\n";
	if (hasAlternate(id)) {
	    popupText += "<a href=\"#\" onmouseover=\"document.getElementById('styleImg').src='"+pathToImages+thisStyle.imageAlt+"';return false\"><img src=\""+pathToImages+thisStyle.imageAlt+"\" height=\"70\" alt=\"\" /></a>\n";
	}
	popupText += "</div> <!-- id=styleThumbs -->\n";

	popupText += "<div id=\"styleImage\"><img id=\"styleImg\" src=\""+pathToImages+thisStyle.imageDetail+"\" alt=\"\" /></div>\n";
	popupText += "</div> <!-- id=detailView -->\n";

	popupText += "</body>";
	popupText += "</html>";

	popup=window.open('','popupAlternate','copyhistory=no,directories=no,location=no,locationbar=no,menubar=no,name="",personalbar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,width=500,height=650,top=0,left=0');
	popup.document.write(popupText);
	popup.document.close();
	popup.document.focus();
}

function hasAlternate(styleID) {
	var thisStyle = styles.getItem(styleID);
	return thisStyle!=null && thisStyle.imageAlt!=null && thisStyle.imageAlt.length>0;
}

function pagePrev() {
	var newPage = getCurrentPage()-1;
	if (newPage>=0) {
		goToPage(newPage);
	}
}

function pageNext() {
	var newPage = getCurrentPage()+1;
	if (newPage<numPages) {
		goToPage(newPage);
	}
}
function enablePurchase(id) {
	if (hasDiscount(id)) {
		displayElem(document.getElementById('styleDiscount'));
	}
}

function disablePurchase() {
	removeElem(document.getElementById('styleDiscount'));
}

function addOptions(id) {
	var style = styles.getItem(id);
	if (style!=null && style.children!=null && style.children.length>0) {
		var selectElemID = 'option.'+id;
		var parent = document.getElementById('styleOptions');
		var div = document.createElement('div');
		parent.appendChild(div);
		var label = style.substyleGroupDesc;
		if (label!=null && label.length>0) {
			var labelElem = document.createElement('label');
			labelElem.htmlFor = selectElemID;
			var textElem = document.createTextNode(label);
			div.appendChild(labelElem);
			labelElem.appendChild(textElem);
		}
		var select = document.createElement('select');
		select.onchange = optionSelected;
		select.name = selectElemID;
		select.id = selectElemID;
		var option = document.createElement('option');
		option.text = '';
		option.id = '';
		select.options[select.options.length] = option;
		div.appendChild(select);
		for (var i in style.children) {
			option = document.createElement('option');
			option.text = style.children[i].option;
			option.value = style.children[i].id;
			select.options[select.options.length] = option;
		}
	}
	if (canPurchase(id)) {
		enablePurchase(id);
		document.forms[0].elements[elemNamePurchaseStyleID].value = id;
	}
}

function optionSelected(e) {
	if (!e) var e = window.event;
	var targetElem;
	if (e.target) targetElem = e.target;
	else if (e.srcElement) targetElem = e.srcElement;
	if (targetElem.nodeType==3) targetElem = targetElem.parentNode; // Catch Safari bug
	var selectedOptionID = targetElem.options[targetElem.selectedIndex].value;
	removeChildOptions(targetElem);
	addOptions(selectedOptionID);
}

function canPurchase(id) {
	var style = styles.getItem(id);
	return style!=null && style.isActive;
}

function removeShoppingBagItem(shoppingBagItemID) {
	document.forms[0].elements[elemNamePurchaseStyleID].value = shoppingBagItemID;
	document.forms[0].elements[elemNamePurchaseInd].value = 'remove';
	goToShoppingPageSubmit();
}

function removeChildOptions(elem) {
	if (elem!=null) {
		var elemDiv = elem.parentNode;
		var parentDiv = elemDiv.parentNode;
		var nextDiv = elemDiv.nextSibling;
		var optionsRemoved = nextDiv!=null;
		while (nextDiv!=null) {
			parentDiv.removeChild(nextDiv);
			nextDiv = elemDiv.nextSibling;
		}
		if (optionsRemoved) {
			disablePurchase();
		}
	}
}

function getSelectedOptionID() {
	var optionID = null;
	var parent = document.getElementById('styleOptions');
	var selectElems = parent.getElementsByTagName('select');
	if (selectElems.length>0) {
		var selectElem = selectElems[selectElems.length-1];
		optionID = selectElem.options[selectElem.selectedIndex].value;
	} else {
		optionID = getStyleID();
	}
	return optionID;
}

function purchase() {
	var selectedStyleID = getSelectedOptionID();
	if (canPurchase(selectedStyleID)) {
		document.forms[0].elements[elemNamePurchaseInd].value = 'y';
		goToShoppingBag();
	} else {
		alert('You need to select more options before you can purchase this item.');
	}
}

function continueShopping() {
	goToBrowseCatalogue();
}

function hasDiscount(id) {
	var result = false;
	var thisStyle = styles.getItem(id);
	if (thisStyle!=null && window.discountStyleIDs) {
		for (i=0; !result && i<discountStyleIDs.length; i++) {
			var thisID = discountStyleIDs[i];
			while (!result && thisStyle!=null) {
				result = thisStyle.id == thisID;
				thisStyle = styles.getItem(thisStyle.parentID);
//				thisStyle = thisStyle.parentID!=null ?styles.getItem(thisStyle.parentID) :null;
			}
		}
	}
	return result;
}

function selectOption(selectElem, optionID) {
	for (var i=0; i<selectElem.options.length; i++) {
		var thisOption = selectElem.options[i];
		if (thisOption!=null) {
			if (thisOption.value==optionID) {
				thisOption.selected = true;
				break;
			}
		}
	}
}

function provinceChanged() {
	var provinceElem = document.forms[0].elements[elemNameProvince];
	var countryElem = document.forms[0].elements[elemNameCountry];
	var provinceID = provinceElem.options[provinceElem.selectedIndex].value;
	var countryID = countriesByProvince[provinceID];
	selectOption(countryElem, countryID);
}

function countryChanged() {
	var provinceElem = document.forms[0].elements[elemNameProvince];
	var countryElem = document.forms[0].elements[elemNameCountry];
	var countryID = countryElem.options[countryElem.selectedIndex].value;
	var provinceID = provinceElem.options[provinceElem.selectedIndex].value;
	if (provinceID!=null && provinceID!='') {
		if (countriesByProvince[provinceID]!=countryID) {
			provinceElem.selectedIndex = 0;
		}
	}
}

function processPayment() {
	if (window.orderAlreadySent) {
		alert('Please wait. Your payment is being processed.');
	} else {
		window.orderAlreadySent = true;
		goToProcessOrder();
	}
}

function appendQueryString(root, name, value) {
	if (root.indexOf('?')<0) root += '?';
	else root += '&';
	root += name + '=' + value;
	return root;
}

function generateUrlStyleCode(page, styleCode) {
	var url = page;
	if (styleCode!=null && styleCode.length>0) url = appendQueryString(url, paramNameStyleCode, styleCode);
	if (isWholesale()) url = appendQueryString(url, paramNameWholesaleInd, 'y');
	return url;
}

function generateUrlStyleTypeID(page, styleTypeID) {
	var url = page;
	if (styleTypeID!=null && styleTypeID.length>0) url = appendQueryString(url, paramNameStyleTypeID, styleTypeID);
	if (isWholesale()) url = appendQueryString(url, paramNameWholesaleInd, 'y');
	return url;
}


// Getters and setters
function clearStyleID() {
	if (document.forms[0].elements[elemNameStyleID]) document.forms[0].elements[elemNameStyleID].value = '';
}

function getStyleID() {
	return document.forms[0].elements[elemNameStyleID].value;
}

function setStyleID(id) {
	document.forms[0].elements[elemNameStyleID].value = id;
}

function getStyleTypeID() {
	return document.forms[0].elements[elemNameStyleTypeID].value;
}

function setStyleTypeID(id) {
	document.forms[0].elements[elemNameStyleTypeID].value = id;
}

function getCurrentPage() {
	var elem = document.forms[0].elements[elemNameCurrentPage];
	return parseInt(elem.value);
}

function setCurrentPage(pageNum) {
	var elem = document.forms[0].elements[elemNameCurrentPage];
	elem.value = pageNum;
}

function isRetail() {
//	return document.forms[0].elements[elemNameWholesaleInd].value == 'n';
        return !isWholesaleCatalogue;
}

function isWholesale() {
//	return document.forms[0].elements[elemNameWholesaleInd].value == 'y';
	return isWholesaleCatalogue;
}

function setRetail() {
//	document.forms[0].elements[elemNameWholesaleInd].value = 'n';
	isWholesaleCatalogue = false;
}

function setWholesale() {
//	document.forms[0].elements[elemNameWholesaleInd].value = 'y';
	isWholesaleCatalogue = true;
}


// Navigation functions
function goToPage(pageNum) {
	if (isNaN(pageNum)) {
		alert('There was an internal error while attempting to open page "'+pageNum+'"');
	} else {
		setCurrentPage(pageNum);
		var url = generateUrlStyleTypeID('shopping.jsp', getStyleTypeID());
		url = appendQueryString(url, elemNameCurrentPage, getCurrentPage());
		document.location.href = url;
	}
}

function goToShoppingBag() {
	document.forms[0].elements[elemNameAction].value = actionViewShoppingBag;
	goToShoppingPageSubmit();
}

function goToBrowseCatalogue(styleID) {	// If no features on home page, we may not need this function
	if (styleID!=null && styleID.length>0) {
		document.forms[0].elements[elemNameAction].value = actionBrowseCatalogue;
		goToShoppingPageDirect(styleID);
	} else if (getStyleTypeID()!=null && getStyleTypeID().length>0) {
		document.forms[0].elements[elemNameAction].value = actionBrowseCatalogue;
		goToShoppingPageDirect();
	} else {
		document.forms[0].elements[elemNameAction].value = actionOverview;
		goToShoppingPageDirect();
	}
}

function goToCheckOutShipping() {
	document.forms[0].elements[elemNameAction].value = actionCheckOutShipping;
	goToShoppingPageSubmit();
}

function goToCheckOutPayment() {
	document.forms[0].elements[elemNameAction].value = actionCheckOutPayment;
	goToShoppingPageSubmit();
}

function goToProcessOrder() {
	document.forms[0].elements[elemNameAction].value = actionProcessOrder;
	document.forms[0].action = 'processOrder.jsp';
	document.forms[0].target = '';
	document.forms[0].submit();
}

function goToSearchResults() {
	goToShoppingPageSubmit();
}

function goToStyleCode(styleCode) {
	document.location.href = generateUrlStyleCode('shopping.jsp', styleCode);
}

function goToStyleTypeID(styleTypeID) {
	document.location.href = generateUrlStyleTypeID('shopping.jsp', styleTypeID);
}

function goToShoppingPageDirect(styleID) {
	if (styleID!=null && styleID.length>0) {
	    goToStyleID(styleID);
	} else {
	    goToStyleTypeID(getStyleTypeID());
	}
}

function goToShoppingPageSubmit(styleID) {
	if (styleID!=null && styleID.length>0) {
		setCurrentStyleID(styleID);
	} else {
		clearStyleID();
	}
	document.forms[0].action = 'shopping.jsp';
	document.forms[0].target = '';
	document.forms[0].submit();
}

