//----------------------------------------------------------------------------

// make sure MyWin is global. other javascript functions check it as well as
// parts of the page
var MyWin;

// --------------------------------------------------------------------------
// Actually adds an item the the list
// Contains code for unsubscribing, erases all items in PrefsBox,
// submits form (saves changes) automatically
// --------------------------------------------------------------------------
function UnSub(Form,CMD,PrefsBox)
{
    if (CMD || confirm("Are you sure you want to unsubscribe from all categories? You will not recieve any notifications.")) {
        var leng = PrefsBox.options.length;
	for(var i=0; i<leng; i++) {
	    PrefsBox.options[0] = null;
	}
        Form.HiddenChangedCats.value = "2";
	PrefsBox.options[0] = Spacer();
        if (Form.formtype.value != "content") {
	    PrefsBox.options[0] = new Option(Form.Master.options[0].text, Form.Master.options[0].value);
	    if (CMD) {} else
		alert('Since you have no product categories selected, All Agilent Categories has been added to your Preferences List. If you would like to unsubscribe from the service, you can visit the E-mail Update Service Homepage or go to Step 1 and do so.');

	}
    }
    return 1;
}


//------------------------------------------------------------------------------
//  Added by siva gopal
//  can be removed once the ENP project is done

////////////////////////
////////////////////////
////////////////////////
  function AddBtn2(Form, PrefsBox) {
    var i;
    var g;
    var j;
    var f;
    var skip=0;
    var end=0;
    var end2=0;
    var others=0;
    for(i=1; i<Form.Master2.options.length; i++) {//skip first element
      if (Form.Master2.options[i].selected == true) {
        var others = 1;
        break;
      }
    }
    if (PrefsBox.options.length && PrefsBox.options[0].value == "SPACER2")
      PrefsBox.options[0]=null;
    if (IsAll(Form.Master2.options[0].value) && (Form.Master2.options[0].selected == true)) {
      if (PrefsBox.options.length && (PrefsBox.options[0].value == Form.Master2.options[0].value))
        return 1;
      if ((PrefsBox.options.length != 0) || (others != 0)) {
        if (others != 0)
          alert('All Agilent Categories has been added to your list of preferences, however your other selections could not be added due to this.');
        if ((others != 0) || confirm("To select All Agilent Categogories, your preferences list must be cleared. Do you want to clear your preferences list?")) {
          UnSub(Form,1);
          PrefsBox.options[0] = new Option(Form.Master2.options[0].text, Form.Master2.options[0].value);
          return 1;
        } else {
          return 1;
        }
      }
    } else if ((PrefsBox.options.length) && (PrefsBox.options[0].value == Form.Master2.options[0].value)) {
      if (Form.Master2.selectedIndex != -1) {
        //  PrefsBox.options[0] = null; //removes All Categories options of specific categories are selected
        //  alert('Your Preferences selection of All Agilent Categories has been removed since you selected a specific category or categories.');
      }
    }
    for(i=0; i<Form.Master2.options.length; i++) {
      if (! Form.Master2.options[i].selected)
        continue;
      if (Form.Master2.options[i].value.indexOf("SKIPTHISITEM") != -1)
        continue;
      end=0;
      //Tests to see if something...???
//      for(j=i; j<PrefsBox.options.length; j++) {
//        if (Form.Master2.options[j].value.indexOf("::") == -1) {
//          end=1;
//        } else if ((Form.Master2.options[i].value == PrefsBox.options[j].value)) {
//          end=1;
//          break;
//        }
//      }
//      if (end)
//        continue;
      skip=0; //reset skip variable
      //Checks to see if the major category selected also has subcategories selected
      //  (wont add all subcats if specific subcats are selected)
      for(j=i; j<Form.Master2.options.length; j++) {
       if (Form.Master2.options[i].selected) {
        if ((Form.Master2.options[j].value.indexOf(
              Form.Master2.options[i].value+"::") != -1) &&
              (Form.Master2.options[j].selected)) {
                      skip=1;
                      break;
        } else if (Form.Master2.options[j].value.indexOf(Form.Master2.options[i].value) == -1) {
          break;
        }
       }
      }
        // IF SELECTED IS A PROD CATEGORY
        if ((Form.Master2.options[i].value.indexOf("::") == -1) &&
          (skip == 0)) {
          PrefsBox.options[PrefsBox.options.length]
          = new Option(Form.Master2.options[i].text,Form.Master2.options[i].value);
          //Adds subcategory(ies)
          for(g=i; g<Form.Master2.options.length; g++) {
            if (Form.Master2.options[g].value.indexOf(
              Form.Master2.options[i].value+"::") == -1)
                    continue;
              PrefsBox.options[PrefsBox.options.length]
              = new Option(Form.Master2.options[g].text,Form.Master2.options[g].value);
          }//for
        } else {
        //IF SELECTED IS A PROD SUBCATEGORY
          if (Form.Master2.options[i].value.indexOf("::") == -1) {
              //is a category, not subcategory
              PrefsBox.options[PrefsBox.options.length]
                = new Option(Form.Master2.options[i].text,Form.Master2.options[i].value);
              //starts searching for the subcategories selected in the major category
              for(j=i; j<Form.Master2.options.length; j++) {
                if ((Form.Master2.options[j].value.indexOf(Form.Master2.options[i].value+"::") != -1) &&
                    (Form.Master2.options[j].selected == true)) {
                            end2=0;
                            //checks so subcats wont be added if exists
                            for(f=0; f<PrefsBox.options.length; f++) {
                              if ((PrefsBox.options[f].value == Form.Master2.options[j].value) &&
                                  (PrefsBox.options[f].value.indexOf(Form.Master2.options[j].value+"::") != -1)) {
                                Form.Master2.options[j].selected=false;
                                end2=1;
                                break;
                              }
                            }
                            if (end2 == 1) continue;
                            PrefsBox.options[PrefsBox.options.length]
                            = new Option(Form.Master2.options[j].text,Form.Master2.options[j].value);
                            Form.Master2.options[j].selected = false;
                } else if (Form.Master2.options[j].value.indexOf(Form.Master2.options[i].value) == -1) {//if
                    continue;//break;
                }//if of if..else if
              }//for
          } else {
            for(j=0; j<Form.Master2.options.length; j++) {
              if (Form.Master2.options[i].value.indexOf(Form.Master2.options[j].value+"::") != -1) {
                PrefsBox.options[PrefsBox.options.length] = new Option(Form.Master2.options[j].text, Form.Master2.options[j].value);
                break;
              }
            }
            PrefsBox.options[PrefsBox.options.length] = new Option(Form.Master2.options[i].text, Form.Master2.options[i].value);
          }//if
        }//END OF IF..ELSE
      }
    if ((! PrefsBox.options.length) || (PrefsBox.options.length == 0)) {
      PrefsBox.options[0] = Spacer();
      return 1;
    }
    SortOList(Form.Master2, PrefsBox);

    return 1;
  }



  function RemoveBtn2(Form,PrefsBox) {
    //General note: starting counters at end of lists are used here because length of list
    //    is changed and Form.List.options.length becomes unreliable when going from beginning
    var i=0;
    var g=0;
    var j=0;
    var skip=0;
    var skip2=0;
    var t1 = (PrefsBox.options.length-1);
    var t2;
    for(i=t1; i>-1; --i) {  //goes from end of list
      if ((PrefsBox.options[i].value == "SPACER2")) continue;// || (PrefsBox.options[i].value == Form.Master.options[0].value)) continue;
      skip=0;
      skip2=0;
      if (PrefsBox.options[i].selected == false) continue;
      t2=(PrefsBox.options.length-1);
      if (PrefsBox.options[i].value.indexOf("::") != -1) {
        for(j=t2; j>-1; --j) {
          if (PrefsBox.options[j].value == ParentName(PrefsBox.options[i].value)) {
            if (skip==0) {
              PrefsBox.options[j] = null;             //removes parent of childless
              --i;
              continue;
            } else
              PrefsBox.options[j].selected = false;   //deselects parent
            break;        //end loops once it reaches parent
          } //if
          if ((PrefsBox.options[j].value.indexOf( ParentName( PrefsBox.options[i].value ) + "::" ) != -1 )
              && (PrefsBox.options[j].value != ParentName(PrefsBox.options[i].value))) { //checks for same parent and not being selected
              if (PrefsBox.options[j].selected == false) {
                      skip=1;
              } else {
                      PrefsBox.options[j] = null;
                      --i;
                      skip2=1;
              }
        continue;
          } //if
        }   //for
      }
      if (skip2) continue;
      if (PrefsBox.options[i].value.indexOf("::") == -1) {
        if (confirm("Are you sure you want to remove '"+PrefsBox.options[i].text+((i == 0)?("'?"):("' and all of its subcategories?")))) {
          for(g=(PrefsBox.options.length-1); g>-1; --g) {
              if (PrefsBox.options[g].value.indexOf(PrefsBox.options[i].value+"::") != -1) {
                  PrefsBox.options[g]=null;
              }
          }
          PrefsBox.options[i] = null;
        }
      } else if (skip == 0) {
        for(j=0; j<PrefsBox.options.length; j++) {
          if (PrefsBox.options[i].value.indexOf(PrefsBox.options[j].value+"::")) {

          } //end of if
        } //end of for
      } //end of if (! skip)
    } //end of for
    if ((PrefsBox.options.length == 0)){
        PrefsBox.options[0] = Spacer();
    }
  }

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------

// --------------------------------------------------------------------------
//Make sure all 'Prefs' are selected so they ACTUALLY get through to the script
// --------------------------------------------------------------------------
function SelectAll(Form,PField,PrefsBox) {
    PField.value = "";
    for(var i=0; i< PrefsBox.options.length; i++) {
        PField.value += PrefsBox.options[i].value+",";
    }
    //alert(PField.value);
}

function AddItemsToList(AddItem, FromWindow) {
    var i=0;
    var OneFound=false;
    //Removes SPACER
    if ((document.NotifyForm.Prefs.options.length == 1) && (document.NotifyForm.Prefs.options[0].value == "SPACER")) {
	document.NotifyForm.Prefs.options[0] = null;
    }
    var SuccessFound = 0;
    //tests if item already exists
    for(i=0; i<(document.NotifyForm.Prefs.options.length) && (ParentName(AddItem.value) != AddItem.value); i++) {
	if (document.NotifyForm.Prefs.options[i].value == AddItem.value) {
	    SuccessFound = 1;
	    continue;
	}
    }
    //alerts user that item already exists
    if (SuccessFound) {
	FromWindow.alert("You already have that item selected.");
	return 0;
    }

    //Tests for existence of parent item in user prefs (not all agilent prefs)
    if (GetOIndex(document.NotifyForm.Prefs.options, ParentName(AddItem.value)) == -1) {
	document.NotifyForm.Prefs.options[
	    document.NotifyForm.Prefs.options.length
	] = new Option(
	    FromWindow.document.PrefsForm.Agilent.options[
		GetOIndex(FromWindow.document.PrefsForm.Agilent.options,ParentName(AddItem.value))
	    ].text
	    ,
	    ParentName(AddItem.value)
	);
	document.NotifyForm.HiddenChangedCats.value = "1";
    }

    //Adds all subcategories if a parent category is added
    if ((ParentName(AddItem.value) == AddItem.value)) {
	for(i=0; i<FromWindow.document.PrefsForm.Agilent.options.length; i++) {
	    if ((GetOIndex(document.NotifyForm.Prefs.options, FromWindow.document.PrefsForm.Agilent.options[i].value) == -1)
	    && (ParentName(FromWindow.document.PrefsForm.Agilent.options[i].value) == AddItem.value)) {
		document.NotifyForm.Prefs.options[document.NotifyForm.Prefs.options.length] =
		new Option(FromWindow.document.PrefsForm.Agilent.options[i].text,FromWindow.document.PrefsForm.Agilent.options[i].value);
		OneFound=true;
		document.NotifyForm.HiddenChangedCats.value = "1";
	    } else {
		if (OneFound)
		    continue;
	    }
	}
    }
    document.NotifyForm.Prefs.options[document.NotifyForm.Prefs.options.length] = new Option(AddItem.text, AddItem.value);
    document.NotifyForm.HiddenChangedCats.value = "1";

    SortOList(FromWindow.document.PrefsForm.Agilent,document.NotifyForm.Prefs);
    FromWindow.alert("\""+ToUserText(AddItem.text)+"\" has been added to your list of preferences"+
			(((ParentName(AddItem.value) == AddItem.value)
			&& (Children(FromWindow.document.PrefsForm.Agilent,FromWindow.document.PrefsForm.Agilent.selectedIndex) > 0))
				?(" (along with its subcategories)")
				:(""))
			+".");
}


//Removes an item from the list, list will automatically update
//itself and move concurrent options down to replace removed option
function RemoveFromList(Form) {
    vari=0;
    if (Form.Prefs.selectedIndex < 0) {
	return 1;
    }
    var Checked = Form.Prefs.options[Form.Prefs.selectedIndex];
    var Parent = ParentName(Checked.value);
    if ((Parent == Checked.value) //if the selected item is a top category
	// &&
	//Turns up error when testing for selIdx+1 if it is last item on list
        // (Form.Prefs.selectedIndex != (Form.Prefs.options.length-1))
	// &&
	//if the next item is a subcategory of the selected item
	// (ParentName(Form.Prefs.options[Form.Prefs.selectedIndex+1].value) == Parent)
    ) {
	if ( (Children(Form.Prefs, Form.Prefs.selectedIndex) == 0) ||
	    confirm("Are you sure you want to remove "+Checked.text+" and all of its subcategories?")) {
	    //deletes each child of the category
	    while ((Form.Prefs.selectedIndex != (Form.Prefs.options.length-1))
		    && ParentName(Form.Prefs.options[Form.Prefs.selectedIndex+1].value) == Parent) {
		Form.Prefs.options[Form.Prefs.selectedIndex+1] = null;
		Form.HiddenChangedCats.value = "1";
		if ((Form.Prefs.options.length-1) == Form.Prefs.selectedIndex)
		    break;
	    }
	    Form.Prefs.options[Form.Prefs.selectedIndex] = null;
	}
    } else {//if not a top level category
	if ((Form.Prefs.options.selectedIndex == (Form.Prefs.options.length-1)) //If it is the last item on the list
	    && (Form.Prefs.options.selectedIndex != 0)	// if it is first item on list
	    ||
	    ((ParentName(Form.Prefs.options[Form.Prefs.selectedIndex+1].value)) != (ParentName(Form.Prefs.options[Form.Prefs.selectedIndex].value)))
	) {
	    if ((Form.Prefs.options[Form.Prefs.selectedIndex-1].value) == (ParentName(Form.Prefs.options[Form.Prefs.selectedIndex].value))) {
		Form.Prefs.options[Form.Prefs.selectedIndex-1] = null; //erase parent if it is only one left in category
		Form.HiddenChangedCats.value = "1";
	    }
	}
	Form.Prefs.options[Form.Prefs.selectedIndex] = null;
        Form.HiddenChangedCats.value = "1";
    }
    if (Form.Prefs.options.length == 0) {
	Form.Prefs.options[0] = Spacer();
    }
    return 1;
}

//Opens window that contains info for modifying pref categories
function NewWindow(Form, Page) {
    if (MyWin && !MyWin.closed) { MyWin.close(); }
    var Width = 425;
    var Height = 390;
    var WinArgs = "width="+Width+",";
    WinArgs += "innerWidth="+Width+",";
    WinArgs += "height="+Height+",";
    WinArgs += "innerHeight="+Height+",";
    WinArgs += "status=no,location=no,menubar=no,scrollbars=yes,toolbar=no,resizable=yes,screenX="+(screen.width-Width)+",screenY=0";

    MyWin = window.open(Page, "", WinArgs);
}

function SortOList(TotalMaster,Child) {	//Sort Options List
    //TotalMaster refers to the definition array, the correct sort order
    //Master contains the correct sort for all elements
    //Child is the array to be sorted
    //'array' means array of Option objects
    Master = new Array();
    var i=0;
    var g=0;
    //Populate Master array
    for(i=0; i<TotalMaster.options.length; i++) {
	if (GetOIndex(Child.options, TotalMaster.options[i].value) != -1) {
	    Master[Master.length] =
		new Option(TotalMaster.options[i].text,TotalMaster.options[i].value);
	}
    }
    //Clears old array
    var Length = Child.options.length; //kept using new length value, not original
    for(i=0; i<Length; i++) {
	Child.options[0] = null;//just cycles through and deletes the first option x times
    }
    //Forms new array
    for(i=0; i<Master.length; i++) {
	Child.options[Child.options.length] = new Option(Master[i].text, Master[i].value);
    }
}

//Splits string separated by "::" and returns the array
function GetValuesArray(ScalarValue) {
    if (ScalarValue.indexOf("::") == -1) {
	return 0;
    }
    var items = ScalarValue.split("::");
    return items;
}

	//Finds Parent Name of item in "xyz::abc" format (xyz is item name)
	function ParentName(Str) {
		if (GetValuesArray(Str)==0) {
			return Str;
		} else {
			var Items = GetValuesArray(Str);
			return Items[0];
		}
	}

	//Finds name of item in "xyz::abc" format (abc is item name)
	function ItemName(Str) {
		if (GetValuesArray(Str)==0) {
			return Str;
		} else {
			var Items = GetValuesArray(Str);
			return Items[1];
		}
	}

	//Removes leading "  - " from displayed Object.text values
	function ToUserText(Str) {
		re = /^[^a-zA-Z0-9]*(.+)$/gi;
		Str.search(re);
		return RegExp.$1;
	}

  function NumKids(Box,Parent) {//number of children of a parent category
    var children=0;
    for(var i=0; i<Box.options.length; i++) {
      if (ParentName(Box.options[i].value) == Parent) {
        children++;
      }
    }
    return children;
  }

	//Searches an array of Option objects and returns the index
	//of the item with the same value as TextStr
	function GetOIndex(OArray, TextStr) {
		for(var i=0; i<OArray.length; i++) {
			if (OArray[i].value == TextStr) {
				return i;
			}
		}
		return -1;
	}

	//CHECKS FOR ERRORS IN A NEW USER'S FORM
	function NewUserValidation(Form) {
		var Output="";
		//USERNAME
		re = /([^a-zA-Z0-9_]+)/g;
		if (Form.username.value == "") {
			Output += "Please enter your desired username.\n";
		} else {
			if (Form.username.value.search(re) != -1) {
				Output += "You username can only contain letters, numbers and '_'.\n";
			}
		}

		//PASSWORDS
		if ((Form.password.value.length > 12 || Form.passwordconfirm.value.length > 12)
			|| (Form.password.value.length < 6 || Form.passwordconfirm.value.length < 6)) {
			Output += "Your password must be between 6 and 12 characters long.\n";
		} else {
		if (Form.password.value != "" && Form.passwordconfirm.value != "" && (Form.password.value != Form.passwordconfirm.value)) {
			Output += "Your passwords do not match\n";
		} else {
			if (Form.password.value == "") {
				Output += "Please enter a password\n";
			}
			if (Form.passwordconfirm.value == "") {
				Output += "Please re-enter your password in the Password Confirm field\n";
			}
		}
		}
		//EMAIL
		re = /^(.+)\@(.+)$/g;
		if (Form.email.value.search(re) == -1) {
			Output += "You must enter a valid and complete e-mail address\n";
		}

//    if ((! Form.type_xyz[0].checked) && (! Form.type_xyz[1].checked)) {
//      Output += "You do not have a preferences for Step 1 selected (Yes/No).\n";
//    }

//    if ((! Form.AllCategories[0].checked) && (! Form.AllCategories[1].checked)) {
//      Output += "You do not have an option in Step 3 (notifications for either all categories or selected areas of interest) selected.\n";
//    }

		if (Output != "") {
			alert("We have encountered the following errors with your request:\n\n"+Output);
			return 0;
		}

//		if (Form.Prefs.options.length == 1 && Form.Prefs.options[0].value == "SPACER" && Form.AllCategories[1].checked) {
//			if (confirm("Are you sure you want to save your changes without any product categories selected. You will not receive any notifications.")) {
//				return 1;
//			}
//			return 0;
//		}
//    for(var i=0; i<Form.elements.length; i++) {
//         if (! confirm(Form.elements[i].name))
//            break;
//    }
    if (Form.type_xyz.checked == false) {
      if (confirm("You are set to not recieve e-mail notifications (Step 1). Are you sure you want to continue?")) {
        return 1;
      } else {
        return 0;
      }
    }
		return 1;
	}

	//CHECKS FOR ERRORS IN AN EXISTING USER'S FORM
	function ExistingUserValidation(Form) {
		var Output="";
		//USERNAME
		//Not changeable in existing user options
    var Ask = (((Form.HiddenChangedCats.value=="2") || (Form.formtype.value == "newuser"))?1:0);
		//PASSWORDS
		if (Form.password.value != "" && Form.passwordconfirm.value != "") {
			if ((Form.password.value == "" && Form.passwordconfirm.value != "") ||
			    (Form.password.value != "" && Form.passwordconfirm.value == "")) {
				  Output += "Please enter your password in both fields if you wish to change it, otherwise leave both fields blank.\n";
		  } else {
			if (Form.password.value != Form.passwordconfirm.value) {
				Output += "Your passwords do not match\n";
			}
      }
		} else {
			;//dont do anything, changing password is not required
		}

		//EMAIL
		re = /^(.+)\@(.+)$/g;
		if (Form.newemail.value.search(re)
			== -1 && Form.newemail.value != "") {
			Output += "You must enter a valid and complete e-mail address\n";
		} else
			if (Form.newemail.value == "") {
			;
			//dont do anything, changing email is not required
			}
		if (Output != "") {
			alert(
"We have encountered the following errors with your request:\n\n"+Output
			);
			return 0;
		} else {
		if ((Form.Prefs.options.length == 1)
		//if length of options is 1 item
        && (Form.Prefs.options[0].value == "SPACER")
	//and that item is SPACER
//        && (Form.AllCategories.checked)
	//and "Send me all product category notifications" isnt checked
        && (Form.HiddenChangedCats.value.search(/2/) == -1)
        ) {
			    if (confirm("At least one area of interest is not selected. If you do not select at least one you will not recieve any notifications. "
              +"Are you sure you want to continue?")) {
				        return 1;
			    }
			    return 0;//0 if user cancels confirm
		} //if (a&&b&&c)
      if (Form.HiddenChangedCats.value == "2") {
        return 1;
      }
    }//else
		return 1;
	}

	function Children(List, Item) {
		//Note: IF Item IS NOT A PARENT, ONLY Item's PARENT'S CHILDREN WILL BE COUNTED
		var Children=0;
		var i=0;
		if (List.options.selectedIndex == (List.options.length-1))
			return 0;
		if (ParentName(List.options[Item].value) != List.options[Item].value) {
			Item = GetOIndex(List.options, ParentName(List.options[Item].value));
		}
		i = Item;
		while(ParentName(List.options[i].value) == List.options[Item].value) {
			if (i == Item) {
				i++;
				continue;
			}
			i++;
			Children++;
			if (i == (List.options.length-1)) {
				break;
			}
		}
		return Children;
	}

  //Checks other forms to make sure they are correct
	function ConfirmCC(Form,cmd) {
    var Err="";
    var newname = "add_piece_"+cmd;
    var re = /[\n\r]*/g;
    var Content = Form.content.value;
    Content.replace(re,""); //I dont want to count newlines (\n and \r) in count
		if (Form.Prefs.length < 1 || Form.Prefs[0].value == "SPACER") {
		  Err += "You must make product category selection(s) before you continue.\n";
	  }

    ////Other fields of possible errors
    if (Form.countries.selectedIndex == -1) {
      Err += "You must select a Country.\n";
    }
    if (Form.title.value == "") {
      Err += "You must enter a Title for the content.\n";
    }
    if (Content == "") {
      Err += "You must enter some content for this item.\n";
    }

    switch (cmd) {
      case "event":
	if (Content.length > 500)
      	  Err += "Please decrease the size of your content (Abstract) field to 500 characters or less.\n";
        if (Form.content_url.value == "") {
          Err += "You must enter a valid URL for the content on the external web.\n";
        }
        if ((Form.exp.value == "") || (Form.exp.value.match(/[^\d\/]/gi)) || (! Form.exp.value.match(/[\d]+\/[\d]+\/[\d]+/gi))) {
          Err += "The Expiration Date contains invalid information. It must contain a number (days to expire).\n";
        }
        break;
      case "prodinfo":
	if (Content.length > 500)
      	  Err += "Please decrease the size of your content (Abstract) field to 500 characters or less.\n";
        if (Form.content_url.value == "") {
          Err += "You must enter a valid URL for the content on the external web.\n";
        }
        break;
      case "support":
	if (Content.length > 500)
      	  Err += "Please decrease the size of your content (Abstract) field to 500 characters or less.\n";
        if (Form.content_url.value == "") {
          Err += "You must enter a valid URL for the content on the external web.\n";
        }
        break;
      case "newsletter":
	if (Content.length > 750)
      	  Err += "Please decrease the size of your content (Abstract) field to 750 characters or less.\n";
        if (Form.content_url.value == "") {
          Err += "You must enter a valid URL for the content on the external web.\n";
        }
        break;
      default:
        Err += "\n-- AN ERROR OCCURRED IN PROCESSING THE FORM\nPLEASE TRY AGAIN LATER OR CONTACT THE ADMINISTRATOR IF YOU STILL HAVE PROBLEMS --\n";
    }
    ///end

    if (Err == "") {
      for(var i=0; i<Form.elements.length; i++) {
        if (Form.elements[i].name == newname) {
          Form.elements[i].value = 1;
        }
      }
      SelectAll(Form,Form.P,Form.Prefs);
      Form.submit();
      return 1;
    }
    alert("We found erros in your entry:\n\n"+Err);
		return 0;
	}

	//Manages which checkboxes are selected (All or other) and adds some automation
	function CheckSelectedTypes(Form,Btn) {
		if (Btn == "type_all") {
		  if (Form.type_all.checked == true) {
			Form.type_ss.checked=false;
			Form.type_product.checked=false;
			Form.type_event.checked=false;
			Form.type_newsletters.checked=false;
		  } else {
		  if (Form.type_all.checked == false) {
		  		//checks each type and if none are selected keeps type_all selected
				if (Form.type_ss.checked == true)
					;
				else if (Form.type_product.checked == true)
					;
				else if (Form.type_event.checked == true)
					;
				else if (Form.type_newsletters.checked == true)
					;
				else
					Form.type_all.checked=true;
		  }
		  }
		} else {// if Btn is not type_all
				if (Form.type_ss.checked               == true &&
						Form.type_product.checked      == true &&
						Form.type_event.checked        == true &&
						Form.type_newsletters.checked  == true) {
								Form.type_ss.checked          = false;
								Form.type_product.checked     = false;
								Form.type_event.checked       = false;
								Form.type_newsletters.checked = false;
								Form.type_all.checked         = true;
				} else {//begin else 3

				if (Form.type_ss.checked == true)
					Form.type_all.checked = false;
				else if (Form.type_product.checked == true)
					Form.type_all.checked = false;
				else if (Form.type_event.checked == true)
					Form.type_all.checked = false;
				else if (Form.type_newsletters.checked == true)
					Form.type_all.checked = false;
				else {
						for(var i=0; i<Form.elements.length; i++) {
							if (Form.elements[i].name == Btn && Form.elements[i].type == Btn)
								Form.elements[i].checked = true;
						}
				     }
				} //end else 3
		}
	}

  function CheckCat(Form) {
    //if (Form.formtype.value == "content")
      return 1;
    if (Form.Master.selectedIndex == -1)
      return 1;
    if (Form.AllCategories[0].checked) {
      Form.AllCategories[1].checked = true;
      return 1;
    } else if (Form.AllCategories[1].checked) {
      return 1;
    } else {
      Form.AllCategories[1].checked = true;
      return 1;
    }
  }

  function CheckCat2(Form) {
    if (Form.formtype.value == "content")
      return 1;
    if ((Form.Prefs.options.length < 1) ||
        (Form.Prefs.options[0].value == "SPACER"))
      Form.AllCategories[0].checked = true;
    else
      Form.AllCategories[1].checked = true;
  }
  ////////////////////////
  ////////////////////////
  ////////////////////////
  function RemoveBtn(Form,PrefsBox) {
    //General note: starting counters at end of lists are used here because length of list
    //    is changed and Form.List.options.length becomes unreliable when going from beginning
    var i=0;
    var g=0;
    var j=0;
    var skip=0;
    var skip2=0;
    var t1 = (PrefsBox.options.length-1);
    var t2;
    for(i=t1; i>-1; --i) {  //goes from end of list
      if ((PrefsBox.options[i].value == "SPACER")) continue;// || (PrefsBox.options[i].value == Form.Master.options[0].value)) continue;
      skip=0;
      skip2=0;
      if (PrefsBox.options[i].selected == false) continue;
      t2=(PrefsBox.options.length-1);
      if (PrefsBox.options[i].value.indexOf("::") != -1) {
        for(j=t2; j>-1; --j) {
          if (PrefsBox.options[j].value == ParentName(PrefsBox.options[i].value)) {
            if (skip==0) {
              PrefsBox.options[j] = null;             //removes parent of childless
              --i;
              continue;
            } else
              PrefsBox.options[j].selected = false;   //deselects parent
            break;        //end loops once it reaches parent
          } //if
          if ((PrefsBox.options[j].value.indexOf( ParentName( PrefsBox.options[i].value ) + "::" ) != -1 )
              && (PrefsBox.options[j].value != ParentName(PrefsBox.options[i].value))) { //checks for same parent and not being selected
              if (PrefsBox.options[j].selected == false) {
                      skip=1;
              } else {
                      PrefsBox.options[j] = null;
                      --i;
                      skip2=1;
              }
        continue;
          } //if
        }   //for
      }
      if (skip2) continue;
      if (PrefsBox.options[i].value.indexOf("::") == -1) {
        if (confirm("Are you sure you want to remove '"+PrefsBox.options[i].text+((i == 0)?("'?"):("' and all of its subcategories?")))) {
          for(g=(PrefsBox.options.length-1); g>-1; --g) {
              if (PrefsBox.options[g].value.indexOf(PrefsBox.options[i].value+"::") != -1) {
                  PrefsBox.options[g]=null;
              }
          }
          PrefsBox.options[i] = null;
          
        }
      } else if (skip == 0) {
        for(j=0; j<PrefsBox.options.length; j++) {
          if (PrefsBox.options[i].value.indexOf(PrefsBox.options[j].value+"::")) {

          } //end of if
        } //end of for
      } //end of if (! skip)
    } //end of for
    if ((PrefsBox.options.length == 0)){
     	PrefsBox.options[0] = Spacer();
    }
  } //end of function

  ////////////////////////
  ////////////////////////
  ////////////////////////
  function AddBtn(Form, PrefsBox) {
    var i;
    var g;
    var j;
    var f;
    var skip=0;
    var end=0;
    var end2=0;
    var others=0;
    for(i=1; i<Form.Master.options.length; i++) {//skip first element
      if (Form.Master.options[i].selected == true) {
        var others = 1;
        break;
      }
    }
    if (PrefsBox.options.length && PrefsBox.options[0].value == "SPACER")
      PrefsBox.options[0]=null;
    if (IsAll(Form.Master.options[0].value) && (Form.Master.options[0].selected == true)) {
      if (PrefsBox.options.length && (PrefsBox.options[0].value == Form.Master.options[0].value))
        return 1;
      if ((PrefsBox.options.length != 0) || (others != 0)) {
        if (others != 0)
          alert('All Agilent Categories has been added to your list of preferences, however your other selections could not be added due to this.');
        if ((others != 0) || confirm("To select All Agilent Categogories, your preferences list must be cleared. Do you want to clear your preferences list?")) {
          UnSub(Form,1);
          PrefsBox.options[0] = new Option(Form.Master.options[0].text, Form.Master.options[0].value);
          return 1;
        } else {
          return 1;
        }
      }
    } else if ((PrefsBox.options.length) && (PrefsBox.options[0].value == Form.Master.options[0].value)) {
      if (Form.Master.selectedIndex != -1) {
    //      PrefsBox.options[0] = null; //removes All Categories options of specific categories are selected
    //      alert('Your Preferences selection of All Agilent Categories has been removed since you selected a specific category or categories.');
      }
    }
    for(i=0; i<Form.Master.options.length; i++) {
      if (! Form.Master.options[i].selected)
        continue;
      if (Form.Master.options[i].value.indexOf("SKIPTHISITEM") != -1)
        continue;
      end=0;
      //Tests to see if something...???
//      for(j=i; j<PrefsBox.options.length; j++) {
//        if (Form.Master.options[j].value.indexOf("::") == -1) {
//          end=1;
//        } else if ((Form.Master.options[i].value == PrefsBox.options[j].value)) {
//          end=1;
//          break;
//        }
//      }
//      if (end)
//        continue;
      skip=0; //reset skip variable
      //Checks to see if the major category selected also has subcategories selected
      //  (wont add all subcats if specific subcats are selected)
      for(j=i; j<Form.Master.options.length; j++) {
       if (Form.Master.options[i].selected) {
        if ((Form.Master.options[j].value.indexOf(
              Form.Master.options[i].value+"::") != -1) &&
              (Form.Master.options[j].selected)) {
                      skip=1;
                      break;
        } else if (Form.Master.options[j].value.indexOf(Form.Master.options[i].value) == -1) {
          break;
        }
       }
      }
        // IF SELECTED IS A PROD CATEGORY
        if ((Form.Master.options[i].value.indexOf("::") == -1) &&
          (skip == 0)) {
          PrefsBox.options[PrefsBox.options.length]
          = new Option(Form.Master.options[i].text,Form.Master.options[i].value);
          //Adds subcategory(ies)
          for(g=i; g<Form.Master.options.length; g++) {
            if (Form.Master.options[g].value.indexOf(
              Form.Master.options[i].value+"::") == -1)
                    continue;
              PrefsBox.options[PrefsBox.options.length]
              = new Option(Form.Master.options[g].text,Form.Master.options[g].value);
          }//for
        } else {
        //IF SELECTED IS A PROD SUBCATEGORY
          if (Form.Master.options[i].value.indexOf("::") == -1) {
              //is a category, not subcategory
              PrefsBox.options[PrefsBox.options.length]
                = new Option(Form.Master.options[i].text,Form.Master.options[i].value);
              //starts searching for the subcategories selected in the major category
              for(j=i; j<Form.Master.options.length; j++) {
                if ((Form.Master.options[j].value.indexOf(Form.Master.options[i].value+"::") != -1) &&
                    (Form.Master.options[j].selected == true)) {
                            end2=0;
                            //checks so subcats wont be added if exists
                            for(f=0; f<PrefsBox.options.length; f++) {
                              if ((PrefsBox.options[f].value == Form.Master.options[j].value) &&
                                  (PrefsBox.options[f].value.indexOf(Form.Master.options[j].value+"::") != -1)) {
                                Form.Master.options[j].selected=false;
                                end2=1;
                                break;
                              }
                            }
                            if (end2 == 1) continue;
                            PrefsBox.options[PrefsBox.options.length]
                            = new Option(Form.Master.options[j].text,Form.Master.options[j].value);
                            Form.Master.options[j].selected = false;
                } else if (Form.Master.options[j].value.indexOf(Form.Master.options[i].value) == -1) {//if
                    continue;//break;
                }//if of if..else if
              }//for
          } else {
            for(j=0; j<Form.Master.options.length; j++) {
              if (Form.Master.options[i].value.indexOf(Form.Master.options[j].value+"::") != -1) {
                PrefsBox.options[PrefsBox.options.length] = new Option(Form.Master.options[j].text, Form.Master.options[j].value);
                break;
              }
            }
            PrefsBox.options[PrefsBox.options.length] = new Option(Form.Master.options[i].text, Form.Master.options[i].value);
          }//if
        }//END OF IF..ELSE
      }
    if ((! PrefsBox.options.length) || (PrefsBox.options.length == 0)) {
      PrefsBox.options[0] = Spacer();
      return 1;
    }
    SortOList(Form.Master, PrefsBox);

    return 1;
  }
  function IsAll(Str) {
    if (Str == '0AAgilent')
      return 1;
    return 0;
  }
  function Spacer() {
    var SpacerObj = new Option("< NO CATEGORIES SELECTED >", "SPACER");
    return SpacerObj;
  }

  //Uses a link and will go somewhere without using the URL
  function SpecialSubmit(Form, Cmd) {
    if (Form.elements.length) {
      Form.Command.value = Cmd;
      Form.submit();
    }
  }

  function Preview(H, Form, File) {
    var SHeader = "Welcome to this Special Edition of your Test & Measurement Update Service from Agilent Technologies. As you requested, we are sending you this special update containing information about a time-sensitive event, firmware upgrade, software update, or driver.";
    var Header  = "Welcome to the latest edition of your Test & Measurement Update Service from Agilent Technologies.\n\nAs you requested, we are sending you all of the new items that match your interests. To quickly access the latest information on the topics that interest you, just click on the hyperlink provided.\n\nYou can always view and update your preferences or cancel your subscription to the Update Service at any time. Just visit our web site at http://www.agilent.com/find/notifyme";
    var Footer = "\n\nBest Regards,\n\nAgilent Technologies\nInnovating the HP Way\n\n---------- Contact Information ----------\n";
    Footer += "You can always send your questions and comments about our E-mail Update Service to notify_me@agilent.com.\n\nYou can also unsubscribe from the E-mail Update Service at any time.  Login to our web site, send a request via e-mail, or reply to this message and type \"Unsubscribe\" on the subject line.\n\nIf you are unsure where to send your request, or if you need information about your local Agilent office, please Contact Us.\n\nFor information that governs all of our e-mail correspondence with you, please review Agilent's Online Privacy Statement.  Please direct any questions about Agilent's privacy program to privacy_advocate@agilent.com.";

    var Titles   = new Array("prodinfo","newsletter","support","event");
    var Readable = new Array("Product Information", "Monthly Feature", "Support & Service Information", "Events");

    var TOC = Readable[FindIndex(Titles, Form.ctype.value)]+"\n"+"- "+Form.Title.value;

    var Title = ((Form.formtype.value == "admin")?Form.Title.value:Form.title.value);
    var Message = ((Form.formtype.value=="admin")?Form.Content.value:Form.content.value);
    var URL = Form.content_url.value;
    var PrevCH="";
    if (Form.ctype.value == "support" || Form.csubtype.value == "specialevents") {
      PrevCH += SHeader+"\n\n";
    } else {
      PrevCH += Header+"\n\n";
    }
    PrevCH += TitleIze("Table of Contents") + "\n" + TOC +"\n\n";
    PrevCH += TitleIze(Readable[FindIndex(Titles, Form.ctype.value)])+"\n"+Title+"\n"+Message+"\nFor more information:\n"+URL;
    PrevCH += Footer;
    Preview = window.open(File+"?preview=1&content="+escape(PrevCH),"Preview","width="+(screen.width/2)+",height="+(screen.height/2)+"toolbar=no,location=no,status=no,resizable=yes");
  }

function TitleIze(Str) {
  return "---------- "+Str+" ----------";
}

function FindIndex(Array, Value) {
  for(var i=0; i<Array.length; i++) {
    if (Array[i] == Value) return i;
  }
  return -1;
}
