var minimumQuantityType = {
	STYLE : 1,
	COLOR_DIM : 2,
	SKU : 3
}
var multipleQuantityType = {
	STYLE : 1,
	SKU : 2
}


var sizeMatrix = {
	quantityType : 0,
	multipleQty : 1,
	minimumQty : 1,
	minimumWarningQty : 1
}

function basicSizeMatrixValidation(value){
	if (!isValidMinimumQty(value)){ alert(sizeMatrixMessages.getRessources("ERROR_MINIMUM_ORDER_QTY", LOCALE, sizeMatrix.minimumQty, value).text); return true; }
	else if (!isValidMultipleQty(value)){ alert(sizeMatrixMessages.getRessources("ERROR_MULTIPLE_QTY", LOCALE, sizeMatrix.multipleQty).text); return true; }
	return false;
}

function isMinimumWarningQtyRequired(value){
	return (value < sizeMatrix.minimumWarningQty)? true : false;
}

function isValidMinimumQty(value){
	return (value < sizeMatrix.minimumQty)? false : true;
}

function isValidMultipleQty(value){
	if (isNaN(value) || value.length == 0){ return false; }
	if((value > 0 && value < sizeMatrix.multipleQty) || value % sizeMatrix.multipleQty != 0){ return false;	}	
	return true;	
}

function hasCartValidQty(){
	var retValue = true;
	if(hasVendorOnHold){
		alert(sizeMatrixMessages.getRessources("VENDOR_ON_HOLD", LOCALE).text);
		retValue = false;
	}
	var retValue = !basicSizeMatrixValidation(cartTotalQuantity);

	if (isMinimumWarningQtyRequired(cartTotalQuantity)){ alert(sizeMatrixMessages.getRessources("WARNING_MINIMUM_ORDER_QTY", LOCALE, sizeMatrix.minimumWarningQty, cartTotalQuantity).text); }

	return retValue;
}

function getSessionID() {
	var index = document.location.href.indexOf(";");
	if (index != -1) {
		var index2 = document.location.href.indexOf("?");
		if (index2 == -1) {
			return document.location.href.substring(index);
		}
		return document.location.href.substring(index, index2);
	}
	return "";
}

var ShippingDetails = new Object();

ShippingDetails.extend({

	shippingDetailUpdateInProgress: false,
	
	shippingDetails: new Array(),
	
	display : function(elementId, elementValue) {
		var details = null;
		
		if(!this.shippingDetailUpdateInProgress && this.shippingDetails[elementId] != elementValue){

			this.shippingDetails[elementId] = elementValue;
		
			if (elementValue != null && elementValue != "") {
				this.shippingDetailUpdateInProgress = true;
				new SmartAjax.Request("/displayShippingAddress.do"+getSessionID(), 
					{parameters:"shippingDetailID=" + elementValue, onSuccess:shippingDetails_onSuccess, onFailure: shippingDetails_onFailure},
					{ElementId: elementId, ElementValue: elementValue}
					);
			} else {
				document.getElementById("ShippingDetail-Description").innerHTML = "";
				document.getElementById("ShippingDetail-Address1").innerHTML = "";
				document.getElementById("ShippingDetail-State").innerHTML = "";
				document.getElementById("ShippingDetail-StateCountrySeparator").innerHTML = "";
				document.getElementById("ShippingDetail-City").innerHTML = "";
				document.getElementById("ShippingDetail-Country").innerHTML = "";
				document.getElementById("ShippingDetail-PostalCode").innerHTML = "";
				document.getElementById("ShippingDetail-Telephone").innerHTML = "";
				document.getElementById("ShippingDetail-Fax").innerHTML = "";
				document.getElementById("ShippingDetail-Email").innerHTML = "";
				document.getElementById("ShippingDetail-Attention").innerHTML = "";
		
			}
		}
	}
})

function shippingDetails_onFailure(request, shippingDetailID) {
	ShippingDetails.shippingDetailUpdateInProgress = false;
}

function shippingDetails_onSuccess(request, shippingDetail) {
	var details = null;
	var d = document;
	var address = new String("");
	var telephone = new String("");
	var fax = new String("");
	var email = new String("");
	var attention = new String("");
	eval(request.responseText);
	
	if (details.address_1 != null && details.address_1.length > 0) {
		address = address.concat(details.address_1);
	}
	
	if (details.address_2 != null && details.address_2.length > 0) {
		address = address.concat("<br/>", details.address_2);
	}
	
	if (details.address_3 != null && details.address_3.length > 0) {
		address = address.concat("<br/>", details.address_3);
	}
	
	if (details.telephone != null && details.telephone != "null" && 
		details.telephone != "NA" && details.telephone.length > 0) 
	{
		telephone = telephone.concat("<br/>", details.telephone);
	}
	
	if (details.fax != null && details.fax != "null" && 
		details.fax != "NA" && details.fax.length > 0) 
	{
		fax = fax.concat("<br/>", details.fax);
	}
	
	if (details.email_1 != null && details.email_1 != "null" && 
		details.email_1 != "NA" && details.email_1.length > 0) 
	{
		email = email.concat("<br/>", details.email_1);
	}
	
	if (details.attention != null && details.attention != "null" && 
		details.attention != "NA" && details.attention.length > 0) 
	{
		attention = attention.concat("<br/>", details.attention);
	}
	
	d.getElementById("ShippingDetail-Description").innerHTML = details.description;
	d.getElementById("ShippingDetail-Address1").innerHTML = address;
	d.getElementById("ShippingDetail-State").innerHTML = details.stateID;
	d.getElementById("ShippingDetail-City").innerHTML = details.city;
	d.getElementById("ShippingDetail-Country").innerHTML = details.countryID;
	d.getElementById("ShippingDetail-PostalCode").innerHTML = details.postalCode;
	d.getElementById("ShippingDetail-StateCountrySeparator").innerHTML = ",";
	d.getElementById("ShippingDetail-Telephone").innerHTML = telephone;
	d.getElementById("ShippingDetail-Fax").innerHTML = fax;
	d.getElementById("ShippingDetail-Email").innerHTML = email;
	d.getElementById("ShippingDetail-Attention").innerHTML = attention;

	ShippingDetails.shippingDetailUpdateInProgress = false;

	//Check if the select's value has changed while we were waiting for the AJAX response
	var currentShippingDetailId = d.getElementById(shippingDetail.ElementId).value;
	if( currentShippingDetailId != shippingDetail.ElementValue ){
		ShippingDetails.display(shippingDetail.ElementId, currentShippingDetailId);
	}
}

function RessourceManager(locale){
	var managerLocale = new String("en");
	
	var ressources = new Array();
	this.addRessource = function(rsrc) {
		if (typeof rsrc == "object") {
			ressources[ressources.length] = rsrc; 
			return true;
		}
		return false;
	}
	
	this.getRessources = function(key, locale){
		locale = (typeof(locale) == "string" && locale.length > 0) ? locale : managerLocale;
		var ress = null;
		if (typeof(key) == "number") {
			ress = ressources[key].ressource(locale).clone();
		} else {
			for (var i = 0; i < ressources.length; i++) {
				if (ressources[i].key == key) {
					ress = ressources[i].ressource(locale).clone();
				}
			}
		}
		
		if (ress != null && arguments.length >= 2) {
			for (var idx = 0; idx < arguments.length - 2; idx++) {
				ress.text = ress.text.replace("{" + idx + "}", arguments[idx+2]);
			}
		}
		return ress;
	}
	
	this.setLocale = function(locale){
		managerLocale = (arguments.length == 1 && typeof(locale) == "string" && locale.length > 0)? locale : managerLocale;
	}
	
	this.getRessourcesCount = function() {return ressources.length;}
	
	this.setLocale(locale);
}

function Ressources(k) {
	this.key = k;
	var ressources = new Array();
	this.addRessource = function(t, locale) {
		locale = (typeof(locale) == "string" && locale.length > 0) ? locale : new String("en");
		ressources[ressources.length] = new Ressource(t,locale);
	}
	this.ressource = function(locale) {
		local = (typeof(locale) == "string" && locale.length > 0) ? locale : new String("en");
		var lang = null;
		// Attempt to extract the language code from locale
		if (locale.indexOf("_") > -1) {
			var tmp = locale.split("_");
			if (tmp.length > 0) lang = tmp[0];
		}
		for (var i = 0; i < this.count(); i++) {
			if (ressources[i].locale == locale || (lang != null && ressources[i].locale == lang)) {
				return ressources[i];
			}
		}
		
		// In last resort we provide ressource with default supported locale
		return this.ressource("en");
	}
	this.count = function() {return ressources.length;}
}

function Ressource(t,l){
	this.text = t;
	this.locale = (typeof(l) == "string" && l.length > 0)? l : new String("en");
}

sfHover = function() {

	setHover(document.getElementById("nav"))
}
	

if (window.attachEvent) window.attachEvent("onload", sfHover);


function setHover(nav) {

		if(document.getElementById("nav"))
		{
			var sfEls = document.getElementById("nav").getElementsByTagName("LI");
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=" sfhover";
					}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
					}
				}
		}


}







function hideSelects(){
	var oSelects=document.getElementsByTagName("select");
	for(var i=0;i<oSelects.length;i++)
		oSelects[i].className+=" hide";
}
function showSelects(){
	var oSelects=document.getElementsByTagName("select");
	for(var i=0;i<oSelects.length;i++)
		oSelects[i].className=oSelects[i].className.replace(" hide","");
}



function formatDate(day, month, year) {
	if (year < 2000) {
		year += 1900;
	}
	if (day < 10) {
		day = "0" + day;
	}
	month += 1;
	if (month < 10) {
		month = "0" + month;
	}
	return month + "/" + day + "/" + year;
}

function calendarDateChanged(calendar) {
	// Beware that this function is called even if the end-user only
	// changed the month/year. In order to determine if a date was
	// clicked you can use the dateClicked property of the calendar:
	if (calendar.dateClicked) {
		calendar.params.inputField.value = 
			formatDate( calendar.date.getDate(), calendar.date.getMonth(), calendar.date.getFullYear());
		if(calendar.params.inputField.onchange){
			calendar.params.inputField.onchange();
		}
		calendar.callCloseHandler();
	}
}

function formatDateMonth(month, year) {
	if (year < 2000) {
		year += 1900;
	}
	month += 1;
	if (month < 10) {
		month = "0" + month;
	}
	return month + "/" + year;
}

function calendarDateChangedMonth(calendar) {
	// Beware that this function is called even if the end-user only
	// changed the month/year. In order to determine if a date was
	// clicked you can use the dateClicked property of the calendar:
	if (calendar.dateClicked) {
		calendar.params.inputField.value = 
			formatDateMonth( calendar.date.getMonth(), calendar.date.getFullYear());
		if(calendar.params.inputField.onchange){
			calendar.params.inputField.onchange();
		}
		calendar.callCloseHandler();
	}
}

function fieldCheckDecimal(e)
{
	var keynum;
	var keychar;
	var numcheck;
	
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	//return true if the key pressed was a system key
    switch (keynum) {
       case 38: //up arrow  
       case 40: //down arrow
       case 37: //left arrow
       case 39: //right arrow
       case 33: //page up  
       case 34: //page down  
       case 36: //home  
       case 35: //end                  
       case 13: //enter  
       case 9: //tab  
       case 27: //esc  
       case 16: //shift  
       case 17: //ctrl  
       case 18: //alt  
       case 20: //caps lock
       case 8: //backspace  
       case 46: //delete
           return true;
           break;
	}
	//Numeric - numbers at the top of keyboard or keypad
	if((keynum >= 48 && keynum <=57) || (keynum >= 96 && keynum <=105)){
		return true;
	}
	return false;
}

function fieldCheckDouble(e)
{
	var keynum;
	var keychar;
	var numcheck;
	
	if(window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	//return true if the key pressed was a system key
    switch (keynum) {
       case 38: //up arrow  
       case 40: //down arrow
       case 37: //left arrow
       case 39: //right arrow
       case 33: //page up  
       case 34: //page down  
       case 36: //home  
       case 35: //end                  
       case 13: //enter  
       case 9: //tab  
       case 27: //esc  
       case 16: //shift  
       case 17: //ctrl  
       case 18: //alt  
       case 20: //caps lock
       case 8: //backspace  
       case 46: //delete
           return true;
           break;
	}
	//Numeric - numbers at the top of keyboard or keypad and both '.'
	if((keynum >= 48 && keynum <=57) || (keynum >= 96 && keynum <=105) || keynum == 110 || keynum == 190 ){
		return true;
	}
	return false;
}

// count how many sFind in the string
function countString(sString, sFindThis) { 
    if (sFindThis != "") {
      var counter = 0;
      var start = 0;
      while (start<sString.length) {
        start = sString.indexOf(sFindThis, start);
        if (start == -1){
         break;
         } else {
           counter = counter + 1;
           start = start + 1;
          }
        }
      }
   return counter;
}

function fieldCheckMaxLength(field, table_column)
{
	var maxlength;
	var counter1 = 0;
	
	// table_column - maxlength
	if (table_column=="IC_EMAIL_ACTIVITY_PARAMETERS.PARAMETER_VALUE") {
		maxlength = 470;						// the column length of the table is 500, leave some space for 'add to mailing list' comment
	}
	else if (table_column=="IC_PO_STYLES.NOTES") {
		maxlength = 500;
	}
	else if (table_column=="IC_PO_VENDORS.NOTES") {
		maxlength = 4000;
	}
	else if (table_column=="IC_PO_MESSAGES.MESSAGE") {
		maxlength = 4000;
	}
	else {
		maxlength = 100;
	}
	// counter of carriage return
	counter1 = countString(field.value, "\n");	// for firefox
	
	if(window.event) // IE
	{
		if (field.value.length<=maxlength)
			return true;
		else {
			field.value = field.value.substring(0, maxlength);
			return false;
		}
	}
	else {
		if (field.value.length+counter1<=maxlength)
			return true;
		else {
			field.value = field.value.substring(0, maxlength - counter1);	// may trim too many since CR included in the trimmed string
			return false;
		}
	}
} //function fieldCheckMaxLength(field, table_column)

initFilterOnKeyUpEnter = function() {
	var elements = document.getElementsByClassName('resultFilter', document);

	for (var i=0; i<elements.length; i++) {
		var element = elements[i];
		addEvent(element, 'keyup', function (e) {
			var key = e.keyCode;
			var shift = e.shiftKey;
				
			if (!shift && key == 13) {
				element.form.filterResultsSubmit.value = 'true';
				element.form.submit();
			}
		});
	}
}
addEvent(window, "load", initFilterOnKeyUpEnter, true);


resetPaginationForm = function() {
	var pagForm = document.getElementById("PaginationForm");
	
	if (pagForm != null) {
		pagForm.elements['page'].value = pagForm.elements['currentPage'].value;
		pagForm.elements['resultPerPage'].value = pagForm.elements['currentResultsPerPage'].value;
	}
}
addEvent(window, "load", resetPaginationForm, true);

function setFormActionURL(form, url){
	form.action= url+ getSessionID();
}

if (window.attachEvent) window.attachEvent('onload', sfHover);


/********************************************************
*
*          show/hide popup window within a browser
*
********************************************************/
//	var time;					// time handler
//	var TIMEOUT = 5000;			// default time out for the promotion infomation window
	
function showHTMLMessage(obj, url, elmID, displayMode) {
	var coors = findElementPosition(obj);
	var objHeight = obj.offsetHeight;
	var margin = 5;
	var popLeft = coors[0];
	var popTop  = coors[1] + objHeight + margin;
	if (document.getElementById(elmID).style.display != "none" && document.getElementById(elmID).style.display != "") {
		// if already displayed
//		clearTimeout(time);
//		time = setTimeout("closePopUp()", TIMEOUT);
	} else {
		// not displayed
		if (document.getElementById(elmID).src.indexOf(url) < 0) {
			// need to get the source
			document.getElementById(elmID).src = url;
			document.getElementById(elmID).style.left = popLeft;
			document.getElementById(elmID).style.top  = popTop;
			document.getElementById(elmID).style.display = displayMode;
			
//			time = setTimeout("closePopUp()", TIMEOUT);
		} else {
			// display style currently is "none"
			document.getElementById(elmID).style.display = displayMode;
				
//			time = setTimeout("closePopUp()", TIMEOUT);
		}
	}
}

/* show iframe message within template */
function showIMessage(obj, evt, url, elmID, displayMode, reload) {
	var coors = findMousePosition(evt);
	var objHeight = obj.offsetHeight;
	var margin = 5;
	var popLeft = coors[0];
	var popTop  = objHeight + margin + coors[1];

	var template = "/displayIMessage.do";
	/* the first argument takes the url of the displayed page */
	/* the second argument takes the element id of the displayed iframe */
	var src = template + "?url=" + escape(url) + "&elmID=" + elmID;
	
	document.getElementById(elmID).style.left = popLeft + "px";
	document.getElementById(elmID).style.top  = popTop + "px";
	if (document.getElementById(elmID).style.display != "none"&& document.getElementById(elmID).style.display != "") {
		// if already displayed
		if (reload) {
			document.getElementById(elmID).src = "about:blank";
			document.getElementById(elmID).src = src;
		}
	} else {
		// not displayed
		if (document.getElementById(elmID).src.indexOf(src)<0 || reload) {
			document.getElementById(elmID).src = src;
		}
	}
	document.getElementById(elmID).style.display = displayMode;
}

function closeMessage(elmID) {
	var elt = document.getElementById(elmID);
	elt.style.display = "none";
	
	if (window.closeMessage_Custom) {
		closeMessage_Custom(elt);
	}
}
	
function findMousePosition(evt) {
	if (document.layers) {
		return [evt.pageX,evt.pageY];
	}
	else if (document.all) {
		if (document.documentElement && document.documentElement.scrollTop) {
			return [window.event.clientX+document.documentElement.scrollLeft, window.event.clientY+document.documentElement.scrollTop];
		}
		else {
			return [window.event.clientX+document.body.scrollLeft, window.event.clientY+document.body.scrollTop];
		}
	}
	else {
		return [evt.pageX,evt.pageY];
	}
}

function findElementPosition(obj) {  
	var left = 0;
	var top = 0;
	if (obj.offsetParent) {
		left = obj.offsetLeft;
		top = obj.offsetTop;
		while (obj = obj.offsetParent) {
			left += obj.offsetLeft;
			top += obj.offsetTop;
		}
	} else {
		left = obj.offsetLeft;
		top = obj.offsetTop;
	}
	return [left, top];
}
	
/* used for sorting function in the search result header */	
function sortSearchResults(sortBy, sortOrder) {
	var pagForm = document.forms['PaginationForm'];
	pagForm.sortBy.value = sortBy;
	pagForm.sortOrder.value = sortOrder;
	pagForm.sortResultsSubmit.value = "true";
	pagForm.submit();
}

/** end **/

function showCartPreview(parentNode, url, reload) {
	var pos = findElementPosition(parentNode);
	var iframe = document.getElementById("cartInfoPreview");
	
	// register function on load event
	// it will resize the IFrame to pack his content (body)
	addEvent(iframe, "load", function() {
		var _iframe_elt = document.getElementById("cartInfoPreview");	// as HTML element
		var _iframe_wind = frames["cartInfoPreview"];	// as window object
		
		if (_iframe_wind != null && _iframe_wind != undefined && _iframe_wind.location.href != "about:blank") {
			var body = _iframe_wind.document.body;
			
			if (body != null && body != undefined) {
				_iframe_elt.style.height = (body.scrollHeight || body.offsetHeight)+"px";
			}
		}
		// call the custom function to let client do what erver they have to do
		if (window.showCartPreview_Custom) {
			showCartPreview_Custom(parentNode, pos, iframe);
		}
	}, false);
	
	if (iframe.src.indexOf(url) < 0 || reload) {
		iframe.src = url;
	}
	iframe.style.left = pos[0]+"px";
	iframe.style.top = (pos[1] + parentNode.clientHeight)+"px";
	iframe.style.display = "";
	
	// if the iframe is already loaded, attempt to execute custom function
	var _iframe_wind = frames["cartInfoPreview"];	// as window object
	if (_iframe_wind != null && _iframe_wind != undefined && _iframe_wind.location.href != "about:blank") {
		// call the custom function to let client do what erver they have to do
		
		if (window.showCartPreview_Custom) {
			showCartPreview_Custom(parentNode, pos, iframe);
		}
	}
}

