/*
Misc javascript functions used throughout the cart
*/

// -------------------------------------------------------------------
function GoTo(thisURL) {
     //alert(thisURL);
     location = thisURL;
}
// -------------------------------------------------------------------
function OpenWindow(thisURL,x,y) {

	alert(thisURL);

    var gWin;
    if(x == undefined){
        gWin = window.open(thisURL,'GraphicWindow','resizable=0','scrollbars=0');
    }
    else{
        gWin = window.open(thisURL,'GraphicWindow','width='+x+',height='+y+',resizable=0,scrollbars=0');
    }
}


function popup(img,h,w,title){

    var sWidth = screen.width / 2 - w;

     var win = window.open("","graphics","top=100,left=" + sWidth + ",scrollbars=0,resizable=1");
     win.resizeTo(w,h + 125);
     win.document.open("text/html", "replace");
     win.document.write("<html><head><title>"+title+"</title></head><body topmargin=0 leftmargin=0 marginwidth=0 marginheight=0>");
     win.document.write("<img src="+img+" width="+w+" height="+h+"><br>");
     win.document.write("<form><div align=center><input type=button name=Close value=\"Close Window\" onclick=window.close()></div></form>");
     win.document.write("</body></html>");
     win.status = "Zoom Image of " + title;
     win.focus();
}


// -------------------------------------------------------------------
function qtyCheck(form){

     var qtySelected = parseInt(0);

     for(i = 0; i < form.elements.length; i++){

          var fieldName = form.elements[i].name;

          if(fieldName.substring(0,8).toLowerCase() == "quantity"){
               var fieldValue = parseInt(form.elements[i].value);

               if(fieldValue > 0){
                    qtySelected += parseInt(fieldValue);

                        // Check availability

                    var id = fieldName.substring(9,fieldName.length);
                    var availFld = "available|" + id;
                    var minField = "minimum|" + id;

                    var nameFld = "name|" + id;
                    var productName = form.elements[nameFld].value

                    var pattern = /\s{2,}/g;
                    var pName = productName.replace(pattern,"");


                    if(eval(form.elements[availFld])){
                        var qtyAvailable = parseInt(form.elements[availFld].value);
                        if(fieldValue > qtyAvailable){
                            if(qtyAvailable <= 0){
                                alert("Sorry, the '" + pName + "' is not available at this time.");
                            }
                            else{
                                alert("There are only " + qtyAvailable + " of the '" + pName + "s' available.\n\n" +
                                      "Please reduce the quantity so it is equal to or fewer than " + qtyAvailable + " item(s).");
                            }
                            form.elements[i].value = "";
                            form.elements[i].focus();
                            return false;
                        }
                    }
                    if(eval(form.elements[minField])){
                        var qtyMinimum = parseInt(form.elements[minField].value);
                        if(fieldValue < qtyMinimum){
                            alert("You must purchase a minimum of " + qtyMinimum + " '" + pName + "s'.");
                            form.elements[i].value = "";
                            form.elements[i].focus();
                            return false;
                        }
                    }
               }
          }
     }

     if(qtySelected == 0){
          alert("You have not entered a quantity of an item to add to the cart.");
          return false;
     }

return true;
}


// -------------------------------------------------------------------
// Checks quantity, inventory and option selections
function checkInputs(form,sku){

	//var isInventoried = false;
	//var inventoryFld = "inventoried[" + sku + "]";
	//if(form.elements[inventoryFld] && form.elements[inventoryFld].value == "true"){
	//	isInventoried = true;
	//}

	// It's inventoried, get selected quantity
	var qtyFld = "item." + sku + ".quantity";
    var qtySelected = parseInt(0);

    // select box
	if(form.elements[qtyFld].type == "select-one"){
		var qIndex = form.elements[qtyFld].selectedIndex;
		qtySelected = parseInt(form.elements[qtyFld].options[qIndex].value);
	}
    else{
	    // text box
		qtySelected = parseInt(form.elements[qtyFld].value);
	}

	if(isNaN(qtySelected) || qtySelected < 1){
		alert("You have not entered a valid quantity for this item?");
		form.elements[qtyFld].value = "";
		form.elements[qtyFld].focus();
		return false;
	}

	// Now get all options and check against the matrix
	var optionFld = "option." + sku + ".";
	var nameLen = sku.length + 8;

	var Options = new Array();

	for(i = 0; i < form.elements.length; i++){

		var fieldName = form.elements[i].name;
		var fieldType = form.elements[i].type;

		if(fieldName.substring(0,nameLen) == optionFld){

			var fldValue = null;

			if(fieldType == "select-one"){
	            var selectedIndex = form.elements[fieldName].selectedIndex;
				fldValue = form.elements[fieldName].options[selectedIndex].value;
			}
			if(fieldType == "text"){
				fldValue = form.elements[fieldName].value;
			}
			if(fieldType == "radio"){
				var isChecked = false;
				for(j=0; j < form.elements[fieldName].length;j++){
					if(form.elements[fieldName][j].checked == true){
						isChecked = true;
						break;
					}
				}
				if(!isChecked){
					var parts = fieldName.split('.');
					fldValue = "invalid|" + parts[2];
				}
			}

			// Stop here if we find an invalid option
			if(fldValue && fldValue.substring(0,7).toLowerCase() == "invalid"){
				// find the 2 parts of the value
				testFlds = fldValue.split('|');
				var optionName = testFlds[1];
				var message = "You must select an option for '" + optionName +
							  "' before you can add this item to your cart.";
				alert(message);
				if(fieldType == "radio"){
					form.elements[fieldName][0].focus();
				}
				else{
					form.elements[fieldName].focus();
				}
				return false;
			}
		}
    }
return true;
}

// -------------------------------------------------------------------
function showIt(whichEl,classEL){
    if(document.all){
        whichEl = document.all[whichEl];
        classEL = document.all[classEL];
    }
    else{
        whichEl = document.getElementById(whichEl);
        classEL = document.getElementById(classEL);
    }
    whichEl.style.display = (whichEl.style.display == "none" ) ? "" : "none";
    classEL.className = (classEL.className == "subListItem" ) ? "subListItemClicked" : "subListItem";
}


// -------------------------------------------------------------------
function swapStyle(El,styleClass){
    El.className = styleClass;
}

/*
Form submission script for include/mail/mail.php
*/

// -------------------------------------------------------------------


function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}





