/*
(C) Copyright MarketLive. 2006. All rights reserved.
MarketLive is a trademark of MarketLive, Inc.
Warning: This computer program is protected by copyright law and international treaties.
Unauthorized reproduction or distribution of this program, or any portion of it, may result
in severe civil and criminal penalties, and will be prosecuted to the maximum extent
possible under the law.
*/

function validateProductSelection(qtyMessage, optionMsg,form, minQty) {
	var iTotalQty = 0;
    var qtyErrorMsg = qtyMessage.toString();
    var optionErrorMsg = optionMsg.toString();
    var qtyValue = '';
    var optValue = '';
    var optTypeValue = '';
    var selectedKitItems = '';
    var iValue;
    var qty = new Array();
    var optionTypes = new Array();
    var options = new Array();
    var productWithNoOptions = 0;
    var productWithOptions = 0;
    var validOptions = 0;
    var j = 0;
    var badOptions = 0;
    var qtyValid = false;
    var isKit = false;
    var productPk = "";
    var bValidationResult = true;

    for(var i = 0; i < form.length; i++) {

        var field = form.elements[i];
	  // alert( ' field name: ' + field.name + ', field value ' + field.value + ' field type ' + field.type);
        if ((field.type == "text" || field.type == "select-one") && (field.name == "qty")) {

            qtyValue = (field.type == "text")? field.value:field[field.selectedIndex].value;
            if( isNotDigitsPrompt(field, qtyValue, qtyMessage) ) {
                return false;
            }

        } else if (field.type == "hidden" ) {
            if(field.name == "option") {
              optValue =  field.value;
            } else if (field.name == "optionTypes") {
              optTypeValue = field.value;
            } else if (field.name == "qty") {
				var isTeamSale=false;
				if(document.getElementById('isTeamSale')){
					isTeamSale=document.getElementById('isTeamSale').value;
				}
				qtyValue = field.value;
				if(isTeamSale == false)
					isKit = true;
		    }

		// make sure that any javascript attached to a radio button gets triggered if its checked/selected.
        } else if (field.type == "radio" && field.checked){
            field.click();
        }

		if ( field.name == "productPk" ) {
			productPk = field.value;
	  	}
		if ( productPk.length > 0 && isKit  ) {
		 	var fieldName =  "document.getElementById('mainForm').selectedKitItems_" + productPk;
			obj = eval( fieldName);
				if ( obj.value == undefined ) {
					var k=0;
					for ( k=0; k < obj.length ; k++ ) {
						if ( obj[k].checked ) {
							break;
						}
					}

					if ( k == obj.length ) {
						alert('select a kit');
						return false;
					} else {
					    bValidationResult = validateKitSingleProductOptions(productPk);
					}
				}
	  	}

        // if all fields values are collected, store them into the arrays
        if (qtyValue != "" && optValue != "" &&  optTypeValue != "") {
        // alert(" qtyValue " + qtyValue + " optValue " + optValue + " optTypeValue " + optTypeValue );
          qty[j] = qtyValue;
          options[j] = optValue;
          optionTypes[j] = optTypeValue;
          j++;
          optTypeValue = ""; qtyValue = ""; optValue = "";
        }
    }
      // alert("qty.length " + qty.length + " options.length " + options.length + " optionTypes.length " + optionTypes.length + " j " + j);
      // go through the arrays and validate
    for (var m = 0; m < j; m++) {
          // check qty
        qtyValue = qty[m];

        if (isAllDigits(qtyValue)) {
            iValue = parseInt(qtyValue);
            if (!isNaN(iValue)) {
                iTotalQty += iValue;
                qtyValid = true;
            }
        }
       // now check options selection
       if (qtyValid && (iValue > 0)) {
           qtyValid = false;
           optTypeValue = optionTypes[m];
           optValue = options[m];
           if (optTypeValue > 0) {
               // product has options so check if any selected
               if(optValue != "none") {
                   // something was selected
                   // now check that number of options corresponds to selection
                   arr = optValue.split(":");
                   if (arr.length == optTypeValue) {
                       // got the same number of options as the number of drop-down menus
                       // now check if a zero value is selected for each one of them
                       for(var n = 0; n < arr.length; n++) {
                            subArr = arr[n].split("=");
                            if ((subArr[1] != 0)) {
                                validOptions++;
                            }
                       }
                       if (validOptions == optTypeValue) {
                           productWithOptions++;
                       } else {
                           badOptions++;
                       }
                       // reset var
                       validOptions = 0;
                   } else {
                       badOptions++;
                   }
               } else {
                   badOptions++;
               }
           } else {
               // product has no options, increment counter.
               productWithNoOptions++;
           }
       } // end if valid qty and qty > 0
    } // end for
	
//	return false;
    // validate quantity. On detail page, minQty is probably 1.
    // On basket, 0 is a valid qty -- means to remove
    if (iTotalQty < minQty) {
        alert(qtyErrorMsg);
        return false;
    } else {
        if (badOptions > 0) {
          alert(optionErrorMsg);
          return false;
        } else {
            // if nothing was selected for product with options and
            // there is no product without options
            // and there is a qty greater than minQty then there's an error
            if ( (productWithOptions < 1) && (productWithNoOptions < 1) && (iTotalQty > minQty) ) {
               alert(optionErrorMsg);
               return false;
            } else {
				return true;
            }
        }
    }
    return bValidationResult;

}

/*
function isAllDigits(argvalue) {
   argvalue = argvalue.toString();
   if(argvalue.length < 1) return false;

    var validChars = "0123456789";
    var startFrom = 0;
    if (argvalue.substring(0, 2) == "0x") {
       validChars = "0123456789abcdefABCDEF";
       startFrom = 2;
    } else if (argvalue.charAt(0) == "0") {
       validChars = "01234567";
       startFrom = 1;
    } else if (argvalue.charAt(0) == "-") {
        startFrom = 1;
    }

    for (var n = startFrom; n < argvalue.length; n++) {
        if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
    }
    return true;
}
*/
function isNotDigitsPrompt(field, qtyValue, qtyMessage) {
    if ( qtyValue == "" ) {
        field.value = "0";
        return false;
    } else if ( !isAllDigits(qtyValue) ) {
        alert(qtyMessage);
        return true;
    }
}
function isAllDigits(argvalue) {
   argvalue = argvalue.toString();
   if(!validateNotEmpty(argvalue)) return false;

   if(!validatePositiveInt(argvalue)) return false;

   return true;
}

function validateInteger( strValue ) {
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validatePositiveInt( strValue ) {
  var objRegExp  = /(^\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function trimAll( strValue ) {
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function validateKitSingleProductOptions( productPk ) {
    // locate error message
    var selectedSkuFieldName =  "document.getElementById('mainForm').selectedKitSku";
    var selectedSkuFieldObj =  eval( selectedSkuFieldName );
    var selectedSkuPk = selectedSkuFieldObj.value;
    var errorMessageFieldName = "";
    var errorMessageFieldObj;
    var notDone = 1;

    for ( var j = 0; notDone == 1 ; j++ ) {
        errorMessageFieldName = "document.getElementById('mainForm').errorMessage_" +  productPk + "_" + selectedSkuPk + "_" + j;
        errorMessageFieldObj = eval( errorMessageFieldName );
        if ( errorMessageFieldObj != undefined ) {
            if ( errorMessageFieldObj.value != "" ) {
                alert(errorMessageFieldObj.value);
                notDone = 0;
                return false;
            }
        } else {
            notDone = 0;
        }
    }
    return true;

}
function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; i<oClassNames.length; i++){
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++){
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++){
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}
//--------CUSTOM:ML-SC <CHK_UC1a> START-----------------------
function rollDownCart(){
	var menuObjs = getElementsByClassName(document, "*", "GlobalCartOff");
	//now that we have gotten all elements with the class name fire their onmouseover events starting from the end of the array
	//we start from the end because of javascripts bubble up behaviour. We are trying to mimic the events in the correct sequence
    for(var i=(menuObjs.length-1); i>-1; i--){
		if (menuObjs[i].onmouseover != null){
			if( document.createEvent ) {
				var evObj = document.createEvent('MouseEvents');
				evObj.initEvent( 'mouseover', true, false );
				menuObjs[i].dispatchEvent(evObj);
			} else if( document.createEventObject ) {
				menuObjs[i].fireEvent('onmouseover');
			}
		}
    }
	//call a static mousover that exists on an anchor
	_p1(this);_mot=$P(_mot);
	
	/* artf853888: Taking out the items added to your cart message */
	/*
	var newItemMsg = document.getElementById("cartNewItemMessage");
	if (newItemMsg) {
		newItemMsg.style.display = "inline";	
	}
	*/
	//call rollupcart() to hide the cart after 3.5 seconds. Note the time comes from property file and is used in the actual milonic function
	//This 1 second time is needed for the cart not to hide automatically. 
    var t=setTimeout("rollUpCart()",3500);
}

function rollUpCart(){
	//fire static onmouseout functions
	hidetip();
	$I();
	/* artf853888: Taking out the items added to your cart message */
	/*
	var newItemMsg = document.getElementById("cartNewItemMessage");
	if (newItemMsg) {
		newItemMsg.style.display = "none";	
	}
	*/
}

function validateCustomFields(nameLength, numLength, nameSpeciChar, numSpeciChar){
   // This is the validation for custName 
	if(document.getElementById('mainForm').customizationName == null){
		return true;
	}
	if(document.getElementById('mainForm').customizationName.value=='Enter Name'){
		document.getElementById('mainForm').customizationName.value="";
	}
	else{
		var custName = document.getElementById('mainForm').customizationName.value;
		if(custName.length>14){
			alert(nameLength);
			return false;
		}
		var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?0123456789";
		for (var i = 0; i < custName.length; i++) {
  			if (iChars.indexOf(custName.charAt(i)) != -1) {
  				alert (nameSpeciChar);
  				return false;
  			}
		}
 
	 }
	if(document.getElementById('mainForm').customizationNumber.value=='Enter Number'){
		document.getElementById('mainForm').customizationNumber.value="";
	}
	else{
		var custNumber = document.getElementById('mainForm').customizationNumber.value;
		if(custNumber.length>2){
			if(document.getElementById('mainForm').customizationName.value==""){
				document.getElementById('mainForm').customizationName.value="Enter Name";
			}
			alert(numLength);
			return false;
		}
		var nonums = /^[0-9]*$/;
		if (!nonums.test(custNumber)) {
			if(document.getElementById('mainForm').customizationName.value=""){
				document.getElementById('mainForm').customizationName.value="Enter Name";
			}
			alert(numSpeciChar);			
			return false;
		}
	 }
 return true;
}

if(!DomLoaded){
	/* DOMLOADED*/
	var DomLoaded={onload:[],loaded:function(){
	if(arguments.callee.done){
	return;
	}
	arguments.callee.done=true;
	for(var i=0;i<DomLoaded.onload.length;i++){
	DomLoaded.onload[i]();
	}
	},load:function(_2){
	this.onload.push(_2);
	if(document.addEventListener){
	document.addEventListener("DOMContentLoaded",DomLoaded.loaded,null);
	}
	if(/KHTML|WebKit/i.test(navigator.userAgent)){
	var _3=setInterval(function(){
	if(/loaded|complete/.test(document.readyState)){
	clearInterval(_3);
	delete _3;
	DomLoaded.loaded();
	}
	},10);
	}
	window.onload=DomLoaded.loaded;
	}};	
}

//once this div is loaded in the dom then roll down the cart
DomLoaded.load(function(){
		var cartTrigger = document.getElementById("cartTrigger");
		if(cartTrigger){
			rollDownCart();
		}
});
//--------CUSTOM:ML-SC <CHK_UC1a> END-----------------------


function clearMessages(){
	var addToCartSucMessage=document.getElementById('sucMsg');
	var addToCartSucMessageRow=document.getElementById('sucMsgRow');
	if(addToCartSucMessage!=null)
	{
		addToCartSucMessage.style.display ='none';
		addToCartSucMessageRow.style.display ='none';
	}
}

function validateProductSelectionDetail(qtyMessage, optionMsg,form, minQty) {
	var iTotalQty = 0;
    var qtyErrorMsg = qtyMessage.toString();
    var optionErrorMsg = optionMsg.toString();
    var qtyValue = '';
    var optValue = '';
    var optTypeValue = '';
    var selectedKitItems = '';
    var iValue;
    var qty = new Array();
    var optionTypes = new Array();
    var options = new Array();
    var productWithNoOptions = 0;
    var productWithOptions = 0;
    var validOptions = 0;
    var j = 0;
    var badOptions = 0;
    var qtyValid = false;
    var isKit = false;
    var productPk = "";
    var bValidationResult = true;

    for(var i = 0; i < form.length; i++) {

        var field = form.elements[i];
	  // alert( ' field name: ' + field.name + ', field value ' + field.value + ' field type ' + field.type);
        if ((field.type == "text" || field.type == "select-one") && (field.name == "qty")) {

            qtyValue = (field.type == "text")? field.value:field[field.selectedIndex].value;
            if( isNotDigitsPrompt(field, qtyValue, qtyMessage) ) {
                return false;
            }

        } else if (field.type == "hidden" ) {
            if(field.name == "option") {
              optValue =  field.value;
            } else if (field.name == "optionTypes") {
              optTypeValue = field.value;
            } else if (field.name == "qty") {
				var isTeamSale=false;
				if(document.getElementById('isTeamSale')){
					isTeamSale=document.getElementById('isTeamSale').value;
				}
				qtyValue = field.value;
				if(isTeamSale == false)
					isKit = true;
		    }

		// make sure that any javascript attached to a radio button gets triggered if its checked/selected.
        } else if (field.type == "radio" && field.checked){
            field.click();
        }

		if ( field.name == "productPk" ) {
			productPk = field.value;
	  	}
		if ( productPk.length > 0 && isKit  ) {
		 	var fieldName =  "document.getElementById('mainForm').selectedKitItems_" + productPk;
			obj = eval( fieldName);
				if ( obj.value == undefined ) {
					var k=0;
					for ( k=0; k < obj.length ; k++ ) {
						if ( obj[k].checked ) {
							break;
						}
					}

					if ( k == obj.length ) {
						showMessageBox('select a kit');
						return false;
					} else {
					    bValidationResult = validateKitSingleProductOptions(productPk);
					}
				}
	  	}

        // if all fields values are collected, store them into the arrays
        if (qtyValue != "" && optValue != "" &&  optTypeValue != "") {
        // alert(" qtyValue " + qtyValue + " optValue " + optValue + " optTypeValue " + optTypeValue );
          qty[j] = qtyValue;
          options[j] = optValue;
          optionTypes[j] = optTypeValue;
          j++;
          optTypeValue = ""; qtyValue = ""; optValue = "";
        }
    }
      // alert("qty.length " + qty.length + " options.length " + options.length + " optionTypes.length " + optionTypes.length + " j " + j);
      // go through the arrays and validate
    for (var m = 0; m < j; m++) {
          // check qty
        qtyValue = qty[m];

        if (isAllDigits(qtyValue)) {
            iValue = parseInt(qtyValue);
            if (!isNaN(iValue)) {
                iTotalQty += iValue;
                qtyValid = true;
            }
        }
       // now check options selection
       if (qtyValid && (iValue > 0)) {
           qtyValid = false;
           optTypeValue = optionTypes[m];
           optValue = options[m];
           if (optTypeValue > 0) {
               // product has options so check if any selected
               if(optValue != "none") {
                   // something was selected
                   // now check that number of options corresponds to selection
                   arr = optValue.split(":");
                   if (arr.length == optTypeValue) {
                       // got the same number of options as the number of drop-down menus
                       // now check if a zero value is selected for each one of them
                       for(var n = 0; n < arr.length; n++) {
                            subArr = arr[n].split("=");
                            if ((subArr[1] != 0)) {
                                validOptions++;
                            }
                       }
                       if (validOptions == optTypeValue) {
                           productWithOptions++;
                       } else {
                           badOptions++;
                       }
                       // reset var
                       validOptions = 0;
                   } else {
                       badOptions++;
                   }
               } else {
                   badOptions++;
               }
           } else {
               // product has no options, increment counter.
               productWithNoOptions++;
           }
       } // end if valid qty and qty > 0
    } // end for
	
//	return false;
    // validate quantity. On detail page, minQty is probably 1.
    // On basket, 0 is a valid qty -- means to remove
    if (iTotalQty < minQty) {
        showMessageBox(qtyErrorMsg);
        return false;
    } else {
        if (badOptions > 0) {
          showMessageBox(optionErrorMsg);
          return false;
        } else {
            // if nothing was selected for product with options and
            // there is no product without options
            // and there is a qty greater than minQty then there's an error
            if ( (productWithOptions < 1) && (productWithNoOptions < 1) && (iTotalQty > minQty) ) {
               showMessageBox(optionErrorMsg);
               return false;
            } else {
				return true;
            }
        }
    }
    return bValidationResult;

}