
// courtesy of Jeremy Keith, _DOM Scripting_
function insertAfter (newElement, targetElement) {
	var parent = targetElement.parentNode;
	if (parent.lastChild == targetElement) {
		parent.appendChild (newElement);
	} else {
		parent.insertBefore(newElement, targetElement.nextSibling);
	}
}

function selectColorTheme(newId, newValue, largeImage)
{
	var stn = document.getElementById('stn');
	var o = document.getElementById('theme'+stn.value);
	o.style.borderWidth='1px';
	o.style.borderColor='black';
	var a = document.getElementById(newId);
	a.style.borderWidth='2px';
	a.style.borderStyle='solid';
	a.style.borderColor='blue';

	document.getElementById('largeImage').src=largeImage;
	stn.value = newValue;
}

var selectedFont = null;

function selectFont( font, fontName ) {
   if ( fontName != 'Helvetica' && fontName != 'Arial'
        && fontName != 'Courier' && fontName != 'Times'
        && fontName != 'Verdana' )
   {
      if ( ! confirm('You have selected a non-standard font that may not be supported by all machines or browsers.\n\nWhen your selected font is not available, your site will be displayed in Verdana.\n\nDo you still want to use this font?') ) {
        return;
      }        
   }


   if (selectedFont != null) {
      selectedFont.className='font-menu'; 
   }
   font.className='font-menu-selected';
   selectedFont = font;
   
   document.getElementById('fontName').value = fontName;
   
   try {
    frames.previewPane.changeElementFont( fontName );
   } catch ( error ) {
    var ppSrc = document.getElementById('previewPane').src;    
    document.getElementById('previewPane').src = ppSrc;        
   }
}

// colors stuff

var editIds = new Array('bg', 'fg');
var editColor = new Array(2);
var editColorField = new Array(2);
var editColorId = new Array(2);

function updateColor( colorCode, cpId ) {
   if ( editColor[cpId] != null ) {
      editColor[cpId].getElementsByTagName('div')[0].style.backgroundColor = colorCode;
      editColorField[cpId].value = colorCode;
      
      if ( cpId == 0 ) {
        try {
          frames.previewPane.changeElementBackgroundColor( editColorId[cpId], colorCode );
        } catch ( error ) {
          var ppSrc = document.getElementById('previewPane').src;    
          document.getElementById('previewPane').src = ppSrc;        
        }

      } else {
        try {
          frames.previewPane.changeElementFontColor( editColorId[cpId], colorCode );
        } catch ( error ) {
          var ppSrc = document.getElementById('previewPane').src;    
          document.getElementById('previewPane').src = ppSrc;        
        }
        
      }
   }      
}

function overColor( colorElement, cpId ) {
   if ( editColor[cpId] != colorElement ) {
      colorElement.style.border = '1px solid yellow';
   }
}

function outColor( colorElement, cpId ) {
   if ( editColor[cpId] != colorElement ) {
      colorElement.style.border = '1px solid white';
   }
}

function clickColor( colorElement, colorId, cpId ) {
   if ( editColor[cpId] != colorElement ) {
      if ( editColor[cpId] != null ) {
         editColor[cpId].style.border = '1px solid white';
         editColor[cpId].getElementsByTagName('div')[0].style.border = '1px solid black';
      }
      colorElement.style.border = '1px dotted black';      
      colorElement.getElementsByTagName('div')[0].style.border = '1px solid white';
      
      editColor[cpId] = colorElement; 
      editColorId[cpId] = colorId;
      editColorField[cpId] = document.getElementById( editIds[cpId] + 'color-field-' + colorId );           
           
      frames[editIds[cpId] + 'colorPickerFrame'].setCol( editColorField[cpId].value );
      frames[editIds[cpId] + 'colorPickerFrame'].setCallback( function( colorCode ) { updateColor( colorCode, cpId ); } );
   }
}

function popupPicker( cpId ) {
   showMenu(editIds[cpId] + 'color-picker-table', editIds[cpId] + 'color-picker-arrow', 'bottom-right' );
   
   frames[editIds[cpId] + 'colorPickerFrame'].setCol( editColorField[cpId].value );
   var updateFunction = function( colorCode ) { updateColor( colorCode, cpId ); };
   frames[editIds[cpId] + 'colorPickerFrame'].setCallback( updateFunction );
   
}

// * preview pane sizer *

function sizePreviewPane() {
   if ( isIE() ) {
      var w = Math.min( Math.max( parseInt(window.screen.availWidth) - 434, 590 ), 810 );
      var h = Math.min( Math.max( parseInt(window.screen.availHeight) - 428, 340 ), 600 );
   
      document.getElementById('previewPane').style.width = w;
      document.getElementById('previewPane').style.height = h;
   }
}

// * reset *

function resetFontsColors() {
   frames['previewPane'].location.reload();
   
   // refresh color boxes
   var tds = document.getElementById('bgcolors-row').getElementsByTagName("TD");
   var i;
   for ( i = 0; i < tds.length; i++ ) {
      var div1 = tds[i].getElementsByTagName("DIV")[0];
      var div2 = div1.getElementsByTagName("DIV")[0];      
      var divId = div1.id;
      var origId = divId.substring( divId.indexOf('(') + 1, divId.indexOf(')') );
      
      var newValue = document.getElementById( 'orig-bgcolor-field-' + origId ).value;
      document.getElementById( 'bgcolor-field-' + origId ).value = newValue;
      div2.style.backgroundColor = '#' + newValue;      
   }
   editColorId[0] = editColorField[0].value;
   frames['bgcolorPickerFrame'].setCol( editColorField[0].value );
      
   tds = document.getElementById('fgcolors-row').getElementsByTagName("TD");
   for ( i = 0; i < tds.length; i++ ) {
      var div1 = tds[i].getElementsByTagName("DIV")[0];
      var div2 = div1.getElementsByTagName("DIV")[0];      
      var divId = div1.id;
      var origId = divId.substring( divId.indexOf('(') + 1, divId.indexOf(')') );
          
      var newValue = document.getElementById( 'orig-fgcolor-field-' + origId ).value;
      document.getElementById( 'fgcolor-field-' + origId ).value = newValue;
      div2.style.backgroundColor = '#' + newValue;   
   }   
   editColorId[1] = editColorField[1].value;
   frames['fgcolorPickerFrame'].setCol( editColorField[1].value );
   
   // reset the font selection
   document.theform.fontName.value = document.theform.origFontName.value;
   document.theform.fontSize.value = document.theform.origFontSize.value;
   
   if ( selectedFont != null ) {
      selectedFont.className = 'font-menu';  
   }
   selectedFont = document.getElementById( 'font-name-' + document.theform.fontName.value );
   selectedFont.className = 'font-menu-selected';
}


// * sub-document modification functions

function changeElementFont( font ) { 
   var element = null;

   if ( arguments.length >= 2 ) {
     element = arguments[1];
   } else {
     element = document;
   }
   
   try {
    if ( element.getAttribute("noFAC") ) {
     return;
    }
   } catch (error) { }     
   
   try {
      element.style.fontFamily = font;
   } catch (error) {
   }
   
   var i;   
   for ( i = 0; i < element.childNodes.length; i++ ) {   
      changeElementFont( font, element.childNodes[i] );
   }
}

function changeElementFontSize( diff ) {
   var element = null;

   if ( arguments.length >= 2 ) {
     element = arguments[1];
   } else {
     element = document;
   }

   try {
    if ( element.getAttribute("noFAC") ) {
     return;
    }
   } catch (error) { }   

   var i;
   for ( i = 0; i < element.childNodes.length; i++ ) {
      changeElementFontSize( diff, element.childNodes[i] );
   }
   
   var inline = 0;
   try {
      inline = element.getAttribute( "hasFontSize" );
   } catch (error) { }
   
   if (!inline) {   
     try {
       var curSize = null;
       if ( isIE() ) {
          curSize = element.currentStyle.fontSize;
       } else {
          curSize = getComputedStyle(element, null).fontSize;
       }

       if ( curSize != null ) {
          var iSize = parseInt( curSize );
          if ( curSize.match('pt') ) {
             iSize *= 4;
             iSize /= 3;
          }
          element.style.fontSize = iSize + diff + "px";
       }
     } catch (error) {
     }
   }
}

function changeElementBackgroundColor( colorId, color ) {
   var element = null;

   if ( arguments.length >= 3 ) {
     element = arguments[2];
   } else {
     element = document;
   }  

   try {
      if ( element.getAttribute( "bgcolorId" ) == colorId ) {
         element.style.backgroundColor = color;
      }
   } catch (error) {
   }

   var i;
   for ( i = 0; i < element.childNodes.length; i++ ) {
      changeElementBackgroundColor( colorId, color, element.childNodes[i] );
   }
}


function changeElementFontColor( colorId, color ) {
   var element = null;

   if ( arguments.length >= 3 ) {
     element = arguments[2];
   } else {
     element = document;
   }
   
   try {
      if ( element.getAttribute( "colorId" ) == colorId ) {
         element.style.color = color;
         
         element.onmouseout = function (evt) { element.style.color = color; };
         
         if ( element.onmouseover == null && (element.getAttribute("hcolorId") != null) ) {
            element.onmouseover = function (evt) { element.style.color = "#" + element.getAttribute("hcolorId"); };
         }
      }  
   } catch (error) {
   }
   
   try {      
      if ( element.getAttribute( "hcolorId" ) == colorId ) {
         var curColor = null;
         var curColorId = null;
         
         if ( isIE() ) {
            curColor = element.currentStyle.color;
         
         } else {
            try {
               curColor = frames['previewPane'].getComputedStyle(element, null).color;
            } catch ( error ) { }
         }
         
         element.onmouseover = function (evt) { element.style.color = color; };
         element.onmouseout = function (evt) { element.style.color = curColor; };      
      }
      
   } catch (error) {
   }


   var i;
   for ( i = 0; i < element.childNodes.length; i++ ) {
      changeElementFontColor( colorId, color, element.childNodes[i] );
   }
}


function updateFontsAndColors() {
   try {
      changeElementFont( parent.document.getElementById('fontName').value );
      changeElementFontSize( parseInt( parent.document.getElementById('fontSize').value ) - 
                             parseInt( parent.document.getElementById('origFontSize').value ) );
                             
      var tds = parent.document.getElementById('bgcolors-row').getElementsByTagName("TD");
      var i;
      for ( i = 0; i < tds.length; i++ ) {
        var div1 = tds[i].getElementsByTagName("DIV")[0];
        var div2 = div1.getElementsByTagName("DIV")[0];      
        var divId = div1.id;
        var origId = divId.substring( divId.indexOf('(') + 1, divId.indexOf(')') );

        var newValue = parent.document.getElementById( 'bgcolor-field-' + origId ).value;
        
        changeElementBackgroundColor(origId,newValue);
      }

      tds = parent.document.getElementById('fgcolors-row').getElementsByTagName("TD");
      for ( i = 0; i < tds.length; i++ ) {
        var div1 = tds[i].getElementsByTagName("DIV")[0];
        var div2 = div1.getElementsByTagName("DIV")[0];      
        var divId = div1.id;
        var origId = divId.substring( divId.indexOf('(') + 1, divId.indexOf(')') );

        var newValue = parent.document.getElementById( 'fgcolor-field-' + origId ).value;        
        
        changeElementFontColor(origId,newValue);
      }                                
                             
                                   
   } catch (error) {
   }
}

var current_edit_row = null;
var current_edit_row_id = null;
var is_editing = false;

function editCssToken(name, token, id)
{
	document.getElementById('errorSection').innerHTML='';

	//var properties = document.getElementById('properties_' + id).value.split('|');
	
	// http://json.org - JavaScript Object notation
	var property_json = document.getElementById('properties_json_' + id).value;
	if (window.console) console.log (property_json);
	var propertiesObj = eval ( "({" + property_json + "})" );
	
	document.getElementById('token').value=token;
  	document.getElementById('es_title').innerHTML = 'Edit Setting for ' + name;
  	document.getElementById('es_description').innerHTML = propertiesObj.description;
	var se = document.getElementById('sample');
	// Font color
	if (window.console) console.log('color: ' + propertiesObj.color);
	if (propertiesObj.color=='')
	{
		disableColorField('color');
		se.style.color='#000000';
	}
	else
	{
		enableColorField('color');
		se.style.color='#'+propertiesObj.color;
	}
	document.getElementById('color').value = propertiesObj.color;
	
	// Background color
	if (window.console) console.log('bgColor: ' + propertiesObj.bgColor);
	if (propertiesObj.bgColor == '')
	{
		disableColorField('bgColor');
		se.style.backgroundColor='#FFFFFF';
	} 
	else
	{
		enableColorField('bgColor');
    if (propertiesObj.bgColor=='transparent')
      se.style.backgroundColor='transparent';
    else
      se.style.backgroundColor='#'+propertiesObj.bgColor;
	}
	document.getElementById('bgColor').value = propertiesObj.bgColor;
	// Border color
	if (window.console) console.log('borderColor: ' + propertiesObj.borderColor);
	if (propertiesObj.borderColor == '')
	{
		disableColorField('borderColor');
		se.style.border='';
	} 
	else
	{
		enableColorField('borderColor');
		if (propertiesObj.borderColor=='transparent')
			se.style.border='1px solid transparent';
		else
			se.style.border='1px solid #'+propertiesObj.borderColor;		
	}
	document.getElementById('borderColor').value = propertiesObj.borderColor;
	// Font
	if (window.console) console.log('font: ' + propertiesObj.font);
	if (propertiesObj.font == '')
	{
		disableCCFSelectField('font');
		se.style.fontFamily='';
	}
	else
	{
		enableCCFFontStyle('font','Arial / sans-serif');
		se.style.fontFamily=propertiesObj.font;
	}
	selectOption('font', propertiesObj.font);
	// Font size
	if (window.console) console.log('size: ' + propertiesObj.size);
	if (propertiesObj.size == '')
	{
		disableCCFFontSize('size');
		se.style.fontSize='';
	}
	else
	{
		enableCCFFontSize('size', '10');
		se.style.fontSize=propertiesObj.size;
	}
	var setSize = propertiesObj.size!='' ? propertiesObj.size.match(/([\d]+)([\w]*)/)[1] : '';
	document.getElementById('size').value=setSize;
	//selectOption('size', propertiesObj.size);
	
	// Font style
	if(propertiesObj.bold=='' && propertiesObj.italic=='' && propertiesObj.underline=='')
	{
		document.getElementById('fs').style.color='#FFFFFF';
		se.style.fontWeight='';
		se.style.fontStyle='';
		se.style.textDecoration='';
	}
	else
	{
		document.getElementById('fs').style.color='#000000';
	}
	
	// Bold
	if (propertiesObj.bold=='')
	{
		disableCCFFontStyle('fs_bold');
		se.style.fontWeight='';
	}
	else if (propertiesObj.bold=='bold')
	{
		selectCCFFontStyle('fs_bold', 'bold');
		se.style.fontWeight='bold';
	}
	else
	{
		deselectCCFFontStyle('fs_bold', 'normal');
		se.style.fontWeight='';
	}
	// Italic
	if (propertiesObj.italic=='')
	{
		disableCCFFontStyle('fs_italic');
		se.style.fontStyle='';
	}
	else if (propertiesObj.italic=='italic')
	{
		selectCCFFontStyle('fs_italic', 'italic');
		se.style.fontStyle='italic';
	}
	else
	{
		deselectCCFFontStyle('fs_italic', 'normal');
		se.style.fontStyle='';
	}
	// Underline
	if (propertiesObj.underline=='')
	{
		disableCCFFontStyle('fs_underline');
		se.style.textDecoration='';
	}
	else if (propertiesObj.underline=='underline')
	{
		selectCCFFontStyle('fs_underline', 'underline');
		se.style.textDecoration='underline';
	}
	else
	{
		deselectCCFFontStyle('fs_underline', 'none');
		se.style.textDecoration='';
	}
}

function setupCssEdit (name, token, id) { // row id
	var es = document.getElementById('es');
	var f = document.getElementById('saveCCF');
	
	var clickedRow = document.getElementById('row_id_'+id);
	
	if (id == current_edit_row_id && is_editing) { // clicked the same link
			// simply stop editing
			hideElementWithId(current_edit_row.id);
			endCssEdit (id);
			is_editing = false;
	// user clicked another link to edit a different token
	} else if ((id == current_edit_row_id && !is_editing) || 
	  		   (id != current_edit_row_id && current_edit_row != null)) {
		if (current_edit_row_id != null) {
			var expander = document.getElementById('expander_'+current_edit_row_id);
			document.getElementById('expander_'+current_edit_row_id).src='/images/expander_closed.gif';
		}
		current_edit_row_id = id;
		insertAfter (current_edit_row, clickedRow);
		current_edit_row.style.display=""; // should be 'table-row' but IE (yeah, you knew it) hates it.
		current_edit_row.style.visibility="visible";
		editCssToken(name, token, id);
		document.getElementById('expander_'+id).src='/images/expander_open.gif';
		is_editing = true;
	} else {
		// create a row/cell to hold the editor
		var newRow = document.createElement('tr');
		//newRow.style.display='none';
		newRow.id = 'editor_row_id_'+id;
		
		var newCell = document.createElement('td');
		newCell.appendChild(f);
		var cs = document.createAttribute('colspan');
		cs.nodeValue = "2";
		newCell.setAttributeNode(cs);
		newRow.appendChild(newCell);
		
		// save it
		current_edit_row = newRow;
		
		//now show them
		f.style.display="block";
		f.style.visibility="visible";
		es.style.display='block';
		es.style.visibility='visible';
		insertAfter (newRow, clickedRow);
		current_edit_row_id = id;
		editCssToken(name, token, id);
		document.getElementById('expander_'+id).src='/images/expander_open.gif';
		is_editing = true;
	}
}

function endCssEdit (row_id) { // row id
	if (window.console) console.log(row_id);
	row_id = row_id.split('_').pop();
	document.getElementById('expander_'+row_id).src='/images/expander_closed.gif';
}

function disableColorField(name)
{
	document.getElementById(name + '_label').style.color='#C0C0C0';
	document.getElementById(name).style.backgroundColor='#C0C0C0';
	document.getElementById(name).disabled=true;
	document.getElementById(name + '_img').style.visibility='hidden';	
}

function enableColorField(name)
{
	document.getElementById(name + '_label').style.color='#000000';
	document.getElementById(name).style.backgroundColor='#FFFFFF';
	document.getElementById(name).disabled=false;
	document.getElementById(name + '_img').style.visibility='visible';
}

function disableCCFSelectField(name)
{
	document.getElementById(name + '_label').style.color='#C0C0C0';
	document.getElementById(name).style.backgroundColor='#C0C0C0';
	document.getElementById(name).options[0].text='';
	document.getElementById(name).options[0].selected=true;
	document.getElementById(name).disabled=true;
}

function disableCCFFontStyle(name)
{
	var fsb = document.getElementById(name);
	document.getElementById(name + '_value').disabled=true;
	fsb.style.display='none';
	fsb.style.visibility='hidden';
}

function enableCCFFontStyle(name, firstOption)
{
	document.getElementById(name + '_label').style.color='#000000';
	document.getElementById(name).style.backgroundColor='#FFFFFF';
	document.getElementById(name).options[0].text=firstOption;
	document.getElementById(name).disabled=false;
}

function enableCCFFontSize(name, value)
{
	document.getElementById(name + '_label').style.color='#000000';
	document.getElementById(name).style.backgroundColor='#FFFFFF';
	document.getElementById(name).value=value;
	document.getElementById(name).disabled=false;
}
function disableCCFFontSize(name)
{
	document.getElementById(name + '_label').style.color='#C0C0C0';
	document.getElementById(name).style.backgroundColor='#C0C0C0';
	document.getElementById(name).value='';
	document.getElementById(name).disabled=true;
}

function selectOption(id, value)
{
	for(j=0; j<document.getElementById(id).options.length; j++)
	{
		var option = document.getElementById(id).options[j];
		if(option.value == value)
			option.selected=true;
	}
}

function selectCCFFontStyle(name, value)
{
	var fsb = document.getElementById(name);
	document.getElementById(name + '_value').disabled=false;
	document.getElementById(name + '_value').value=value;
	fsb.style.display='';
	fsb.style.visibility='visible';
	fsb.style.backgroundColor='#F2F2F2';
	fsb.style.border='1px solid #000066';
	fsb.style.padding='0px';
}

function deselectCCFFontStyle(name, value)
{
	var fsb = document.getElementById(name);
	document.getElementById(name + '_value').disabled=false;
	document.getElementById(name + '_value').value=value;
	fsb.style.display='';
	fsb.style.visibility='visible';
	fsb.style.backgroundColor='';
	fsb.style.border='';
	fsb.style.padding='1px';
}

function validateCCFColorCode(code)
{
  var pattern=new RegExp("^[0-9a-fA-F]{6}$");
  return (pattern.test(code) || code == "transparent")
}

// user click on the save button in the custom colors and fonts page
function saveCssProperty()
{
	var form = document.forms['saveCCF'];
  	var fullURL = 'persistCustomFontsAndColors.hg?' + getFormValue(form, 'property.');
  	xmlLoader(fullURL, saveCssPropertyHandler);
}

// ajax call handler for persisting the property item
function saveCssPropertyHandler(xmlHttp)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);
  // Check to see if there is any validation error
  var error = xmlDoc.getElementsByTagName("validationError");
  if(error.length > 0 )
  {
    // there is an error
	document.getElementById('errorSection').innerHTML=xmlElementToString(error[0].firstChild);
    // Reset the height of the 'ccf-edit-section' div so it will display correctly in FF
    document.getElementById('ccf-edit-section').style.height="";
  }
	else
	{
		document.getElementById('errorSection').innerHTML='';
	  	var propertyId = xmlDoc.getElementsByTagName("propertyId")[0].firstChild.data;
	  	var sample = xmlDoc.getElementsByTagName("propertyStyle")[0].firstChild;
	  	var properties_json = xmlDoc.getElementsByTagName("properties-json")[0].firstChild;
	  	var setting = xmlDoc.getElementsByTagName("setting")[0].firstChild;
	  	document.getElementById('sample_' + propertyId).innerHTML=xmlElementToString(sample);
		document.getElementById('properties_json_' + propertyId).value=xmlElementToString(properties_json);
		document.getElementById('setting_' + propertyId).innerHTML=xmlElementToString(setting);
		hideElementWithId(current_edit_row.id);
	}
}

// user click on the one of the Font Style button
function clickFontStyle(ele)
{
	if(ele.style.borderColor=='')
	{
		ele.style.backgroundColor='#C0C0C0';
		ele.style.border='1px solid #000066';
		ele.style.padding='0px';
		return true;
	}
	else
	{
		ele.style.backgroundColor='#C0C0C0';
		ele.style.border='';
		ele.style.padding='1px';
		return false;
	}
}function preloadImages() 
{ 
  if(document.images)
  { 
    if(!document.preloadedImages) 
    {
      document.preloadedImages=new Array();
    }
    
    var j = document.preloadedImages.length;
    var args = preloadImages.arguments; 
    for (var i = 0; i < args.length; i++)
    {
      document.preloadedImages[j] = new Image(); 
      document.preloadedImages[j].src = args[i];
      j++;
    }
  }
}

function resizeImage(_this, size)
{
	if(size == 'small' && _this.offsetWidth > 60)
	{
		_this.style.width = '60px';
	}
	if(size == 'large' && _this.offsetWidth > 175)
	{
		_this.style.width = '175px';
	}
	if(size == 'zoom' && _this.offsetWidth > 400)
	{
		_this.style.width = '400px';
	}
	if(size == 'enlarge' && _this.offsetWidth > 420)
	{
		_this.style.width = '420px';
	}
}


function findElement(elementId, curDocument)
{
  if(!curDocument)
  {
    curDocument = document;
  }
  var element;
  //try and get the element by id first
  if(curDocument.getElementById)
  {
    element = curDocument.getElementById(elementId);
  }
  
  //if no element was found with the specified id
  //try and find it by name
  if(!element)
  {
    element = curDocument[elementId];
    //check all elements on page
    if(!element && curDocument.all) 
    {
      element = curDocument.all[elementId]; 
    }
    
    //check the all of the form elements
    if(!element)
    {
      for(var i = 0; i < curDocument.forms.length; i++) 
      {
        element = curDocument.forms[i][elementId];
        if(element)
        {
          break;
        }
      }
    }
    
    //check all of the layers
    if(!element && curDocument.layers)
    {
      for(var i = 0; i < curDocument.layers.length; i++) 
      {
        element = findElement(elementId, curDocument.layers[i].document);
        if(element)
        {
          break;
        }
      }
    }
  }
  return element;
}

function swapImageRestore() 
{ 
  var i;
  var x;
  var a=document.MM_sr; 
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
  {
    x.src=x.oSrc;
  }
}

function swapImage() { //v3.0
  var i,j=0,x,a=swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=findElement(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


/**
 * Function to hide an element.
 */
function hideElement(element)
{
  element.style.display  = "none";
  element.style.visibility = "hidden";
}

/**
 * Function to hide an element.
 */
function hideElementsWithIds()
{
  var elementsToHide = hideElementsWithIds.arguments;
  if(elementsToHide && elementsToHide.length)
  {
    for(var i = 0; i < elementsToHide.length; i++)
    {
      hideElementWithId(elementsToHide[i]);
    }
  }
}

function showElementsWithIds()
{
  var elementsToShow = showElementsWithIds.arguments;
  if(elementsToShow && elementsToShow.length)
  {
    for(var i = 0; i < elementsToShow.length; i++)
    {
      showElementWithId(elementsToShow[i]);
    }
  }
}

/**
 * Function to display an element.
 */
function showElement(element)
{
  if(element)
  {
  	var displayType = (element.tagName=="TD"||element.tagName=="TR") ? "" : "block";
    element.style.display  = displayType;
    element.style.visibility = "visible";
  }
}

/**
 * Function to test if an element is currently painted on the screen.
 */
function isShown(elementId)
{
  var element = document.getElementById(elementId);
  if(element)
  {
    return !(element.style.display == 'hidden' || element.style.display == 'none');
  }
  return false;
}

function isElementShown(element)
{
  if(element)
  {
    return !(element.style.display == 'hidden' || element.style.display == 'none');
  }
  return false;
}

/**
 * Function to hide or show an element based on 
 * it's current display style.
 * Hides the element if the display style is block or empty.
 * Shows the element otherwise.
 * @param elementToToggle the element to show or hide.
 */
function toggleElement(elementToToggle)
{
  if(elementToToggle.style.display == 'hidden' || elementToToggle.style.display == 'none')
  {
    showElement(elementToToggle);
  }
  else
  {
    hideElement(elementToToggle);
  }
}

function showElementWithId(elementId)
{
  var element = document.getElementById(elementId);
  if(element)
  {
    showElement(element);
  }
}

function showIFrameAtRelativePosition(eventObj, elementId, url, offsetX, offsetY)
{
	var iframe = document.getElementById(elementId + '-frame');	
	if (iframe.src.indexOf(url) == -1)
	{
		// This url have not been loaded yet. load it now.
		iframe.src = url;
	}
	showElementWithIdAtRelativePosition(eventObj, elementId + '-table', offsetX, offsetY);
}

function showElementWithIdAtRelativePosition(eventObj, elementId, offsetX, offsetY)
{
	if (!offsetX) { offsetX = 0; }
    if (!offsetY) { offsetY = 0; }
    
	var eventX = 25;
	var eventY;
	if (Utils.ge('contentDiv') != null)
      eventY = Utils.ge('contentDiv').scrollTop;
	else if (Utils.ge('contentDiv_jsp') != null)
      eventY = Utils.ge('contentDiv_jsp').scrollTop;
	  
//    var eventY = Utils.ge('contentDiv').scrollTop;
	// KH: Made change to work with new embedded scroll layout.
	//var eventX = eventObj.clientX;
    //var eventY = eventObj.clientY;
    showElementWithIdAtPosition(elementId, eventX + offsetX, eventY + offsetY);
}

function showElementWithIdAtPosition(elementId, offsetX, offsetY)
{
    var elementObj = document.getElementById(elementId);
    if(elementObj)
    {
          
      elementObj.style.display = 'block';
      elementObj.style.visibility='visible';
      elementObj.style.position='absolute';
      elementObj.style.top = (offsetY + document.body.scrollTop) + 'px';
      elementObj.style.left = (offsetX + document.body.scrollLeft) + 'px';
    }    
}

function hideElementWithId(elementId)
{
  var element = document.getElementById(elementId);
  if(element)
  {
    hideElement(element);
  }
}

function toggleElementWithId(elementId)
{
  var element = document.getElementById(elementId);
  if(element)
  {
    toggleElement(element);
  }  
}

function toggleVisibilityByCheckbox(sourceElement, visibleWhenChecked, toggleDisplay, affectedElements)
{
  var element = document.getElementById(sourceElement);
  // Show the targeted element if either one of the follow are true:
  // 1) The source element is checked and visibleWhenChecked is true
  // 2) The source element is unchecked and visibleWhenChecked is false
  if ((element.checked && visibleWhenChecked) || 
      (!element.checked && !visibleWhenChecked))
  {
    for(i=0; i<affectedElements.length; i++)
    {
      var elementToToggle = document.getElementById(affectedElements[i]); 
      if (elementToToggle.style.visibility == 'hidden' || elementToToggle.style.display == 'none')
      {
        elementToToggle.style.visibility = "visible";        
        if (toggleDisplay)
          elementToToggle.style.display  = "block";        
      }
    }
  }
  else
  {
    // Hide the targeted element if either one of the follow are true:
    // 1) The source element is unchecked and visibleWhenChecked is true
    // 2) The source element is checked and visibleWhenChecked is false
    for(i=0; i<affectedElements.length; i++)
    {
      var elementToToggle = document.getElementById(affectedElements[i]); 
      if (elementToToggle.style.visibility != 'hidden' && elementToToggle.style.display != 'none')
      {
        elementToToggle.style.visibility = "hidden";
        if (toggleDisplay)
          elementToToggle.style.display  = "none";
      }
    }
  }
}

function toggleEnableByCheckbox(sourceElement, enableWhenChecked, affectedElements)
{
  var element = document.getElementById(sourceElement);
  if ((element.checked && enableWhenChecked) || (!element.checked && !enableWhenChecked))
  {
    // Enable the affected elements
    for(i=0; i<affectedElements.length; i++)
    {
      var affectedElement = document.getElementById(affectedElements[i]);
      affectedElement.disabled = false;
    } 
  }
  else
  {
    // Disable the affected elements
    for(i=0; i<affectedElements.length; i++)
    {
      var affectedElement = document.getElementById(affectedElements[i]);
      affectedElement.disabled = true;
    } 
  }
}

// functions for determining user agent
function isIE()
{
  return isAgent('IE');
}

function isGecko()
{
  return isAgent('Gecko');
}


function isOpera()
{
  return isAgent('Opera');
}

/**
 * function to check if a browser is of a specified type
 * and of at least the version specified.
 * @param appName the name of the browser type to check for.
 *        valid types are 'IE', 'Gecko', 'Opera'.
 * @returns true if this browser is of a the specified type and
 *          and has a version greater than or equal to version.
 */
function isAgent(appName)
{
  return isAgentAndVersion(appName, 0);
}

/**
 * function to check if a browser is of a specified type
 * and of at least the version specified.
 * @param appName the name of the browser type to check for.
 *        valid types are 'IE', 'Gecko', 'Opera'.
 * @param version the version number to check if this browser
 *        is greater than.
 * @returns true if this browser is of a the specified type and
 *          and has a version greater than or equal to version.
 */
function isAgentAndVersion(appName, version)
{
  var isAgent = false;
  var userAgent = navigator.userAgent;
  if(appName == 'IE')
  {
    if(userAgent.indexOf('MSIE') > 0)
    {
      var versionRegExp = new RegExp("MSIE ((\\d+\\.?){1,2})");
      var result = versionRegExp.exec(userAgent);
      if(result.length > 0)
      {
        if(result[1] >= version)
        {
          isAgent = true;
        }
      }
    }
  }
  if(appName == 'Gecko')
  {
    if(userAgent.indexOf('MSIE') < 0)
    {
      var versionRegExp = new RegExp("Mozilla/((\\d+\\.?){1,2})");
      var result = versionRegExp.exec(userAgent);
      if(result.length > 0)
      {
        if(version <= result[1])
        {
          isAgent = true;
        }
      }
    }
  }
  if(appName == 'Opera')
  {
    if(userAgent.indexOf('Opera') > 0)
    {
      var versionRegExp = new RegExp("Opera(/|\\s)((\\d+\\.?){1,2})");
      var result = versionRegExp.exec(userAgent);
      if(result.length > 0)
      {
        if(version <= result[2])
        {
          isAgent = true;
        }
      }
    }
  }
  return isAgent;
}

function scaleImage(imageId, imageMaxWidth, imageMaxHeight, fillToSize)
{
  var imageElement = document.getElementById(imageId);
  imageElement.style.width = "auto";
  imageElement.style.height = "auto";
  if((fillToSize || fillToSize != false) || 
    imageElement.width > imageMaxWidth || 
    imageElement.height > imageMaxHeight)
  {
    var scaledRatio = imageMaxWidth / imageMaxHeight;
    var imageRatio = imageElement.width / imageElement.height;
    var scaledWidth = Math.floor((scaledRatio < imageRatio) ? 
      imageMaxWidth : imageMaxHeight * imageRatio);
    var scaledHeight = Math.floor((scaledRatio < imageRatio) ? 
      imageMaxWidth / imageRatio : imageMaxHeight);
    imageElement.style.width = scaledWidth;
    imageElement.style.height = scaledHeight;
  }
  else
  {
    imageElement.style.width = imageElement.width;
    imageElement.style.height = imageElement.height;
  }
}


function rollDown(elementId, totalTime, callbackFunction, dy, maxHeight, iteration, interval)
{
  var animateElement = document.getElementById(elementId);
  if(!dy)
  {
    showElement(animateElement);
    animateElement.style.visibility = 'hidden'
    animateElement.style.height="";
    maxHeight = animateElement.offsetHeight;
    animateElement.style.overflow = 'hidden';
    animateElement.style.height = 1;
    animateElement.style.visibility = '';
  
    if(totalTime/4 > maxHeight)
    {
      //more than 1 ms per pixel
      interval = (totalTime/4) / maxHeight;
      dy = 4;
    }
    else
    {
      dy = maxHeight / (totalTime / 4);
      interval = (totalTime / 4)/ maxHeight;
    }

    iteration = 1;
  }
  if(iteration > maxHeight)
  {
    if(!isShown(elementId))
    {
      showElement(animateElement);  
    }
    animateElement.style.height="";
    animateElement.style.overflow = '';
    if(callbackFunction)
    {
      callbackFunction(elementId);
    }
    return;
  }
  
  if(dy*iteration < maxHeight+dy)
  {
    animateElement.style.height = dy*iteration > maxHeight ? maxHeight : dy*iteration < 1 ? 1 : dy*iteration;
    setTimeout('rollDown("'+elementId+'", '+totalTime+','+callbackFunction+','+dy+','+maxHeight+','+(iteration+1)+','+interval+')', interval);
  }
  else
  {
    animateElement.style.overflow = '';
    if(callbackFunction)
    {
      callbackFunction(elementId);
    }
  }
}

function rollUp(elementId, totalTime, callbackFunction, dy, maxHeight, iteration, interval)
{
  var animateElement = document.getElementById(elementId);
  if(!dy)
  {
    animateElement.style.height="";
    maxHeight = animateElement.offsetHeight;
    animateElement.style.overflow = 'hidden';

    if(totalTime/4 > maxHeight)
    {
      //less than 1 ms per pixel
      interval = (totalTime/4) / maxHeight;
      dy = 4;
    }
    else
    {
      dy = maxHeight / (totalTime / 4);
      interval = (totalTime / 4)/ maxHeight;
    }
    iteration = 1;
  }
  if(iteration > maxHeight)
  {
    if(!isShown(elementId))
    {
      hideElement(animateElement); 
    }
    if(callbackFunction)
    {
      callbackFunction(elementId);
    }
    return;
  }

  if(dy*iteration < maxHeight)
  {
    animateElement.style.height = maxHeight - dy*iteration < 1 ? 1 : maxHeight - dy*iteration;
    setTimeout('rollUp("'+elementId+'",'+totalTime+','+callbackFunction+','+dy+','+maxHeight+','+(iteration+1)+','+interval+')', interval);
  }
  else
  {
    animateElement.style.overflow = '';
    hideElement(animateElement);
    if(callbackFunction)
    {
      callbackFunction(elementId);
    }
  }
}

function getElementLeft(element)
{
  if (!element && this)
  {
    element = this;
  }

  var leftPosition = element.offsetLeft;
  var parentElement = element.offsetParent;

  while (parentElement != null)
  {

    if(isIE())
    {
      if( (parentElement.tagName != "TABLE") && (parentElement.tagName != "BODY") )
      {
        leftPosition += parentElement.clientLeft;
      }
    }
    else
    {
      if(parentElement.tagName == "TABLE")
      {
        var parentBorder = parseInt(parentElement.border);
        if(isNaN(parentBorder))
        {
          var parentFrame = parentElement.getAttribute('frame');
          if(parentFrame != null)
          {
            leftPosition += 1;
          }
        }
        else if(parentBorder > 0)
        {
          leftPosition += parentBorder;
        }
      }
    }
    leftPosition += parentElement.offsetLeft;
    parentElement = parentElement.offsetParent;
  }
  return leftPosition;
}

function getElementTop(element)
{
  if (!element && this)
  {
    element = this;
  }

  var topPosition = element.offsetTop;
  var parentElement = element.offsetParent;

  while (parentElement != null)
  {
    if(isIE())
    {
      if( (parentElement.tagName != "TABLE") && (parentElement.tagName != "BODY") )
      {
        topPosition += parentElement.clientTop;
      }
    }
    else
    {
      if(parentElement.tagName == "TABLE")
      {
        var parentBorder = parseInt(parentElement.border);
        if(isNaN(parentBorder))
        {
          var parentFrame = parentElement.getAttribute('frame');
          if(parentFrame != null)
          {
            topPosition += 1;
          }
        }
        else if(parentBorder > 0)
        {
          topPosition += parentBorder;
        }
      }
    }

    topPosition += parentElement.offsetTop;
    parentElement = parentElement.offsetParent;
  }
  return topPosition;
}

function setClassNameOnElement(elementId, className)
{
  var element = document.getElementById(elementId);
  
  if (element)
  {
    element.className = className;
  }
}

function collapseBox(elementId, imageId)
{
  var imageElement = document.getElementById(imageId);
  if (isShown(elementId)) 
  { 
    rollUp(elementId, 20); 
    if (imageElement)
    {
      imageElement.src='images/open_help.gif'; 
    }
  } else {
    rollDown(elementId, 20); 
    if (imageElement)
    {
      imageElement.src='images/close_help.gif'; 
    }
  }
}

function getTimestamp()
{
  return new Date().getTime();
}

function isChild( element, parentElement ) {
   try {
      var c = element;
      while ( c != null ) {   
         if ( parentElement == c )
            return true;
         c = c.parentNode;
      }       
   } catch (error) {
   }
   
   return false;   
}

// STRING FUNCTIONS
function strTrim(s) 
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function strReverse(str) {
   if (!str) return '';
   var revstr='';
   for (i = str.length-1; i>=0; i--)
       revstr+=str.charAt(i)
   return revstr;
}

function englishJoin( items ) {
  if ( items.length == 0 ) {
    return "";
  }
  
  if ( items.length == 1 ) {
    return items[0];
  }
  
  if ( items.length == 2 ) {
    return items[0] + ' and ' + items[1];
  
  }
  
  // length is 3 or more
  var str = "";
  var i;
  
  for ( i = 0; i < items.length - 1; i++ ) {
    str = str + items[i] + ", ";  
  }
  
  str = str + "and " + items[items.length - 1];
  
  return str;
}

function urlEncode(str)
{
    return escape(str);
}

function urlDecode(str)
{
    return unescape(str);
}

//  COUNTDOWN CLOCK FUNCTIONS

var clocks = 0;
var enabledClocks = 0;
var clock = new Array();

function leadingZero(num) {
  if ( (num+"").length == 1 ) {
    num = "0" + num;  
  }
  return num;
}

function createEbayCountdown(start, action) {
  if ( start == 0 ) {
     eval(action);
  }

  var cid = clocks++;
  var id = "clock_" + cid;
   
  var str = "";
  start = parseInt(start);
  var days = Math.floor(start/86400);
  start = start % 86400;  
  var hours = Math.floor(start/3600);
  start = start % 3600;
  var mins = Math.floor(start/60);
  var secs = start%60;
  
  str += "<span id=\"" + id + "_days_outer\" ";
  if ( days < 1 ) {
     str += "style=\"visibility: hidden; display: none\" ";
  }
  str += ">";
  str += "<span id=\"" + id + "_days\">" + days + "</span>d </span>";
  str += "<span id=\"" + id + "_hours\">" + leadingZero(hours) + "</span>h ";
  str += "<span id=\"" + id + "_mins\">" + mins + "</span>m ";
  
  str += "<span id=\"" + id + "_secs_outer\"";
  if ( days != 0 ) {
     str += "style=\"visibility: hidden; display: none\" ";
  }
  str += ">";
  str += "<span id=\"" + id + "_secs\">" + leadingZero(secs) + "</span>s</span>";
   
  var countdown = new Object;
  countdown.id = cid;
  countdown.enabled = true;
  countdown.action = action;
  countdown.decrement = 
    function() {      
      secs = parse2Int( document.getElementById('clock_' + this.id + '_secs').innerHTML );
      mins = parse2Int( document.getElementById('clock_' + this.id + '_mins').innerHTML );
      hours = parse2Int( document.getElementById('clock_' + this.id + '_hours').innerHTML );
      try {
        days = parse2Int( document.getElementById('clock_' + this.id + '_days').innerHTML );
      } catch (e) {
        days = 0;
      }

      if ( secs > 0 ) {
        document.getElementById('clock_' + this.id + '_secs').innerHTML = leadingZero( --secs );

        if ( secs == 0 && mins == 0 && hours == 0 && days == 0 ) {
          if ( this.enabled ) {
            this.enabled = false;
            eval(this.action);            
            enabledClocks--;
          }
        }      
      } else {      
        if ( mins > 0 ) {
          document.getElementById('clock_' + this.id + '_secs').innerHTML = 59;
          document.getElementById('clock_' + this.id + '_mins').innerHTML =  --mins;

        } else {       
          if ( hours > 0 ) {
            document.getElementById('clock_' + this.id + '_secs').innerHTML = 59;
            document.getElementById('clock_' + this.id + '_mins').innerHTML = 59;
            document.getElementById('clock_' + this.id + '_hours').innerHTML = leadingZero( --hours );
          } else {
            if ( days > 0 ) {
              document.getElementById('clock_' + this.id + '_secs').innerHTML = 59;
              document.getElementById('clock_' + this.id + '_mins').innerHTML = 59;
              document.getElementById('clock_' + this.id + '_hours').innerHTML = 23;
              document.getElementById('clock_' + this.id + '_days').innerHTML = --days;
              
              if ( days == 0 ) {
                hideElementWithId('clock_' + this.id + '_days_outer');
                showElementWithId('clock_' + this.id + '_secs_outer');              
              }
            }
          }
        }    
      }    
    };  

  document.write(str);
  
  clock[cid] = countdown;
  
  enabledClocks++;
  
  if (enabledClocks == 1) {
    setTimeout("updateCountdowns()", 1000);
  }  
}

function createCountdown(start, action) { 
  if ( start == 0 ) {
     eval(action);
  }
  
  var cid = clocks++;
  var id = "clock_" + cid; 
   
  var str = "";
  start = parseInt(start);
  var hours = Math.floor(start/3600);
  start = start % 3600;
  var mins = Math.floor(start/60);
  var secs = start%60;

  str += "<span id=\"" + id + "_hours\">" + leadingZero(hours) + "</span>:";
  str += "<span id=\"" + id + "_mins\">" + leadingZero(mins) + "</span>:";
  str += "<span id=\"" + id + "_secs\">" + leadingZero(secs) + "</span>";
   
  var countdown = new Object;
  countdown.id = cid;
  countdown.enabled = true;
  countdown.action = action;
  countdown.decrement = 
    function() {
      secs = parse2Int( document.getElementById('clock_' + this.id + '_secs').innerHTML );
      mins = parse2Int( document.getElementById('clock_' + this.id + '_mins').innerHTML );
      hours = parse2Int( document.getElementById('clock_' + this.id + '_hours').innerHTML );

      if ( secs > 0 ) {
        document.getElementById('clock_' + this.id + '_secs').innerHTML = leadingZero( --secs );

        if ( secs == 0 && mins == 0 && hours == 0 ) {
          if ( this.enabled ) {
            this.enabled = false;
            eval(this.action);            
            enabledClocks--;
          }
        }      
      } else {      
        if ( mins > 0 ) {
          document.getElementById('clock_' + this.id + '_secs').innerHTML = 59;
          document.getElementById('clock_' + this.id + '_mins').innerHTML = leadingZero( --mins );

        } else {       
          if ( hours > 0 ) {
            document.getElementById('clock_' + this.id + '_secs').innerHTML = 59;
            document.getElementById('clock_' + this.id + '_mins').innerHTML = 59;
            document.getElementById('clock_' + this.id + '_hours').innerHTML = leadingZero( --hours );
          }
        }    
      }    
    };  

  document.write(str);
  
  clock[cid] = countdown;

  enabledClocks++;
  
  if (enabledClocks == 1) {
    setTimeout("updateCountdowns()", 1000);
  }  
}

function parse2Int( str ) {
   //remove any leading zeros to fix bug were 01 - 07 parse correctly but 08 and 09 parse as 0.
   var trimmedS = str;
   while(trimmedS.indexOf("0") == 0)
   {
     trimmedS = trimmedS.substring(1,trimmedS.length)
   }
   return (trimmedS.length == 0) ? 0 : parseInt( trimmedS );
}

function updateCountdowns() {
  if ( enabledClocks > 0 ) {
    setTimeout("updateCountdowns()", 1000);  
  }

  for ( i = 0; i < clocks; i++ ) {
    if ( clock[i].enabled ) {
      try {
        clock[i].decrement(); 
      } catch (e) {
        alert("Error: " + e.message );
      }
    }
  }     
}

function toggleSection(sectionId)
{
  var sectionElement = document.getElementById(sectionId+"_content");
  if(sectionElement && isShown(sectionId+"_content"))
  {
    hideElementWithId(sectionId+"_content");
    var sectionImage = document.getElementById(sectionId+"_plusMinusImage");
    if(sectionImage)
    {
      sectionImage.src = "images/plus.gif";
    }
  }
  else if(sectionElement)
  {
    showElementWithId(sectionId+"_content")
    var sectionImage = document.getElementById(sectionId+"_plusMinusImage");
    if(sectionImage)
    {
      sectionImage.src = "images/minus.gif";
    }
  }
}

/*
	Quick sort algorithm for HTML tables
	'A' is the array of table rows
	'p' is the lowest bound of the array you want sorted, typically 0
	'r' is the upper bound, typically length-1
	'col' the column to sort on
	'ascend' true or false for ascending or descending order
*/
function quickSort(A, p, r, col, acsend)
{
	if(p < r)
	{
		var q = partition(A, p, r, col, acsend);
		quickSort(A, p, q - 1, col, acsend);
		quickSort(A, q + 1, r, col, acsend);
	}
}

/*
	QuickSort's partitioning sub-algorithm
	Not called directly.
*/

function partition(A, p, r, col, acsend)
{
	var x;
	
	x = getTextValue(A[r].cells[col]);
	
	var i;
	i = p - 1;
	
	var j;
	var curIteration;
	var maxIterations;
	var compare;
	
	for(j = p; j <= r - 1; j++)
	{
		compare = compareValues(getTextValue(A[j].cells[col]), x );
		
		if(acsend)
		{
			compare = -compare;
		}
		
		if( compare == -1 )
		{
			i++;
			//A[i].swapNode(A[j]);
			customSwapNodes(A[i],A[j]);
		}
	}
	
	customSwapNodes(A[r],A[i+1]);
	
	return i + 1;
}

/*
	Exchanges nodes in the DOM.
	IE doesn't allow for prototyping Node so just
	call it's own swapNode function.  Mozilla/Netscape
	requires actual code.
*/
function customSwapNodes(node1, node2)
{
	if(navigator.appName == "Netscape")
	{
	  var nextSibling = node1.nextSibling;
	  var parentNode = node1.parentNode;
	  node1.parentNode.replaceChild(node1, node2);
	  parentNode.insertBefore(node2, nextSibling);
	}
	else
	{
		node1.swapNode(node2);
	}
}

function getTextValue(el)
{
  var i;
  var s;

  // Find and concatenate the values of all text nodes contained within the element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
  {
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
    {
      s += el.childNodes[i].nodeValue;
    }
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
    {
      s += " ";
    }
    else
    {
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);
    }
  }
  return normalizeString(s);
}


// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

function normalizeString(s)
{
  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
  return s;
}


function compareValues(v1, v2)
{
  var f1, f2;

  // If the values are numeric, convert them to floats.

  f1 = parseFloat(v1);
  f2 = parseFloat(v2);
  if (!isNaN(f1) && !isNaN(f2))
  {
    v1 = f1;
    v2 = f2;
  }

  // Compare the two values.
  if (v1 == v2)
  {
    return 0;
  }

  if (v1 > v2)
  {
    return 1
  }

  return -1;
}

function setElementVisibilityById(elementId, visibility)
{
  var element = document.getElementById(elementId);
  setElementVisibility(element, visibility);
}

function setElementVisibility(element, visibility)
{
  if(element)
  {
    element.style.visibility = visibility;
  }
}
function clearSearchForm(searchForm)
{
  var allElements = searchForm.elements;
  for (var index=0; index<searchForm.length; index++)
  {
    var element = allElements[index];
    if (element.type=='select-one')
    {
      element.selectedIndex=0;
    }
    else if (element.type=='text')
    {
      element.value='';
    }
    else if (element.type=='radio')
    {
      if (element.defaultChecked==true)
      {
        element.checked=true;
      }
    }
  }
}

function strikeThroughElementWithId(elementId)
{
  document.getElementById(elementId).style.textDecoration = "line-through";
}

function undecorateElementWithId(elementId)
{
  document.getElementById(elementId).style.textDecoration = "none";
}

/*
  Inserts the specified value at the cursor position in the specified element.
*/
function insertAtCursor(elem, val) 
{
  //IE support
  if (document.selection) 
  {
    elem.focus();
    var sel = document.selection.createRange();
    var tempSelLength = sel.text.length;
    sel.text = val;

    if (val.length == 0) 
    {
      sel.moveStart('character', val.length);
      sel.moveEnd('character', val.length);
    } 
    else 
    {
      sel.moveStart('character', -val.length + tempSelLength);
    }
    //sel.select();
  }
  //MOZILLA/NETSCAPE support
  else if (elem.selectionStart || elem.selectionStart == '0') 
  {
    var startPos = elem.selectionStart;
    var endPos = elem.selectionEnd;
    elem.value = elem.value.substring(0, startPos) + val + elem.value.substring(endPos, elem.value.length);
    elem.selectionStart = startPos + val.length;
    elem.selectionEnd = startPos + val.length;    
  } 
  else 
  {
    elem.value += val;
  }
  elem.focus();
}

// this method build the query string for all the enabled input fields.
// Only fields with the name which started with namePrefix will be included.
function getFormValue(form, namePrefix)
{
  var str = "";
  for(var i = 0;i < form.elements.length;i++)
  {
		if(!form.elements[i].disabled && form.elements[i].name.indexOf(namePrefix)==0)
		{
			str += form.elements[i].name +
             "=" + escape(form.elements[i].value) + "&";
		}
  }
  str = str.substr(0,(str.length - 1));
  return str;
}

// Replaces any occurances of the <, >, &, and " chars in str with their html escape variants.
function htmlEscape(str)
{
  var re_a = new RegExp ('&', 'gi');
  var re_lt = new RegExp ('<', 'gi');
  var re_gt = new RegExp ('>', 'gi');
  var re_q = new RegExp( '"', 'gi');
  
  return str.replace(re_a, '&amp;').replace(re_q, '&quot;').replace(re_lt, '&lt;').replace(re_gt, '&gt;');
}

// progParDivId - the id of an element under which the "Loading..." div will be created.
// updateElemId - the element whose innerHTML will be updated with the loaded default value.
function getDefaultValue(defaultKey, progParDivId, updateElemId)
{
  var dv = loadedDefaultValues[defaultKey];
  if (dv)
  {
    // We've already loaded it; use it.
    updateElemWithDefaultValue(dv);
  }
  else
  {
    // Create the div to indicate "Loading..." progress. The handler will collapse the div when we get the response.
    var loadingDiv = document.createElement("div");
    var divId = defaultKey + Math.round(1000 * Math.random());
    loadingDiv.setAttribute("id", divId);
    loadingDiv.className = progParDivId.className;
    loadingDiv.style.color = progParDivId.style.color;
    loadingDiv.style.fontSize = progParDivId.style.fontSize;
    loadingDiv.style.display = "block";
    loadingDiv.style.visibility = "visible";
    progParDivId.appendChild(loadingDiv);

    // Create a new DefaultValue object for this key.
    var updateElem = document.getElementById(updateElemId);
    loadedDefaultValues[defaultKey] = new DefaultValue(defaultKey, "", loadingDiv, updateElem, true);

    var fullURL = 'defaultValues.hg?defaultKey=' + defaultKey;
    xmlLoader(fullURL, getDefaultValueHandler, loadingDiv.id);
  }
}

function getDefaultValueHandler(xmlHttp, updateElementId)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);  

  var dvNode = xmlDoc.getElementsByTagName("defaultValue")[0];
  var defaultValue = "";
  if (dvNode.childNodes.length > 0)
  {
    defaultValue = dvNode.firstChild.data;
  }
  
  var defaultKey = dvNode.getAttribute("defaultKey");
  if (defaultKey && defaultKey != "")
  {
    var dv = loadedDefaultValues[defaultKey];
    if (dv)
    {
      // Set the default value.
      dv.defaultValue = defaultValue;
      
      // Collapse the "Loading..." div.
      dv.progressTextElem.style.display = "none";
      dv.progressTextElem.style.visibility = "hidden";
  
      // Update the control with the default value.
      updateElemWithDefaultValue(dv);
    }
  }
}

function updateElemWithDefaultValue(dv)
{
  dv.updateElem.value = dv.defaultValue;
  if (dv.selectElemOnUpdate)
  {
    // First, unselect any other previously-selected elems in the DefaultValue table (needed or ff keeps selecting them all -- ugly).
//    for (var key in loadedDefaultValues)
//    {
//      var loadedDv = loadedDefaultValues[key];
//      if (loadedDv.selectElemOnUpdate)
//      {
//        // only cross-browser method of unselecting text
//        var temptext = loadedDv.updateElem.value;
//        loadedDv.updateElem.value = "";
//        loadedDv.updateElem.value = temptext;
//      }
//    }
    dv.updateElem.select();
    dv.updateElem.focus(); 
  }
}

// object that holds default values
function DefaultValue(defaultKey, defaultValue, progressTextElem, updateElem, selectElemOnUpdate)
{
  this.defaultKey = defaultKey;
  this.defaultValue = defaultValue;
  this.progressTextElem = progressTextElem;
  this.updateElem = updateElem;
  this.selectElemOnUpdate = selectElemOnUpdate;
}
// table: defaultKey -> DefaultValue
var loadedDefaultValues = {};
function pageProductManager(showPage, totalPages)
{
  for(var i = 1; i <= totalPages; i++)
  {
    if(i != showPage)
    {
      hideElementWithId('page_'+i);
    }
    else
    {
      showElementWithId('page_'+i);
    }
  }
}


function generateLink(domainName, elementId){

	var url = domainName + "/";
	
	
	var radioElement;
	var destPage;
	for (var i = 1; i <= 4; i++) {
		radioElement = document.getElementById('destPage' + i);
		if (radioElement) {
			if (radioElement.checked) {
				destPage = radioElement.value;
			}
		}
	}
	
	var page;
	if (destPage) {
		if (destPage == 'homePage') {
			page = 'main.sc';
		}
		else 
			if (destPage == 'productPage') {
				page = 'product.sc';
				var productSelect = document.getElementById('destProd');
				if (productSelect) {
					page = page + '?productId=' + productSelect.value;
				}
			}
			else 
				if (destPage == 'categoryPage') {
					page = 'category.sc';
					var categorySelect = document.getElementById('destCat');
					if (categorySelect) {
						page = page + '?categoryId=' + categorySelect.value;
					}
				}
				else 
					if (destPage == 'searchPage') {
						page = 'searchquick-submit.sc';
						var keywords = document.getElementById('destKeywords');
						if (keywords) {
							page = page + '?queryString=' + escape(keywords.value);
						}
					}
		
		
		var sourceCode = '';
		var useSourceCode = document.getElementById('useSourceCode');
		if (useSourceCode && useSourceCode.checked) {
			if (destPage == 'homePage') {
				sourceCode = '?sourceCode=' + document.getElementById('sourceCode').value;
			}
			else {
				sourceCode = '&sourceCode=' + document.getElementById('sourceCode').value;
			}
		}
	}
	
	
	var link = url + page + sourceCode;
	
	var linkSpan = document.getElementById(elementId);
	
	if (linkSpan) {
		linkSpan.innerHTML = '<a href="' + link + '" target="_blank">' + link + '</a>';
	}
}

/************************************************/
/*                  OPTIONS                     */
/************************************************/

// cancel
function cancelOption( ) {
   var tBody = document.getElementById( 'optionGroups' );
     
   if ( isShown( 'optionValueEditorCell') && !confirm( 'Are you sure you want to discard the changes you have made to the ' +
                                                       document.getElementById('label').value + ' option?' ) ) 
      return;
   
   tlDeselectRow( tBody );
   
   var valueTBody = document.getElementById( 'customOptionValues' );
   
   // clear the rows
   tlClear( valueTBody, optionIdFilter );
   showElementWithId( 'noOptionsRow' );  
   
   // clear out the addOptionLabel 
   document.getElementById('addOptionLabel').value = '';
   
   // return the button back to it's initial state in case the user attempted to update
   showElementWithId( 'addOptionValueButton' );
   hideElementWithId( 'updateOptionValueButton' );   	 
   
   // clear the value
   document.getElementById('label').value = '';   
   
   // clear the option hidden id
   document.getElementById( 'optionId' ).value = '';

   // hide the editor
   hideElementWithId( 'optionValueEditorCell' );   
   showElementWithId( 'addOptionButton' );
   hideElementWithId( 'addOptionButtonSpacer' );   
}

// groups
function editOption( index ) {
   var tBody = document.getElementById( 'optionGroups' );
   
   var cellId = 'optionGroupLabelCell' + index;
   
   if ( isShown( 'optionValueEditorCell') && !confirm( 'Are you sure you want to discard the changes you have made to the ' +
                                                       document.getElementById('label').value + ' option?' ) ) 
      return;
   
   
   var valueTBody = document.getElementById( 'customOptionValues' );
   
   // clear the rows
   tlClear( valueTBody, optionIdFilter );
   showElementWithId( 'noOptionsRow' ); 

   if ( tlClickRow( tBody, cellId, 'selection-highlight' ) ) {
      // just selected
      
      // copy the value
      document.getElementById('label').value = 
           strTrim( document.getElementById(cellId).getElementsByTagName('A')[0].innerHTML );
      
      // copy the rows     
      var valueListTBody = 
           document.getElementById( 'optionValuesList' + index );
      
      var rowCount = 
           copyOptionValuesTable( index, valueListTBody );
      
            
      updateOptionButtons( valueTBody );      
      if ( rowCount > 0 ) {
         tlRestoreAlternatingRowStyle( valueTBody, optionIdFilter );
         hideElementWithId( 'noOptionsRow' );         
      }
      
      // set the option hidden id
      document.getElementById( 'optionId' ).value = index;
      
      // display the editor
      showElementWithId( 'optionValueEditorCell' );
      hideElementWithId( 'addOptionButton' );   
      showElementWithId( 'addOptionButtonSpacer' );
   
   
   } else {
      // just deselected
      
      // clear the value
      document.getElementById('label').value = '';
      
      
      // clear the option hidden id
      document.getElementById( 'optionId' ).value = '';
      
      // hide the editor
      hideElementWithId( 'optionValueEditorCell' );   
      showElementWithId( 'addOptionButton' );
      hideElementWithId( 'addOptionButtonSpacer' );
   
   }
}

function copyOption( index ) {
   var tBody = document.getElementById( 'optionGroups' );
   
   var cellId = 'optionGroupLabelCell' + index;
   
   if ( isShown( 'optionValueEditorCell') && !confirm( 'Are you sure you want to discard the changes you have made to the ' +
                                                       document.getElementById('label').value + ' option?' ) ) 
      return;
   
   
   var valueTBody = document.getElementById( 'customOptionValues' );
   
   // clear the rows
   tlClear( valueTBody, optionIdFilter );
   showElementWithId( 'noOptionsRow' );   

   // copy the value
   document.getElementById('label').value = 'Copy of ' + 
        strTrim( document.getElementById(cellId).getElementsByTagName('A')[0].innerHTML );

   // copy the rows     
   var valueListTBody = 
        document.getElementById( 'optionValuesList' + index );

   var rowCount = 
        copyOptionValuesTable( index, valueListTBody );


   updateOptionButtons( valueTBody );      
   if ( rowCount > 0 ) {
      tlRestoreAlternatingRowStyle( valueTBody, optionIdFilter );
      hideElementWithId( 'noOptionsRow' );         
   }

   // set the option hidden id
   document.getElementById( 'optionId' ).value = -1;

   // display the editor
   showElementWithId( 'optionValueEditorCell' );
   hideElementWithId( 'addOptionButtonRow' );   
}

function addOption( ) {
   var tBody = document.getElementById( 'optionGroups' );
       
   var valueTBody = document.getElementById( 'customOptionValues' );
   
   // clear the rows
   tlClear( valueTBody, optionIdFilter );
   showElementWithId( 'noOptionsRow' );   

   updateOptionButtons( valueTBody );      

   // set the option hidden id
   document.getElementById( 'optionId' ).value = -1;

   // display the editor
   showElementWithId( 'optionValueEditorCell' );
   hideElementWithId( 'addOptionButtonRow' );   
}

function copyOptionValuesTable( index, sourceTBody ) {
  var rowCount = 0;
  var matcher = new RegExp( "^option_" + index + "_value_(\\d+)$" );

  var valueTBody = document.getElementById( 'customOptionValues' );

  var trs = sourceTBody.getElementsByTagName('TR');
  var i;

  for ( i = 0; i < trs.length; i++ ) {
     var elem = trs[i].getElementsByTagName('TD')[0];

     if ( elem == null || elem.id == null || elem.id == '' ) {
        // ignore this row
     } else if ( matcher.test( elem.id ) ) {

        var valueId = RegExp.$1;

        rowCount++;

        tlAddRow( valueTBody, optionIdFilter, tlLastNumberParser, customOptionGenerator, 
                  strTrim( elem.getElementsByTagName('SPAN')[0].innerHTML ), valueId );


     } else {
        break;
     }

     elem = elem.nextSibling;      
  }
  
  return rowCount;
}


// values
function optionIdFilter( idString ) {
   if ( !idString || idString == '' || idString == 'addOptionRow' || idString == 'noOptionsRow' )
      return true;
}

function clickOption( index ) {
  var tBody = document.getElementById('customOptionValues');
  tlClickRow(tBody, 'optionCell' + index, 'selection-highlight');
  
  updateOptionButtons( tBody );
}

function moveUpOption() {
  var tBody = document.getElementById('customOptionValues');

   if ( tBody.selectedRow ) {
     var td = document.getElementById( tBody.selectedRow );
     var tr = td.parentNode;
     
     var parent = tr.parentNode;
     
     if ( tlGetPreviousSibling( tr, optionIdFilter ) ) {
        var sib = tlGetPreviousSibling( tr, optionIdFilter );
     
        parent.removeChild( tr );
        
        parent.insertBefore( tr, sib );
        
        swapSortOrderValues( tr, sib );
        
        updateOptionButtons( tBody );
        tlRestoreAlternatingRowStyle( tBody, optionIdFilter );
        
     }
   }
}

function moveDownOption() {
  var tBody = document.getElementById('customOptionValues');

   if ( tBody.selectedRow ) {
     var td = document.getElementById( tBody.selectedRow );
     var tr = td.parentNode;
     
     var parent = tr.parentNode;
     
     if ( tlGetNextSibling( tr, optionIdFilter ) ) {
        var sib = tlGetNextSibling( tr, optionIdFilter );
        
        parent.removeChild( sib );
        
        parent.insertBefore( sib, tr );
        
        swapSortOrderValues( tr, sib );
        
        updateOptionButtons( tBody );
        tlRestoreAlternatingRowStyle( tBody, optionIdFilter );
     }
   }
}

function swapSortOrderValues( tr1, tr2 ) {
   var index1 = tlLastNumberParser( tr1.id );
   var index2 = tlLastNumberParser( tr2.id );
   
   var temp = document.getElementById( 'optionValueSortOrder' + index1 ).value;
   document.getElementById( 'optionValueSortOrder' + index1 ).value = 
      document.getElementById( 'optionValueSortOrder' + index2 ).value;
   document.getElementById( 'optionValueSortOrder' + index2 ).value = temp;
}

function updateOptionButtons( tBody ) {

  if ( tBody.selectedRow ) {
  	 document.getElementById( "editOptionChoiceButton" ).src = "images/opval_edit.gif";
  
     document.getElementById( "deleteOptionButton" ).src = "images/opval_delete.gif";
     
     var td = document.getElementById( tBody.selectedRow );
     
     var tr = td.parentNode;

     if ( tlGetPreviousSibling( tr, optionIdFilter ) ) {
        document.getElementById( "moveUpOptionButton" ).src = "images/ibtn_moveup.gif";
     } else {
        document.getElementById( "moveUpOptionButton" ).src = "images/ibtn_moveup_dis.gif";
     }

     if ( tlGetNextSibling( tr, optionIdFilter ) ) {
        document.getElementById( "moveDownOptionButton" ).src = "images/ibtn_movedown.gif";  
     } else {
        document.getElementById( "moveDownOptionButton" ).src = "images/ibtn_movedown_dis.gif";  
     }     
 
  } else {
  	 document.getElementById( "editOptionChoiceButton" ).src = "images/opval_edit_dis.gif";
     document.getElementById( "deleteOptionButton" ).src = "images/opval_delete_dis.gif";
     document.getElementById( "moveUpOptionButton" ).src = "images/ibtn_moveup_dis.gif";
     document.getElementById( "moveDownOptionButton" ).src = "images/ibtn_movedown_dis.gif";  
  }
}

function addCustomOption() { 
  var id, label;

  if ( arguments.length > 0 ) {
     label = arguments[0];

     if ( arguments.length > 1 ) {
        id = arguments[0];
     } else {
        id = -1;
     }       
  } else {
     id = -1;
     label = document.getElementById('addOptionLabel').value;  
     
     if ( label == null || label == '' ) {
        alert( 'Please specify a value for this option.' );
        document.getElementById('addOptionLabel').focus();
        document.getElementById('addOptionLabel').select();
        return false;
     } else if (label.indexOf("#") != -1) {
        alert('Option value cannot contain \'#\'. Please specify another value.' );
        document.getElementById('addOptionLabel').focus();
        document.getElementById('addOptionLabel').select();
        return false;
     } else {
        document.getElementById('addOptionLabel').value = '';
     }
  }

  var tBody = document.getElementById('customOptionValues');
  
  var index = 
    tlAddRow( tBody, optionIdFilter, tlLastNumberParser, customOptionGenerator, label, id );
  tlRestoreAlternatingRowStyle( tBody, optionIdFilter );
  
  clickOption( index );
  
  updateOptionButtons( tBody );
  
  hideElement( document.getElementById('noOptionsRow') );
}

function customOptionGenerator( index, params ) {
   var label = params[0];
   var id = -1;
   
   if ( params.length > 1 ) {
       id = params[1];                
   }
   
   
   var trTag = document.createElement("tr");    
   trTag.setAttribute('id', 'optionRow' + index);
   
   var tdTag = document.createElement("td");
   tdTag.setAttribute('id', 'optionCell' + index);
   tdTag.align = 'center';
   tdTag.valign = 'top';
   tdTag.width = '100%';
   tdTag.onclick = function() { clickOption( index ) };
   
   tdTag.innerHTML =  '<a href="#" onClick="return false;">' + label + '</a>' +
                      '<input type="hidden" name="optionLabel(' + index + ')" value="' + label + '" id="optionLabel(' + index + ')"/>' +
                      '<input type="hidden" name="optionValueId(' + index + ')" value="' + id + '"/>' +
                      '<input type="hidden" id="optionValueSortOrder' + index +'" name="optionSort(' + index +')" value="' + index + '" size="2"/>';
                       
   trTag.appendChild( tdTag );
   
   return trTag;   
}

function customOptionEditor( index ) {
  var tBody = document.getElementById('customOptionValues');

  var index;
  var optionId;
  var optionLabel;
  if ( arguments.length > 0 ) {
     optionId = arguments[0];
     index = tlLastNumberParser( optionId );
  } else {
     if ( tBody.selectedRow ) {
        index = tlLastNumberParser( tBody.selectedRow );
        optionId = 'optionRow' + index;
        optionLabel = 'optionLabel(' + index + ')';
     } else {
        return false;
     }  
  }
  
  // make sure that the user entered a name into the field 
  if (document.getElementById('addOptionLabel').value == '') {
  	alert( 'You must give this option choice a name.' );
  	document.getElementById('addOptionLabel').focus();
  	document.getElementById('addOptionLabel').select();
  	return false;
  }
  
  var toSelect = null;
  if ( tBody.selectedRow == ('optionCell' + index) ) {
     var td = tlDeselectRow( tBody );
     var tr = td.parentNode;
     
     if ( tlGetNextSibling( tr, optionIdFilter ) ) {
        toSelect = 'optionCell' + tlLastNumberParser( tlGetNextSibling( tr, optionIdFilter ).id );
     } else if ( tlGetPreviousSibling( tr, optionIdFilter ) ) {
        toSelect = 'optionCell' + tlLastNumberParser( tlGetPreviousSibling( tr, optionIdFilter ).id );
     }
  }  
  
  var trToEdit = document.getElementById(optionId);
  trToEdit.getElementsByTagName('A')[0].innerHTML = document.getElementById('addOptionLabel').value;
  
  // get the new value from the textfield and update the value in the label tag
  var valueToEdit = document.getElementById(optionLabel);
  valueToEdit.value = document.getElementById('addOptionLabel').value;
  
  // clear out the value in the label tag and return the button back to it's original state
  document.getElementById('addOptionLabel').value = '';
  showElementWithId( 'addOptionValueButton' );
  hideElementWithId( 'updateOptionValueButton' );  
}

function editOptionChoice( index ) 
{
	var tBody = document.getElementById('customOptionValues');

	if ( tBody.selectedRow ) {
	  var td = document.getElementById( tBody.selectedRow );
	  var tr = td.parentNode;
	  
	  // place the value into the textfield to make editing possible
	 document.getElementById('addOptionLabel').value = 
	 strTrim( td.getElementsByTagName('A')[0].innerHTML );
	 }
	 hideElementWithId( 'addOptionValueButton' );
	 showElementWithId( 'updateOptionValueButton' );  
	 
	 // disable button options
	 document.getElementById( "editOptionChoiceButton" ).src = "images/opval_edit_dis.gif";
     document.getElementById( "deleteOptionButton" ).src = "images/opval_delete_dis.gif";
     document.getElementById( "moveUpOptionButton" ).src = "images/ibtn_moveup_dis.gif";
     document.getElementById( "moveDownOptionButton" ).src = "images/ibtn_movedown_dis.gif";   	 
}

function deleteCustomOption()
{
  var tBody = document.getElementById('customOptionValues');

  var index;
  var optionId;
  if ( arguments.length > 0 ) {
     optionId = arguments[o];
     index = tlLastNumberParser( optionId );
  } else {
     if ( tBody.selectedRow ) {
        index = tlLastNumberParser( tBody.selectedRow );
        optionId = 'optionRow' + index;
        
     } else {
        return false;
     }  
  }
  
  var toSelect = null;
  if ( tBody.selectedRow == ('optionCell' + index) ) {
     var td = tlDeselectRow( tBody );
     var tr = td.parentNode;
     
     if ( tlGetNextSibling( tr, optionIdFilter ) ) {
        toSelect = 'optionCell' + tlLastNumberParser( tlGetNextSibling( tr, optionIdFilter ).id );
     } else if ( tlGetPreviousSibling( tr, optionIdFilter ) ) {
        toSelect = 'optionCell' + tlLastNumberParser( tlGetPreviousSibling( tr, optionIdFilter ).id );
     }
  }  

  tlDeleteRow( tBody, optionId );
 
  tlRestoreAlternatingRowStyle( tBody, optionIdFilter );
  
  if ( toSelect != null ) {
     tlSelectRow(tBody, toSelect, 'selection-highlight');
  }
  
  updateOptionButtons( tBody );  
  
  if ( tlIsEmpty( tBody, optionIdFilter ) ) {
     showElement( document.getElementById('noOptionsRow') );
  }
}

/************************************************/
/*                 ATTRIBUTES                   */
/************************************************/

function editAttribute(attributeId, attributeType, shownOnWeb, attributeLabel, sortOrder, searchable)
{
  document.getElementById('attributeId').value = attributeId;
  document.getElementById('attributeType').value = attributeType;
  document.getElementById('shownOnWeb').value = shownOnWeb;
  var labelElement = document.getElementById('label');
  labelElement.value = attributeLabel;
  labelElement.select();
  labelElement.focus();
  
  var optionsArray = document.getElementById('sortOrder').options;
  for(var i = 0; i < optionsArray.length; i++)
  {
    if(optionsArray[i].value == sortOrder)
    {
      optionsArray[i].selected = true;
      break;
    }
  }
  if(new Boolean(searchable).valueOf())
  {
    document.getElementById('searchableYes').checked = true;
  }
  else
  {
    document.getElementById('searchableNo').checked = true;
  }
}

function selectAttributeForEdit(attributeId)
{
  if(document.selectedAttributeId)
  {
    document.getElementById('attributeDataTable_'+document.selectedAttributeId).className = document.originalClass;
  }
  if(attributeId && attributeId != '')
  {
    var attributeDataTable = document.getElementById('attributeDataTable_'+attributeId);
    if(attributeDataTable)
    {
      document.originalClass = attributeDataTable.className;
      document.selectedAttributeId = attributeId;
      attributeDataTable.className = 'selection-highlight';
    }
    else
    {
      document.originalClass = null;
      document.selectedAttributeId = null;    
    }
  }
}

function selectAttributeForEdit(attributeId)
{
  if(document.selectedAttributeId)
  {
    document.getElementById('attributeDataTable_'+document.selectedAttributeId).className = document.originalClass;
  }
  if(attributeId && attributeId != '')
  {
    var attributeDataTable = document.getElementById('attributeDataTable_'+attributeId);
    if(attributeDataTable)
    {
      document.originalClass = attributeDataTable.className;
      document.selectedAttributeId = attributeId;
      attributeDataTable.className = 'selection-highlight';
    }
    else
    {
      document.originalClass = null;
      document.selectedAttributeId = null;    
    }
  }
}

/************************************************/
/*                MANUFACTURER                  */
/************************************************/

function selectManufacturerForEdit(manufacturerId)
{
  if(document.selectedManufacturerId)
  {
    document.getElementById('manufacturer_label_'+document.selectedManufacturerId).className = document.manufacturerOriginalClass;
  }
  if(manufacturerId && manufacturerId != '')
  {
    var manufacturerLabelCell = document.getElementById('manufacturer_label_'+manufacturerId);
    if(manufacturerLabelCell)
    {
      document.manufacturerOriginalClass = manufacturerLabelCell.className;
      document.selectedManufacturerId = manufacturerId;
      manufacturerLabelCell.className = 'selection-highlight';
    }
    else
    {
      document.manufacturerOriginalClass = null;
      document.selectedManufacturerId = null;    
    }
  }
  var manufacturerNameInput = document.getElementById('name');  
  manufacturerNameInput.focus();
  manufacturerNameInput.select();
}

function clickManufacturer( manufacturerId ) {
   var forceSelect = false;

   if ( arguments.length >= 2 )
      forceSelect = arguments[1];
      
   if ( forceSelect || document.selectedManufacturerId != manufacturerId ) {
      // select
      document.getElementById('name').value=document.getElementById('manufacturerName_' +  manufacturerId).innerHTML;
      document.getElementById('manufacturerId').value= manufacturerId; 
      selectManufacturerForEdit(manufacturerId); 
      return false;   
         
   } else {  
      // deselect
      document.getElementById('name').value = '';
      document.getElementById('manufacturerId').value= -1;
      selectManufacturerForEdit(-1); 
      return false;   
      
   }
}


/************************************************/
/*                  CATEGORY                    */
/************************************************/
function categoryProductIdFilter( idString ) {
   if ( !idString || idString == '' || idString == 'addProductRow' || idString == 'noProductsRow' )
      return true;
}

function clickCategoryProduct( index ) {
  var tBody = document.getElementById('categoryProductTable');
  tlClickRow(tBody, 'categoryProductCell' + index, 'selection-highlight');
  
  updateCategoryProductButtons( tBody );
}

function sortCategoryProducts() {
  var tBody = document.getElementById('categoryProductTable');
  var tr, sib;
  var i, j, minIdx;
  var minVal, testVal;
  var cmp;
  var index1, index2;
  
  var trNodeList = tBody.getElementsByTagName("tr");
  for (i = 1; i < trNodeList.length - 1; i++)
  {
    minIdx = i;
    minVal = trNodeList[i].getElementsByTagName("td")[0].getElementsByTagName("span")[0].innerHTML;

    for (j = i + 1; j < trNodeList.length; j++)
    {
      testVal = trNodeList[j].getElementsByTagName("td")[0].getElementsByTagName("span")[0].innerHTML;
      cmp = testVal < minVal;
      if (cmp)
      {
        minIdx = j;
        minVal = testVal;
      }
    }

    if (minIdx > i) 
    {
      tr = tBody.rows[i];
      tmpEl = tBody.removeChild(tBody.rows[minIdx]);
      tBody.insertBefore(tmpEl, tr);
    } else {
      tmpEl = tBody.rows[i];
      tr = tlGetNextSibling(tmpEl, categoryProductIdFilter);
    }

    index1 = tlLastNumberParser(tr.id);
    index2 = tlLastNumberParser(tmpEl.id);
    document.getElementById('categoryProductSortOrder'+index2).value = i-1;
    document.getElementById('categoryProductSortOrder'+index1).value = i;
  }

  tlRestoreAlternatingRowStyle( tBody, categoryProductIdFilter );
}

function moveUpCategoryProduct() {
  var tBody = document.getElementById('categoryProductTable');

   if ( tBody.selectedRow ) {
     var td = document.getElementById( tBody.selectedRow );
     var tr = td.parentNode;
     
     var parent = tr.parentNode;
     
     if ( tlGetPreviousSibling( tr, categoryProductIdFilter ) ) {
        var sib = tlGetPreviousSibling( tr, categoryProductIdFilter );
     
        parent.removeChild( tr );
        
        parent.insertBefore( tr, sib );
        
        swapCategoryProductSortOrderValues( tr, sib );
        
        updateCategoryProductButtons( tBody );
        tlRestoreAlternatingRowStyle( tBody, categoryProductIdFilter );
        
     }
   }
}

function moveDownCategoryProduct() {
  var tBody = document.getElementById('categoryProductTable');

   if ( tBody.selectedRow ) {
     var td = document.getElementById( tBody.selectedRow );
     var tr = td.parentNode;
     
     var parent = tr.parentNode;
     
     if ( tlGetNextSibling( tr, categoryProductIdFilter ) ) {
        var sib = tlGetNextSibling( tr, categoryProductIdFilter );
        
        parent.removeChild( sib );
        
        parent.insertBefore( sib, tr );
        
        swapCategoryProductSortOrderValues( tr, sib );
        
        updateCategoryProductButtons( tBody );
        tlRestoreAlternatingRowStyle( tBody, categoryProductIdFilter );
     }
   }
}

function swapCategoryProductSortOrderValues( tr1, tr2 ) {
   var index1 = tlLastNumberParser( tr1.id );
   var index2 = tlLastNumberParser( tr2.id );
   
  
   var temp = document.getElementById( 'categoryProductSortOrder' + index1 ).value;
   document.getElementById( 'categoryProductSortOrder' + index1 ).value = 
      document.getElementById( 'categoryProductSortOrder' + index2 ).value;
   document.getElementById( 'categoryProductSortOrder' + index2 ).value = temp;
   
}

function updateCategoryProductButtons( tBody ) {

  if ( tBody.selectedRow ) {
     document.getElementById( "deleteCategoryProductButton" ).src = "images/opval_delete.gif";
     
     var td = document.getElementById( tBody.selectedRow );
     
     var tr = td.parentNode;

     if ( tlGetPreviousSibling( tr, categoryProductIdFilter ) ) {
        document.getElementById( "moveUpCategoryProductButton" ).src = "images/ibtn_moveup.gif";
     } else {
        document.getElementById( "moveUpCategoryProductButton" ).src = "images/ibtn_moveup_dis.gif";
     }

     if ( tlGetNextSibling( tr, categoryProductIdFilter ) ) {
        document.getElementById( "moveDownCategoryProductButton" ).src = "images/ibtn_movedown.gif";  
     } else {
        document.getElementById( "moveDownCategoryProductButton" ).src = "images/ibtn_movedown_dis.gif";  
     }     
 
  } else {
     document.getElementById( "deleteCategoryProductButton" ).src = "images/opval_delete_dis.gif";
     document.getElementById( "moveUpCategoryProductButton" ).src = "images/ibtn_moveup_dis.gif";
     document.getElementById( "moveDownCategoryProductButton" ).src = "images/ibtn_movedown_dis.gif";  
  }

}

function addCustomCategoryProduct() { 
  var id, label;

  id = -1;
  //label = document.getElementById('addProductCategoryLabel').value;
  
  var selectElement = document.getElementById('addProductCategoryLabel');
  var selectedIndex = selectElement.selectedIndex;
  var optionElement = selectElement.options[selectedIndex];
  
  var prodId = optionElement.value;
  label = optionElement.innerHTML;

  var tBody = document.getElementById('categoryProductTable');
  
  var index = 
  tlAddRow( tBody, categoryProductIdFilter, tlLastNumberParser, customCategoryProductGenerator, label, id, prodId );
  tlRestoreAlternatingRowStyle( tBody, categoryProductIdFilter );
  
  clickCategoryProduct( index );
  
  updateCategoryProductButtons( tBody );
  
  selectElement.removeChild(optionElement);

  if (selectElement.options.length == 0)
  {
    hideElement( document.getElementById('addProductRow') );
  }

  hideElement( document.getElementById('noProductsRow') );
  showElement( document.getElementById('sortCategoryProductsButton'));
}

function customCategoryProductGenerator( index, params ) {
   var label = params[0];
   var id = params[1];
   var prodId = params[2];
   
   var trTag = document.createElement("tr");    
   trTag.setAttribute('id', 'categoryProductRow' + index);
   
   var tdTag = document.createElement("td");
   tdTag.setAttribute('id', 'categoryProductCell' + index);
   tdTag.align = 'left';
   tdTag.valign = 'top';
   tdTag.width = '100%';
   tdTag.onclick = function() { clickCategoryProduct( index ) };
   
   tdTag.innerHTML =  '<span id="categoryProductLabel' + index + '">' + label + '</span>' +  
                      '<input type="text"  id="categoryProductId' + index + '" name="categoryProductId(' + index + ')" value="' + prodId + '"/>' +
                      '<input type="text"  id="categoryProductSortOrder' + index + '" name="categoryProductSortOrder(' + index + ')" value="' + index + '" size="2"/>';
   trTag.appendChild( tdTag );
   
   return trTag;   
}

function deleteCustomCategoryProduct()
{
  var tBody = document.getElementById('categoryProductTable');

  var index;
  var rowId;
  if ( arguments.length > 0 ) {
     rowId = arguments[o];
     index = tlLastNumberParser( rowId );
  } else {
     if ( tBody.selectedRow ) {
        index = tlLastNumberParser( tBody.selectedRow );
        rowId = 'categoryProductRow' + index;
        
     } else {
        return false;
     }  
  }
  
  var toSelect = null;
  if ( tBody.selectedRow == ('categoryProductCell' + index) ) {
     var td = tlDeselectRow( tBody );
     var tr = td.parentNode;
     
     if ( tlGetNextSibling( tr, categoryProductIdFilter ) ) {
        toSelect = 'categoryProductCell' + tlLastNumberParser( tlGetNextSibling( tr, categoryProductIdFilter ).id );
     } else if ( tlGetPreviousSibling( tr, categoryProductIdFilter ) ) {
        toSelect = 'categoryProductCell' + tlLastNumberParser( tlGetPreviousSibling( tr, categoryProductIdFilter ).id );
     }
  }  
  
  var prodId = document.getElementById('categoryProductId' + index).value;
  var label = document.getElementById('categoryProductLabel' + index).innerHTML;

  tlDeleteRow( tBody, rowId );
  
  var selectBox = document.getElementById('addProductCategoryLabel');
  var optionElement = document.createElement("option");
  optionElement.value = prodId;
  optionElement.innerHTML = label;
  
  var currentOptions = selectBox.options;
  var inserted = false;
  for (var i = 0; i < currentOptions.length; i++)
  {
    if (optionElement.innerHTML.toUpperCase() < currentOptions[i].innerHTML.toUpperCase())
    {
        selectBox.insertBefore(optionElement, currentOptions[i]);
        inserted = true;
        break;
    }
  }
  
  if (!inserted)
  {
    selectBox.appendChild(optionElement);
  }
  
  showElement(selectBox);
 
  tlRestoreAlternatingRowStyle( tBody, categoryProductIdFilter );
  
  if ( toSelect != null ) {
     tlSelectRow(tBody, toSelect, 'selection-highlight');
  }
  
  updateCategoryProductButtons( tBody );  
  
  if ( tlIsEmpty( tBody, categoryProductIdFilter ) ) {
     showElement( document.getElementById('noProductsRow') );
     hideElement( document.getElementById('sortCategoryProductsButton'));
  }

  showElement(document.getElementById('addProductRow'));
}

/************************************************/
/*                  CATEGORY                    */
/************************************************/

function updateAfterUpload()
{
	var callbackID = document.getElementById('callbackID').value;
  	var binaryDataID = document.getElementById('binaryDataID').value;
  	var previewBinaryDataID = document.getElementById('previewBinaryDataID').value;
	
	if(document.getElementById('smallImageId'))
	{
		parent.document.getElementById('product.chars.smallImageId').value = document.getElementById('smallImageId').value;
		//The large image has a different name because it existed before the other hidden input fields, and thus lacks consistency
		parent.document.getElementById('largeProductInput').value = document.getElementById('largeImageId').value;
		parent.document.getElementById('product.chars.zoomImageId').value = document.getElementById('zoomImageId').value;
		parent.document.getElementById('product.chars.zoomPreviewImageId').value = document.getElementById('zoomPreviewImageId').value;
		
		parent.document.getElementById('largeProductImage').src = "displayImage.hg?binaryDataId=" + document.getElementById('largeImageId').value;
		
		return;
	}
  			
  	var zoomPreviewImageID = parent.document.getElementById('zoomPreviewImageId');
  	var flashPreview = parent.document.getElementById('flashPreview');
  			
	//window.opener.document.getElementById(callbackID + 'Input').value = binaryDataID;
	//window.opener.document.getElementById(callbackID + 'Image').src = "displayImage.hg?binaryDataId=" + binaryDataID;
			
	if(zoomPreviewImageID != null && flashPreview != null && previewBinaryDataID != 0 && previewBinaryDataID != binaryDataID)
	{
		parent.document.getElementById(callbackID + 'Input').value = binaryDataID;
		parent.document.getElementById(callbackID + 'Image').src = "displayImage.hg?binaryDataId=" + binaryDataID;
	
		zoomPreviewImageID.value = previewBinaryDataID;
				
		if(binaryDataID != previewBinaryDataID && previewBinaryDataID != -1)
		{
			flashPreview.style.visibility = 'visible'; 
			flashPreview.style.cursor = 'pointer';
		}
		else
		{
			flashPreview.style.visibility = 'hidden'; 
		}
	}
	else
	{
		if (!callbackID) { return; }
		
		/*There is still the possibility a zoom preview is on the
		page and we'll need to make sure it stays updated
		*/
		if(zoomPreviewImageID != null && callbackID == 'zoomProduct')
		{
			zoomPreviewImageID.value = binaryDataID;
		}
		
		if(flashPreview != null && callbackID == 'zoomProduct')
		{
			flashPreview.style.visibility = 'hidden';
		}
		
		parent.document.getElementById(callbackID + 'Input').value = binaryDataID;
		parent.document.getElementById(callbackID + 'Image').src = "displayImage.hg?binaryDataId=" + binaryDataID;
	}
		
	if(isIE())
	{
		if(parent.document.getElementById('imageSectionTable') != null)
		{
			if(parent.document.getElementById('imageSectionTable').offsetHeight < parent.document.getElementById('images_content').style.height)
			{
				parent.document.getElementById('images_content').style.height = parent.document.getElementById('imageSectionTable').offsetHeight;
				parent.document.getElementById('imageHeaderTable').style.height = parent.document.getElementById('imageSectionTable').offsetHeight;
				parent.document.getElementById('imagesTabColumn').style.height = parent.document.getElementById('imageSectionTable').offsetHeight;
			}
		}
	}
	
	// 1/30/08 - Removed code here that was causing image uploads to either flash in Safari 
	// or not allow for second uploads in all browsers. See bug # 46072. 
}///////////////////////////////////////////////////////////
// THESE FUNCTIONS DEPENED ON THE FOLLOWING FILES
//   * common.js
//   * xmlutil.js
//
// The main function in this script file is:
//   categoryTreeBuilderHandler
// 
// This function will build a category tree navigation 
// menu based off of the xml document represented by the 
// xmlHttp object passed in.  This can be used in the
// way.
//
// <body onLoad="loadXML('categoryTree.xml', 
//       categoryTreeBuilderHandler, 'categoryNavigationTree');">
//   <div id="categoryNavigationTree"/>
// </body>
///////////////////////////////////////////////////////////

/**
 * Handler to generate the category navigation menu.
 * This handler should be passed into loadXML. 
 * @param xmlHttp the xml document to use to generate the category tree.
 * @param uri the uri of of the content should be set as the inner html
 *        of the specified element.
 * @param elementId the id of the element whose inner html should be replaced.
 */
function categoryTreeBuilderHandler(xmlHttp, contentElementId)
{
  var contentElement = document.getElementById(contentElementId);
  
    var xmlDoc =  XmlDocument.create();
    xmlDoc.loadXML(xmlHttp.responseText);
    var rootElement = xmlDoc.getElementsByTagName("root")[0];
    if(rootElement)
    {
      var categoryTreeWrapper = "<span class='"+rootElement.getAttribute("class")+"' id='categoryWrapper'>";
      //iterate over category tree and populate nodes
      var branches = rootElement.childNodes;
      for(var i = 0; i < branches.length; i++)
      { 
        if(branches[i].tagName == "branch")
        {
          categoryTreeWrapper += buildTree(xmlDoc, categoryTreeWrapper, true, branches[i], contentElementId);
        }
      }
      categoryTreeWrapper += "</span>";
      contentElement.innerHTML = categoryTreeWrapper;
      highlightCategory(getCookie('selectedCategory'));
    }
  
}

/**
 * Helper function to create the internals of a basic img html tag.
 * @param xmlDoc the xmlDocument that contains the image defintion to create.
 * @param imageName the name of the image whose definition is 
 *        contained in the specified xmlDoc.
 * @return the internals of an img html tag with the
 *         source and class attributes populated based on the image 
 *         definition.
 */
function createImage(xmlDoc, imageName)
{
  var images = xmlDoc.getElementsByTagName("image");
  var createdImage;
  for(var i = 0; i < images.length; i++)
  {
    if(images[i].getAttribute("name") == imageName)
    {
      createdImage = "img ";
      if(images[i].getAttribute("class"))
      {
        createdImage += "class='"+ images[i].getAttribute("class") + "' ";
      }
      createdImage += "border='0' ";
      createdImage += "src='"+images[i].getAttribute("src")+"'";
    }
  }
  
  return createdImage;
}

function isExpandedCategory(categoryId)
{
  var expandedCategories = getExpandedCategories();
  for(var i = 0; i < expandedCategories.length; i++)
  {
    if(expandedCategories[i] == categoryId)
    {
      return true;
    }
  }
  return false;
}


function getExpandedCategories()
{
  var expandedCategoriesCookie = getCookie("expandedCategories");
  if(expandedCategoriesCookie && expandedCategoriesCookie != null)
  {
    var expandedCategories = expandedCategoriesCookie.split("|^|");
    return expandedCategories;
  }
  return new Array();
}


function escapeHTML(string)
{
  string = string.replace(/</g, "&lt;");
  string = string.replace(/>/g, "&gt;");
  return string;
}


/**
 * Recursive function to build the category navigation tree.
 * @param xmlDoc the xml document that should be used to get 
 *        image information from.
 * @param parentWrapper the html string to append to when creating this
 *        branch of the tree.
 * @param childNode the node to add to this tree.
 * @param contentElementId the root element id of the tree container.
 * @return the html for the child node.
 */
function buildTree(xmlDoc, parentWrapper, showChild, childNode, contentElementId)
{
  var childId = childNode.getAttribute("id");
  var expandElement = isExpandedCategory(childId);
  
  var childNodeSpan = "<span class='"+childNode.getAttribute("class")+"' id='category-"+childId+"' style='display: "+(showChild ? "block" : "none")+"'>\n";
  childNodeSpan += "  <nobr>\n";
  var childCategories = getChildCategories(childNode);
  if(childCategories && childCategories.length > 0)
  {
    var plusImage = "    <"+createImage(xmlDoc, (expandElement ? "collapseBranchImage" : "expandBranchImage"));
    plusImage += " id='img-plusminus-"+childId+"'";
    plusImage += " onClick='toggleCategory(\""+childId+"\", \""+getImageSource(xmlDoc, 'expandBranchImage')+"\", \""+getImageSource(xmlDoc, 'collapseBranchImage')+"\");'";
    plusImage += "/>\n";
    childNodeSpan += plusImage; 
  }
  else 
  {
    var noChildrenImage = "    <"+createImage(xmlDoc, "noChildrenImage");
    noChildrenImage += " id='img-plusminus-"+childId+"'";
    noChildrenImage += "/>\n";
    childNodeSpan += noChildrenImage; 
  }

  var closedImage = "    <"+createImage(xmlDoc, "closeCategory");
  closedImage += " id='image-folder-"+childId+"'";
  closedImage += "/>\n";
  childNodeSpan += closedImage; 
 
  var categoryLink = "    <a id=\"category-link-"+childId+"\" class=\"categorymenu\" href=\"displayCategory.hg?categoryId="+childId+"\" onClick=\"expandCategory('"+childId+"'); highlightCategory('"+childId+"');\">";
  categoryLink += "<span class='"+"'>"+escapeHTML(childNode.getAttribute("label"))+"</span>";
  categoryLink += "</a>\n";
  childNodeSpan += categoryLink;
  childNodeSpan += "  </nobr>\n";
  
  if(childCategories && childCategories.length > 0)
  {
    for(var i = 0; i < childCategories.length; i++)
    {
      childNodeSpan += buildTree(xmlDoc, childNodeSpan, expandElement, childCategories[i], contentElementId);
    }
  }
  childNodeSpan += "</span>\n";
  return childNodeSpan;
}

/**
 * Helper function to get the image source from the xmlDocument
 * based on the image name.
 * @param xmlDoc the xmlDocument to get the image from.
 * @param imageName the name of the image whose source is desired from
 *        the specified document.
 * @return the source of the specified image name, or null if no 
 *         image has the specified name.
 */
function getImageSource(xmlDoc, imageName)
{
  var images = xmlDoc.getElementsByTagName("image");
  var imgSrc;
  for(var i = 0; i < images.length; i++)
  {
    if(images[i].getAttribute("name") == imageName)
    {
      imgSrc = images[i].getAttribute("src");
      break;
    }
  }
  return imgSrc;
}

/**
 * Helper function to get the list of children the
 * specified category contains.
 * @param categoryNode the node whose children are desired.
 * @return the array of child categories for the specified category,
 *         or empty array if the category does not have any children.
 */
function getChildCategories(categoryNode)
{
  var childNodes = categoryNode.childNodes;
  var childCategories = new Array();
  if(childNodes.length > 0)
  {
    for(var i = 0; i < childNodes.length; i++)
    {
      if(childNodes[i].tagName == "branch")
      {
        childCategories[childCategories.length] = childNodes[i];
      }
    }
  }
  return childCategories;
}


/**
 * Function to show or hide all children of a specified element id.
 * @param elementId the id of the element whose children should be
 *        hidden or shown.
 * @param tagToToggle specifies that only the children with the specified 
 *        tag name should be hidden or shown.  If this is not specified,
 *        all children will be toggled.
 */
function toggleCategory(categoryId, expandBranchImage, 
  collapseBranchImage)
{
  var parentElement = document.getElementById("category-"+categoryId);
  
  var childNodes = parentElement.childNodes;
  for(var i = 0; i < childNodes.length; i++)
  {
    if((childNodes[i].tagName + "").toLowerCase() == "span")
    {
      //determine how whether the children categories should 
      //be shown or hidden
      if(childNodes[i].style.display == "block" || 
        childNodes[i].style.display == "")
      {
        collapseCategory(categoryId, expandBranchImage, childNodes);
      }
      else
      {
        expandCategory(categoryId, collapseBranchImage, childNodes);
      }
      break;
    }
  }
}

function expandCategory(categoryId, expandedImageName, childNodes)
{
  var categoryElement = document.getElementById("category-"+categoryId);
  if(!childNodes)
  {
    if(categoryElement)
    {
      childNodes = categoryElement.childNodes;
    }
  }
  
  var expandedNode = false;
  if(childNodes)
  {
    // show all of the child cateories
    for(var i = 0; i < childNodes.length; i++)
    {
      if((childNodes[i].tagName + "").toLowerCase() == "span")
      {
        childNodes[i].style.display  = "block";      
        expandedNode = true;
      }
    }
  }
  
  if(expandedNode)
  {
    if(!expandedImageName)
    {
      expandedImageName = 'images/minus.gif';
    }

    var imageElement = document.getElementById("img-plusminus-"+categoryId);
    if(imageElement)
    {
      imageElement.src = expandedImageName;
    }
  }
  
  //make sure all parents are showing
  if(categoryElement)
  {
    var curElement = categoryElement.parentElement;
    while(curElement && curElement.id != "categoryWrapper")
    {
      expandCategory(curElement.id.substring("category-".length, curElement.id.length));
      curElement = curElement.parentElement;
    }
    
  }
  
  
  
  // add category to expanded categories state
  var fiftyYears = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 50);
  var cookieValue = getCookie('expandedCategories');
  if(!cookieValue || cookieValue == null)
  {
    cookieValue = "";
  }
  cookieValue += categoryId + "|^|";
  setCookie('expandedCategories', cookieValue, fiftyYears);
}

function collapseCategory(categoryId, collapsedImageName, childNodes)
{
  if(!childNodes)
  {
    parentElement = document.getElementById("category-"+categoryId);
    if(parentElement)
    {
      childNodes = parentElement.childNodes;
    }
  }
  
  var collapsedNode = false;
  if(childNodes)
  {
    // show all of the child cateories
    for(var i = 0; i < childNodes.length; i++)
    {
      if((childNodes[i].tagName + "").toLowerCase() == "span")
      {
        childNodes[i].style.display  = "none";     
        collapsedNode = true;
      }
    }
  }
  
  if(collapsedNode)
  {
    if(!collapsedImageName)
    {
      collapsedImageName = 'images/plus.gif';
    }
  
    var imageElement = document.getElementById("img-plusminus-"+categoryId);
    if(imageElement)
    {
      imageElement.src = collapsedImageName;
    }
  }
  
  // remove category from expanded categories state
  var expandedCategories = getExpandedCategories();
  var newCookieValue = "";
  for(var i = 0; i < expandedCategories.length; i++)
  {
    if(expandedCategories[i] != categoryId && expandedCategories[i] != "")
    {
      newCookieValue += expandedCategories[i] + "|^|";
    }
  }
  var fiftyYears = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 50);
  setCookie('expandedCategories', newCookieValue, fiftyYears);    
}


function toggleImage(imageElementId, image1, image2)
{
  var imageElement = document.getElementById(imageElementId);
  if(imageElement.src.indexOf(image2) > 0)
  {
    imageElement.src = image1;
  }
  else
  {
    imageElement.src = image2;
  }
}

function highlightCategory(categoryId)
{
  var oldCategoryLinkElement = document.getElementById("category-link-"+getCookie('selectedCategory'));
  var categoryLinkElement = document.getElementById("category-link-"+categoryId);
  
  if(oldCategoryLinkElement)
  {
    oldCategoryLinkElement.className = "categoryMenu"
  }
  if(categoryLinkElement)
  {
    categoryLinkElement.className = "selectedCategorymenu"
    
    
  }
  setCookie('selectedCategory', categoryId);    
}

//
//  To Set a session cookie which expires after the browser is closed
//  setCookie ('cookieName', 'cookieValue');
//  
//  To set a cookie which expires after 24 hours
//  var now = new Date();
//  var tomorrow = new Date(now.getTime() + 1000 * 60 * 60 * 24)
//  setCookie ('cookieName', 'cookieValue', tomorrow);
//  
//  To set a cookie with a path
//  setCookie ('cookieName', 'cookieValue', null, '/')
//
//  To delete a cookie you just set it with an expires date in the past:
//  var now = new Date();
//  var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
//  setCookie('cookieName', 'cookieValue', yesterday);
//  


function setCookie(cookieName, cookieValue, expires, path, domain,  secure) 
{
  document.cookie = 
    escape(cookieName) + '=' + escape(cookieValue) + 
      (expires ? '; EXPIRES=' + expires.toGMTString() : '') + 
      (path ? '; PATH=' + path : '') + 
      (domain ? '; DOMAIN=' + domain : '') +
      (secure ? '; SECURE' : '');
}

function getCookie(cookieName) 
{
  var cookieValue = null;
  var posName = document.cookie.indexOf(escape(cookieName) + '=');
  if (posName != -1) 
  {
    var posValue = posName + (escape(cookieName) + '=').length;
    var endPos = document.cookie.indexOf(';', posValue);
    if (endPos != -1)
    {
      cookieValue = unescape(document.cookie.substring(posValue, endPos));
    }
    else
    {
      cookieValue = unescape(document.cookie.substring(posValue));
    }
  }
  return cookieValue;
}

function removeCookie(cookieName, path, domain)
{
  document.cookie = 
    escape(cookieName) + '=;' + 
    'EXPIRES=Fri, 02-Jan-1970 00:00:00 GMT' + 
    (path ? '; PATH=' + path : '') + 
    (domain ? '; DOMAIN=' + domain : '');
 }
function editCouponShippingChange()
{
	var value = document.getElementById('shippingCouponValue').value;
	var shipping = document.getElementById('shippingCouponRadio').checked;
	if (shipping)
	{
		if ((value == '17') && (!isShown('coverageOutsideUS')))
		{
			// Set the display to empty string so that Both Firefox and IE should fall 
			// back on their respective default values. Since 'display:block' will cause
			// FireFox not rendering the page correctly.
			document.getElementById('coverageOutsideUS').style.display = '';
			document.getElementById('coverageOutsideUS').style.visibility = "visible";
		}
		else if ((value != '17') && (isShown('coverageOutsideUS')))
		{
			hideElementWithId('coverageOutsideUS');
		}
	}
	else
	{
		hideElementWithId('coverageOutsideUS');
	}
}
function froogleClickChangePassword() {
  if (document.getElementById('changePassword').checked ) {
      document.getElementById('ftpPassword').disabled = false;      
      document.getElementById('ftpPasswordt').style.color = 'black'; 
      
      if (!document.getElementById('changePassword').changed ) {             
         document.getElementById('ftpPassword').value = '';         
         document.getElementById('changePassword').changed = true;
      }      
   } else {
      document.getElementById('ftpPassword').disabled = true;       
      document.getElementById('ftpPasswordt').style.color = 'gray';       
   }
 }
 
var froogleFileNameChangedMsg = "Warning: The Filename has been changed. Please make sure \n" +
								"the Quick Shopping Cart Filename is identical to the filename \n" +
								"used when you registered your data feed with Google Product Search. \n\n" +
                                "Do you want to continue with the change?";
 
function validateFroogleSetupForm(formElement) {
  var fileName = document.getElementById("fileName");
  var fileNameOld = document.getElementById("fileNameOld");
  
  var reg = /\.XML$/i;
  
  if( ! reg.test(fileName.value) ) {
  	alert("File name must end in .xml");
  	return false;
  }
  
  if (!isEmpty(fileNameOld.value) && fileNameOld.value != fileName.value) {
    if (!confirm(froogleFileNameChangedMsg)) {
      fileName.value = fileNameOld.value;
      fileName.focus();
      fileName.select();
      return false;
    }
  }

  return true;
}

var froogleZeroProductSelected     = "You selected zero product for the Google Product Search Data Feed. No data   \n" +
                                     "feed will be send to Google Product Search.";
 froogleProductSelectedActive   =                     " products for the Google Product Search Data Feed. The data \n" +
                                     "feed will be send to Google Product Search when you publish your store.";
 froogleProductSelectedInactive =                     " products for the Google Product Search Data Feed. However, \n" +
                                     "your Google Product Search Data Feed is currently inactive. Please activate  \n" +
                                     "Google Product Search Data Feed if you want to send the data feed to Google Product Search.";

function validateFroogleAddItemForm(formElement) {
  var formElements = formElement.elements;
  var count = 0;
  for (var i=0; i<formElements.length; i++) {
    if (formElements[i].name.indexOf("itemList(") == 0 && formElements[i].checked) {
      count++;
    }
  }

  if (count == 0) {
    alert(froogleZeroProductSelected);
  } else {
    var optionStatus = document.getElementById("optionStatus");  
    if (optionStatus.value == "active") {
      alert("You selected " + count + froogleProductSelectedActive);
    } else {
      alert("You selected " + count + froogleProductSelectedInactive);
    }
  }
  
  return true;
} 

function checkAllProductsForDataExport(formName, nameStartWith) {
  var forms = document.forms;
  var i;
  var formElements;
  for(i=0; i<forms.length; i++) {
    if (forms[i].name == formName) {
      formElements = forms[i].elements;
      for(var i=0; i<formElements.length; i++) {
        if (formElements[i].name.indexOf(nameStartWith) == 0) {
          formElements[i].checked = true;    
        }
      }
    }
  }
}function uploadImage(callbackPrefix, maxHeight, maxWidth, blockAnimatedGIF) 
{
	var queryString = "?bean.maxHeight=" + maxHeight + "&bean.maxWidth=" + maxWidth + "&bean.blockAnimatedGIF=" + blockAnimatedGIF + "&bean.callbackID=" + callbackPrefix + "&bean.allowIcoImage=" + allowIcoImage;
	window.open('prepareImageUpload.hg' + queryString, 'Upload','width=500,height=220,resizable=0,status=yes;scrollbars=0',false);
}

function resetSystemDefaultImage(callbackPrefix, defaultImageID)
{
	document.getElementById(callbackPrefix + "Input").value = defaultImageID;		
	document.getElementById(callbackPrefix + "Image").src = "displayImage.hg?binaryDataId=" + defaultImageID;
	
	if(callbackPrefix == 'zoomProduct')
	{
		var zoomPreview = document.getElementById('zoomPreviewImageId');
		var flashViewer = document.getElementById('flashPreview');
		
		if(zoomPreview != null && flashPreview != null)
		{
			zoomPreview.value = defaultImageID;
			flashViewer.style.visibility = 'hidden';
		}
	}
}


/////////////////////////////////////////////////////////// 
// Author: Anthony Anter, cjellick
//
// This function will facilitate a digiltal product download
//
///////////////////////////////////////////////////////////

function postFormData(theForm)
{
	theForm.submit();
	var downRem = document.getElementById(theForm.orderItemId.value);
	if(downRem)
	{
		downRem.innerHTML = parseInt(downRem.innerHTML)-1;
	}
}// Paraphrased and extended from O'Reilly Dynamic HTML

// ** utility functions **

function setZIndex(obj, zOrder) {
   obj.zIndex = zOrder;
}

function setBorderColor(obj, color) {
   obj.borderColor = color;
}

function shiftTo(obj, x, y) {
   obj.style.left = x;
   obj.style.top = y;
}

// ** end utility functions **

var selectedObj;
var offsetX, offsetY;

function dragMove( evt ) {
   if (selectedObj) {
      if (isIE()) {
         shiftTo( selectedObj, (window.event.clientX - offsetX),
                               (window.event.clientY - offsetY) );
                               
         return false;
         
      } else {
         shiftTo( selectedObj, (evt.pageX - offsetX), (evt.pageY - offsetY) );
      }
   }
}

function frameDragMove( evt, fr ) {   
   if (selectedObj) {      
      var frameX = parseInt( getElementLeft( document.getElementById( fr ) ) );
      var frameY = parseInt( getElementTop( document.getElementById( fr ) ) );
   
      if (isIE()) {
         shiftTo( selectedObj, (frames[fr].window.event.clientX + frameX - offsetX),
                               (frames[fr].window.event.clientY + frameY - offsetY) );
                               
         return false;
         
      } else {
         shiftTo( selectedObj, (evt.pageX - offsetX), (evt.pageY - offsetY) );
      }
   }
}

function dragEngage( evt, source, elem ) {
   selectedObj = elem;
   
   if ( isIE() ) {
      offsetX = parseInt(window.event.clientX) - parseInt(selectedObj.style.left);
      offsetY = parseInt(window.event.clientY) - parseInt(selectedObj.style.top);
   
   } else {
      offsetX = parseInt(evt.pageX) - parseInt(selectedObj.style.left);
      offsetY = parseInt(evt.pageY) - parseInt(selectedObj.style.top);
   }
   
   if ( !isIE() ) {
      document.captureEvents( Event.MOUSEMOVE );
      document.captureEvents( Event.MOUSEUP );
   }
 
   document.onmousemove = dragMove;
   document.onmouseup = dragRelease;
}

function dragRelease( evt ) {
   if (selectedObj) { 
      selectedObj = null;
   }
}
   
function addDragIFrame( frameId ) {
    if ( !isIE() ) {
      frames[frameId].document.captureEvents( Event.MOUSEMOVE );
      frames[frameId].document.captureEvents( Event.MOUSEUP );    
    }
    
    frames[frameId].document.onmouseup = dragRelease;
    frames[frameId].document.onmousemove = function (evt) { frameDragMove( evt, frameId ); };
}function getProductEbayListItem(selectBoxId, url)
{
    var selectBox = document.getElementById(selectBoxId);    
    if (selectBox)
    {
	  var partNumber = selectBox.value;
      if (partNumber)
      {
		var handleSuccess = getProductEbayListItemHandlerSuccess;
		var handleFailure = getProductEbayListItemHandlerFailure;	
		var callback = {success:handleSuccess, failure:handleFailure};
	    var fullURL = url + '?partNumber=' + escape(partNumber);
		YAHOO.util.Connect.asyncRequest('GET', fullURL, callback);
      }
    }
}

function getProductEbayListItemHandlerSuccess(ajaxResponse)
{
  var json = YAHOO.lang.JSON.parse(ajaxResponse.responseText);
    
  document.getElementById('itemTitle').value = json.label;
  document.getElementById('itemDescription').value = json.description;
  document.getElementById('shippingWeightLbs').value = json.weight;
  document.getElementById('inputPictureCont').innerHTML = json.pictureOptionsHTML;
  
  if (json.hasImages)
  {  
	document.getElementById('gallery').disabled=false;
	document.getElementById('featuredGallery').disabled=false;
  }
  else
  {
	document.getElementById('gallery').disabled=true;
	document.getElementById('featuredGallery').disabled=true;
  }
}

function getProductEbayListItemHandlerFailure(ajaxResponse)
{
  window.alert("Unable to get information for the selected product.  If this continues, contact support.");
}

function removeDefaultPartNumberOption(selectBoxId, optionId)
{
    var selectBox = document.getElementById(selectBoxId);
    var selectedItem = selectBox.value;

    var optionElement = document.getElementById(optionId);
    
    if (optionElement)
    {
        var selectBoxElement = document.getElementById(selectBoxId);
        selectBoxElement.removeChild(optionElement);
    }
    
    selectBox.value = selectedItem;
}


function insertNewLocation(locId, location, zipCode)
{
  var newOption = document.createElement("OPTION");
  newOption.setAttribute('value', locId);
  newOption.innerHTML = location + "  " + zipCode;
  
  var selectBox = document.getElementById('locationDropDown');
  if (selectBox)
  {
    selectBox.appendChild(newOption);
  }
  
  newOption.selected = true;
  
  hideElementWithId('ebayNewLocationPopup-table');
  
  //frames['ebayNewLocationPopup-frame'].history.go(-1);
  frames['ebayNewLocationPopup-frame'].location.href='ebayNewLocationPopup.hg';
}

function insertNewEbayCategory(categoryId, categoryPath, elementId, appHost, lotSizeDisabled, paramArray)
{
//    alert("categoryId: " + categoryId + "; categoryPath: " + categoryPath + "; elementId: " + elementId);
//    if (paramArray != null)
//    {
//      for (var i = 0; i < paramArray.length; i++)
//      {
//        alert("paramArray[" + i + "] = " + paramArray[i]);
//      }
//    }

    var element = document.getElementById(elementId);
    
    if (element)
    {
        element.value = categoryId;
    
        var hiddenElement;
        var catPath;      
        
        if (elementId == 'category1')
        {
            hiddenElement = document.getElementById('category1-hidden');    
            hiddenElement.value = categoryId;
        
            //alert(categoryPath);
            catPath = document.getElementById('categoryPath1');
            if (catPath)
            {
                catPath.innerHTML = categoryPath;
            }
        
            hideElementWithId('ebayCategoryPopup1-table');
            //frames['ebayCategoryPopup1-frame'].history.go(-1);
			frames['ebayCategoryPopup1-frame'].location.href='ebayCategoryPopup.hg?elementId=category1';
        } else {
            hiddenElement = document.getElementById('category2-hidden');
            hiddenElement.value = categoryId;
            
            catPath = document.getElementById('categoryPath2');
            if (catPath)
            {
                catPath.innerHTML = categoryPath;
            }        
        
            hideElementWithId('ebayCategoryPopup2-table');
            //frames['ebayCategoryPopup2-frame'].history.go(-1);
			frames['ebayCategoryPopup2-frame'].location.href='ebayCategoryPopup.hg?elementId=category2';
        }
        
        setupItemSpecifics(elementId, paramArray);        
        disableLotSize(lotSizeDisabled);
    }
}


function setupItemSpecifics(elementId, paramArray)
{
  var myDiv = document.getElementById(elementId + '-attributes');
  if (!myDiv)
  {
    return;
  }
  
  //lets nuke any existing values
  while (myDiv.hasChildNodes())
  {
  	myDiv.removeChild(myDiv.firstChild);
  }
  
  if (paramArray != null)
  {
    for (var i = 0; i < paramArray.length; i++)
    {
      //alert("paramArray[" + i + "] = " + paramArray[i]);
      var vals = paramArray[i].split("=");
      var paramName = vals[0];
      var paramValue = vals[1];
      //alert("name=" + paramName + "; value=" + paramValue);
      
      var inputElement = document.createElement("input");
      inputElement.type = 'hidden';
      inputElement.name = paramName;
      inputElement.value = paramValue;
      myDiv.appendChild(inputElement);
    }
  }
}


function disableLotSize(lotSizeDisabled)
{
    if (lotSizeDisabled == '1')
    {
        if (isShown('type_lots_label'))
        {
            alert("You have selected a category that does not support 'Lots'.  The ability to sell lots will be disabled at this time.  If you wish to re-enable lots, then please select a different category.");
            toggleLotSize('type_individual_label');
        }

        hideElementWithId('lots_radio_table');
        document.getElementById('quantityTypeIndividual').checked = true;
    } else {
        showElementWithId('lots_radio_table');
    }
}


function toggleLotSize(elementId)
{

    if (!isShown(elementId))
    {
        if (elementId == 'type_individual_label')
        {
            document.getElementById('individualQuantity').disabled=false; 
            document.getElementById('lotsQuantity').disabled=true; 
            document.getElementById('lotsSize').disabled=true; 
            toggleElementWithId('type_lots_label');             
            toggleElementWithId('type_individual_label');
            if (!document.getElementById('auctionTypeFixed').checked)
            {
                ebayQuantityCheck('individualQuantity');
            }
        } else {
            document.getElementById('lotsQuantity').disabled=false; 
            document.getElementById('lotsSize').disabled=false; 
            document.getElementById('individualQuantity').disabled=true;             
            toggleElementWithId('type_individual_label'); 
            toggleElementWithId('type_lots_label'); 
            if (!document.getElementById('auctionTypeFixed').checked)
            {
                ebayQuantityCheck('lotsQuantity');
            }
        }
    }


}


function toggleCounterImage()
{
    var counterSelectBox = document.getElementById('counterSelectBox');
    
    if (counterSelectBox)
    {
        var counter = counterSelectBox.value;
        var image = document.getElementById('counterImage');
        
        if (counter && image)
        {
            if (counter == '0')
            {
                image.src = 'images/spacer.gif';
            } else if (counter == '1') {
                image.src = 'images/counter_andale.gif';
            } else if (counter == '2') {
                image.src = 'images/counter_green_led.gif';
            } else if (counter == '3') {
                image.src = 'images/counter_hidden.gif';
            }
        }
    }
}


function expandEbayCategoryTree(categoryId, url)
{
    var tableElement = document.getElementById('cat-table-' + categoryId);
    if (tableElement)
    {
        toggleElement(tableElement);
    } else {
        xmlLoader(url, retrieveEbayCategoryHandler, 'category-cell-' + categoryId);
    }
}


function clearCategorySelection(categoryTextBoxId, categoryHiddenId, categoryPathId, categoryAttributesId)
{
    var categoryTextBoxElement = document.getElementById(categoryTextBoxId);
    if (categoryTextBoxElement)
    {
        categoryTextBoxElement.value = '';
    }
    
    var categoryHiddenElement = document.getElementById(categoryHiddenId);
    if (categoryHiddenElement)
    {
        categoryHiddenElement.value = '';
    }
    
    var categoryPathElement = document.getElementById(categoryPathId);
    if (categoryPathElement)
    {
        categoryPathElement.innerHTML = '';
    }
    
    
    var categoryAttributesElement = document.getElementById(categoryAttributesId);
    if (categoryAttributesElement)
    {
        //lets nuke any existing values
        while (categoryAttributesElement.hasChildNodes())
        {
        	categoryAttributesElement.removeChild(categoryAttributesElement.firstChild);
        }
    }
}


function retrieveEbayCategoryHandler(xmlHttp, contentElementId)
{
  //var xmlDoc =  XmlDocument.create();
  document.getElementById(contentElementId).innerHTML = xmlHttp.responseText;
}


function toggleAuctionType(elementId)
{
    if (isShown(elementId))
    {
        if (elementId == 'auctionTypeOnline')
        {
            var quantity;
            if (document.getElementById('quantityTypeIndividual').checked)
            {
                quantity = document.getElementById('individualQuantity');
            } else {
                quantity = document.getElementById('lotsQuantity');
            }
            
            if (quantity.value == 1)
            {
                enableReservePrice();
                enableBuyItNowPrice();
            }
        } else {
            disableReservePrice();
            disableBuyItNowPrice();
        }
    }
}


function disableReservePrice()
{
    hideElementWithId('reservePriceLabel');
    hideElementWithId('reservePriceBox');
    document.getElementById('reservePriceBox').disabled = true;
}

function enableReservePrice()
{
    showElementWithId('reservePriceLabel');
    showElementWithId('reservePriceBox');
    document.getElementById('reservePriceBox').disabled = false;
}

function disableBuyItNowPrice()
{
    hideElementWithId('buyItNowLabel');
    hideElementWithId('buyItNowBox');
    document.getElementById('buyItNowBox').disabled = true;
}

function enableBuyItNowPrice()
{
    showElementWithId('buyItNowLabel');
    showElementWithId('buyItNowBox');
    document.getElementById('buyItNowBox').disabled = false;
}


function togglePlusMinusImageBW(imageId)
{
    if (imageId)
    {
        var imageElement = document.getElementById(imageId);
        if (imageElement)
        {
            var src = imageElement.src;
            if (src.indexOf('images/plus_bw.gif') > 0)
            {
                imageElement.src = 'images/minus_bw.gif';
            } else {
                imageElement.src = 'images/plus_bw.gif';
            }
        }
    }
}

function togglePlusMinusImage(imageId)
{
    if (imageId)
    {
        var imageElement = document.getElementById(imageId);
        if (imageElement)
        {
            var src = imageElement.src;
            if (src.indexOf('images/plus.gif') > 0)
            {
                imageElement.src = 'images/minus.gif';
            } else {
                imageElement.src = 'images/plus.gif';
            }
        }
    }
}


function updateItemSpecifics(appHost, categoryId, elementId)
{
    var url = appHost + 'ebayRetrieveItemSpecifics.hg?categoryId=' + categoryId;
    var elementName = 'item-specifics-' + elementId;
    xmlLoader(url, retrieveItemSpecificsHandler, elementName);
}


function retrieveItemSpecificsHandler(xmlHttp, elementId)
{    
    var respText = xmlHttp.responseText;
    var responseText = respText.substring(respText.indexOf('?>') + 2, respText.length);
    
    if (responseText != '')
    {
        
        hideElementWithId('noItemSpecificsMessage');
        document.getElementById(elementId).innerHTML = responseText;
        showElementWithId('item_specifics');
        
        alert(document.scripts.length);
        var scriptTag;
        var scriptIndex;
        var temp = new Array();
        temp = responseText.split('//--></script>');
        for (var i = 0; i < temp.length; i++)
        {
            if (temp[i].indexOf("<script") == 0)
            {
                
                scriptTag = temp[i] + '//--></script>';
                //scriptIndex = scriptTag.indexOf('<!--');
                //scriptTag = scriptTag.substring(scriptIndex + 4);
                //alert(scriptTag);
                //eval(scriptTag);
                document.scripts(document.scripts.length) = scriptTag;
            }
        }
    } else {
        var item1 = document.getElementById('item-specifics-category1');
        var item2 = document.getElementById('item-specifics-category2');
        
        var tmp;
        if (elementId = 'item-specifics-category1')
        {
            item1.innerHTML = '';
            hideElementWithId('item-specifics-category1');
            tmp = item2.innerHTML;
            if (tmp == '' || tmp.indexOf('<img') == 0)
            {
                showElementWithId('noItemSpecificsMessage');
            }
        } else {
            item2.innerHTML = '';
            hideElementWithId('item-specifics-category2');
            tmp = item1.innerHTML;
            if (tmp == '' || tmp.indexOf('<img') == 0)
            {
                showElementWithId('noItemSpecificsMessage');
            }        
        }
    }
}


function ebayQuantityCheck(elementId)
{
    var element = document.getElementById(elementId);
    
    if (element)
    {
    
        if (element.value > 1)
        {
            disableReservePrice();
            disableBuyItNowPrice();
        } else if (element.value == 1) {
            enableReservePrice();
            enableBuyItNowPrice();
        } else {
            element.value = '1';
            enableReservePrice();
            enableBuyItNowPrice();
        }
    }
}


function ebayEditListedItem(formId)
{
    var formElement = document.getElementById(formId);
    if (formElement)
    {
        formElement.action = 'ebayEditNewListing.hg';
        formElement.submit();
    }
}

/*******************************************************/
/*         Validation on the listing form              */
/*******************************************************/
EBAY_NO_PART_NUMBER_ERROR = 'Please choose a product to list.  If your store does not yet contain products, you will need to add one by going to Catalog -> Product';
EBAY_NO_CATEGORY_ERROR = 'You must list this item in at least one category.';
EBAY_NO_LOCATION_ERROR = 'You must choose the location you are selling this item from.  If you have not yet defined any locations, please press the \'New Item Location\' button.';
EBAY_NO_STARTING_PRICE_ERROR = 'Please enter a valid starting price that is greater than 0.';
EBAY_BAD_QUANTITY_ERROR = 'Please enter a valid quantity of at least 1.';
EBAY_BAD_LOTS_ERROR = 'Please enter a valid number of items per lot of at least 1.';
EBAY_NO_DOMESTIC_ERROR = 'You must choose at least one domestic shipping service.';
EBAY_DUPLICATE_SERVICES_ERROR = 'You cannot choose the same service twice.'
EBAY_NO_INTERNATIONAL_ERROR = 'Since you have checked at least 1 international shipping destination, you must choose at least one international shipping service.';
EBAY_NO_NONCANADA_ERROR = 'Since you have checked at least 1 international shipping destination besides Canada, you must choose at least one international shipping service that is not limited to Canada.';
EBAY_BAD_SHIP_PRICE_ERROR = 'Please enter a valid positive number for the price of ';
EBAY_FREE_SHIP_CONFIRM_START = 'You have elected to offer ';
EBAY_FREE_SHIP_CONFIRM_END = ' for free.  Are you sure you want to do this?';
EBAY_BAD_SALES_TAX_ERROR = 'Please enter a valid positive sales tax percentage.';
EBAY_BAD_LBS_ERROR = 'Please enter a valid positive number (no decimals) for the portion of the weight in pounds.';
EBAY_BAD_OZS_ERROR = 'Please enter a valid positive number (no decimals) for the portion of the weight in ounces.';
EBAY_ZERO_WEIGHT_ERROR = 'Please enter a non-zero weight for your package.';
EBAY_BAD_HANDLING_COST_ERROR = 'Please enter a valid positive or zero handling cost.';
EBAY_BAD_RESERVE_PRICE_ERROR = 'Please enter a valid number for your reserve price.';
EBAY_RESERVE_PRICE_TOO_LOW_ERROR = 'The reserve price of your auction must be greater than the starting price.';
EBAY_RESERVE_PRICE_CANNOT_BE_INCREASED_ERROR = 'The revised reserve price of your auction cannot be higher than the original reserve price';
EBAY_BIN_PRICE_CANNOT_BE_CHANGED_ERROR = 'The revised Buy It Now price of your auction cannot be changed. (Leave the field empty to remove the Buy It Now feature)';
EBAY_BAD_BUY_IT_NOW_PRICE_ERROR = 'Please enter a valid number for your Buy It Now price, or leave the field blank.';
EBAY_BUY_IT_NOW_PRICE_TOO_LOW_ERROR = 'The Buy It Now price of your auction must be greater than the starting price and the reserve price (if you are using one).';
EBAY_NO_PAYMENT_ERROR = 'You must enable at least one payment method.';
EBAY_NO_PAYPAL_EMAIL_ERROR = 'Please input a valid payment notification email address in order to support PayPal.';
EBAY_PACKAGE_NOT_OVERSIZE_CONFIRM = 'The package dimensions you have entered do not correspond to an oversize package.  Would you like to mark this as a standard package? (Please note, if you select no you will need to change the package dimensions before you can submit this form.)';
EBAY_PACKAGE_NOT_OVERSIZE2_CONFIRM = 'The package dimensions you have entered do not correspond to an very large/oversize 2 package.  Would you like to mark this as a large package/oversize 1? (Please note, if you select no you will need to change the package dimensions before you can submit this form.)';
EBAY_PACKAGE_VERY_LARGE_ERROR = 'The package dimensions you have entered must be marked as a \'Very large package/oversize 2\'.  This may affect the shipping services available to you.';
EBAY_PACKAGE_TOO_BIG_ERROR = 'The package size you have entered is too large to be shipped by any carriers supported by eBay.  You will need to mark your auction as local pickup only or use flat shipping.';
EBAY_BAD_PACKAGE_DIMENSION_ERROR = 'Please enter valid positive whole numbers for your package dimensions.';
EBAY_PACKAGE_IS_IRREGULAR_CONFIRM = 'The package dimensions you have entered are considered to be \'Irregular or unusual\'. Would you like to mark this as an irregular package? (Please note, if you select no you will need to change the package dimensions before you can submit this form.)';
EBAY_NO_SHIP_COUNTRIES_SELECTED = 'Since you have selected at least 1 international shipping service, you must choose at least one international shipping destination.';

function getSelectValue(sel) {
   return sel.options[ sel.selectedIndex ].value;
}

function getSelectText(sel) {
   return sel.options[ sel.selectedIndex ].innerHTML;
}

function ebayValidateShipPrice(elem, service) {
   if ( !isFloat(elem.value) || ( parseFloat(elem.value) < 0 ) ) {
      alert( EBAY_BAD_SHIP_PRICE_ERROR + service + '.' );   
      showElement( document.getElementById('shipping_content') );
      if (!isElementShown(elem))
         showElement( elem );
      elem.select();
      return false;
   }
   if ( parseFloat(elem.value) == 0 ) {
      if( !confirm( EBAY_FREE_SHIP_CONFIRM_START + service + EBAY_FREE_SHIP_CONFIRM_END ) ) {
         showElement( document.getElementById('shipping_content') );
         
         if (!isElementShown(elem))
            showElement( elem );
            
         elem.select();
         return false;
      }
   }
   return true;
}

function ebayValidateServiceSet(form, services, type, flat, require1message) {
  // check for at least one service (if require1)
  // also top-justify the services
  // also, if we are in flat mode, check that each service has a valid price
  if ( getSelectValue(services[0]) == 0 ) {
     if ( getSelectValue(services[1]) == 0 ) {
        if ( getSelectValue(services[2]) == 0 ) {
           // all empty
           if (require1message) {
              alert(require1message);
              showElement( document.getElementById('shipping_content') );
              services[0].focus(); 
              return false;
              
           } else {
              return true;
           }
        } else {
           // only 3 is non-empty
           services[0].selectedIndex = services[2].selectedIndex;
           services[2].selectedIndex = 0;               

           if ( flat ) {
              changeFlatService(type, 1);
              changeFlatService(type, 3);

              form['product.shipping.' + type + 'ServiceCost1'].value = 
               form['product.shipping.' + type + 'ServiceCost3'].value; 
              form['product.shipping.' + type + 'ServiceCost3'].value = "";               
           }
        }
     } else {
        // 1 is empty, 2 is non-empty, 3 is ?
        services[0].selectedIndex = services[1].selectedIndex;
        services[1].selectedIndex = services[2].selectedIndex;
        services[2].selectedIndex = 0;

        if ( flat ) {
           changeFlatService(type, 1);
           changeFlatService(type, 2);
           changeFlatService(type, 3);

           form['product.shipping.' + type + 'ServiceCost1'].value = 
            form['product.shipping.' + type + 'ServiceCost2'].value; 
           form['product.shipping.' + type + 'ServiceCost2'].value = 
            form['product.shipping.' + type + 'ServiceCost3'].value; 
           form['product.shipping.' + type + 'ServiceCost3'].value = "";               
        }         
     }

  } else {
     // 1 is non-empty

     if ( (getSelectValue(services[1]) == 0 ) &&
          (getSelectValue(services[2]) != 0 )) {

        // 2 is empty but 3 has data           
        services[1].selectedIndex = services[2].selectedIndex;
        services[2].selectedIndex = 0;               

        if ( flat ) {
           changeFlatService(type, 2);
           changeFlatService(type, 3);

           form['product.shipping.' + type + 'ServiceCost2'].value = 
            form['product.shipping.' + type + 'ServiceCost3'].value; 
           form['product.shipping.' + type + 'ServiceCost3'].value = "";               
        }         
     }      
  }

  // check uniqueness
  if ( getSelectValue(services[1]) != 0 ) {
     if ( getSelectValue(services[1]) == getSelectValue(services[0]) ) {
        alert(EBAY_DUPLICATE_SERVICES_ERROR);
        showElement( document.getElementById('shipping_content') );
        services[1].focus();
        return false;
     }  

     if ( getSelectValue(services[2]) != 0 ) {

       if ( getSelectValue(services[2]) == getSelectValue(services[0]) ) {
          alert(EBAY_DUPLICATE_SERVICES_ERROR);
          showElement( document.getElementById('shipping_content') );
          services[2].focus();
          return false;
       }           

       if ( getSelectValue(services[2]) == getSelectValue(services[1]) ) {
          alert(EBAY_DUPLICATE_SERVICES_ERROR);
          showElement( document.getElementById('shipping_content') );
          services[2].focus();
          return false;
       }        

     }
  }
  
  if ( flat ) {
     if (!ebayValidateShipPrice( form['product.shipping.' + type + 'ServiceCost1'], getSelectText(services[0]) ))
       return false;
       
     if ( getSelectValue(services[1]) != 0 &&
          !ebayValidateShipPrice( form['product.shipping.' + type + 'ServiceCost2'], getSelectText(services[1]) ))
       return false;
       
     if ( getSelectValue(services[2]) != 0 &&
          !ebayValidateShipPrice( form['product.shipping.' + type + 'ServiceCost3'], getSelectText(services[2]) ))
       return false;  
  }
  
  // Check that international destinations have been checked if international shipping services have been selected
  if (type == 'international')
  {
  	if (getSelectValue(services[0]) != 0 || getSelectValue(services[1]) != 0 || getSelectValue(services[1]) != 0)
  	{
  		if (!anyShipCountriesSelected())
  		{
  			alert(EBAY_NO_SHIP_COUNTRIES_SELECTED);
  			return false;
  		}
  	}
  }
  
  return true;
}

function ebaySubmitAddItem(form) {

   ebayPrepareToSubmit(form);
   if ( !ebayValidateForm(form) ) {
     ebayReenableForm(form);
     return false;
   }
   return true;   
}

function ebayValidateForm(form) {
   // ----------- //
   // ITEM BASICS //
   // ----------- //

   // check that we have a valid part number   
   try {
     var pnum = form['product.partNumber' ];
     if ( pnum.options[ pnum.selectedIndex ].value == "" ) {
        alert(EBAY_NO_PART_NUMBER_ERROR);
        showElement( document.getElementById('item_basics_content') );
        pnum.focus();
        return false;
     }
   } catch(e) {} // we use try catch in case pnum is not a select box
   
   // check that we have chosen category 1
   if ( form['product.category'].value == "" ) {
      alert(EBAY_NO_CATEGORY_ERROR);
      showElement( document.getElementById('item_basics_content') );
      document.getElementById('chooseCategory').focus();
      return false;      
   }
   
   // check that we have chosen a location
   var loc = form['product.locationId'];
   if ( loc.options[loc.selectedIndex].value == -1 ) {
      alert(EBAY_NO_LOCATION_ERROR);
      showElement( document.getElementById('item_basics_content') );
      loc.focus();
      return false;   
   }
   
   // -------------------- //
   // PRICING AND DURATION //
   // -------------------- //
   
   // check that the starting price is positive and an integer
   var stPrice = form['product.startingPrice'];
   if ( !isFloat( stPrice.value ) || ( parseFloat( stPrice.value ) <= 0 ) ) {
      alert(EBAY_NO_STARTING_PRICE_ERROR);
      showElement( document.getElementById('pricing_duration_content') );
      stPrice.focus();
      return false;
   }

   var listingMode = document.getElementById('listingMode');   
   // if reserve, check reserve > starting
   var reserve = form['product.reservePrice'];   
   if ( reserve && reserve.disabled == false ) {
     if (listingMode && listingMode.value == 'revise') {
        var curReservePrice = document.getElementById('curReservePrice');
        var within12HourOfTheEndOfAuction = document.getElementById('within12HourOfTheEndOfAuction');
        var bidCount = document.getElementById('bidCount');

        if (bidCount.value != '0' || within12HourOfTheEndOfAuction.value != 'false') {
          if (checkString(reserve)) {
            if ( !isFloat(reserve.value) ) {
               alert(EBAY_BAD_RESERVE_PRICE_ERROR);
               showElement( document.getElementById('pricing_duration_content') );
               reserve.focus();
               return false;
            } else if (parseFloat(reserve.value) <= parseFloat( stPrice.value )) {
               alert(EBAY_RESERVE_PRICE_TOO_LOW_ERROR);
               showElement( document.getElementById('pricing_duration_content') );
               reserve.focus();
               return false;
            } else if (parseFloat(reserve.value) > parseFloat(curReservePrice.value)) {
               alert(EBAY_RESERVE_PRICE_CANNOT_BE_INCREASED_ERROR + ' ($' + curReservePrice.value + ')');
               showElement( document.getElementById('pricing_duration_content') );
               reserve.focus();
               return false;
            }
          }
        } else if (isEmpty(reserve.value)) {
          ebayTempDisable( reserve );
        } else if ( !isFloat(reserve.value) ) {
           alert(EBAY_BAD_RESERVE_PRICE_ERROR);
           showElement( document.getElementById('pricing_duration_content') );
           reserve.focus();
           return false;
        } else if (parseFloat(reserve.value) <= parseFloat( stPrice.value )) {
           alert(EBAY_RESERVE_PRICE_TOO_LOW_ERROR);
           showElement( document.getElementById('pricing_duration_content') );
           reserve.focus();
           return false;      
        } else if (parseFloat(reserve.value) > parseFloat(curReservePrice.value)) {
           alert(EBAY_RESERVE_PRICE_CANNOT_BE_INCREASED_ERROR + ' ($' + curReservePrice.value + ')');
           showElement( document.getElementById('pricing_duration_content') );
           reserve.focus();
           return false;
        }
     } else if ( checkString( reserve ) ) {
        if ( !isFloat(reserve.value) ) {
           alert(EBAY_BAD_RESERVE_PRICE_ERROR);
           showElement( document.getElementById('pricing_duration_content') );
           reserve.focus();
           return false;
        } else if (parseFloat(reserve.value) <= parseFloat( stPrice.value )) {
           alert(EBAY_RESERVE_PRICE_TOO_LOW_ERROR);
           showElement( document.getElementById('pricing_duration_content') );
           reserve.focus();
           return false;      
        }
     }

     // if BIN, BIN > starting
     // if BIN && reserve, BIN > reserve   
     var BIN = form['product.buyItNowPrice'];
     if (listingMode && listingMode.value == 'revise') {
        var curBINPrice = document.getElementById('curBINPrice');
        var within12HourOfTheEndOfAuction = document.getElementById('within12HourOfTheEndOfAuction');
        var bidCount = document.getElementById('bidCount');

        if (bidCount.value == '0' || within12HourOfTheEndOfAuction.value == 'false') {
          if (!isEmpty(BIN.value)) {
            if (parseFloat(BIN.value) != parseFloat(curBINPrice.value)) {
               alert(EBAY_BIN_PRICE_CANNOT_BE_CHANGED_ERROR);
               showElement( document.getElementById('pricing_duration_content') );
               BIN.focus();
               return false;
            }
          } else {
            ebayTempDisable( BIN );
          }
        }
     } else if ( checkString( BIN ) ) {
        if ( !isFloat(BIN.value) ) {
           alert(EBAY_BAD_BUY_IT_NOW_PRICE_ERROR);
           showElement( document.getElementById('pricing_duration_content') );
           BIN.focus();
           return false;

        } else if ((parseFloat(BIN.value) <= parseFloat( stPrice.value )) ||
                  ( checkString(reserve) && 
                      (parseFloat(BIN.value) <= parseFloat( reserve.value )) )) {

           alert(EBAY_BUY_IT_NOW_PRICE_TOO_LOW_ERROR);
           showElement( document.getElementById('pricing_duration_content') );
           BIN.focus();
           return false;      
        }   
     }      
   }
   
   // -------- //
   // QUANTITY //
   // -------- //
   
   // check that the quantity is valid
   // and check the number of items per lots
   var quantity;
   if ( document.getElementById('quantityTypeLots').checked ) {
      quantity = document.getElementById('lotsQuantity');
   } else {
      quantity = document.getElementById('individualQuantity')   
   }
  
   if ( !isInteger( quantity.value ) || ( parseInt( quantity.value ) <= 0 ) ) {
      alert(EBAY_BAD_QUANTITY_ERROR);
      showElement( document.getElementById('quantity_content') );
      quantity.select();
      return false;
   }   
   
   if ( document.getElementById('quantityTypeLots').checked ) {
      var lots = form['product.itemsPerLot'];
      if ( !isInteger( lots.value ) || ( parseInt( lots.value ) <= 0 ) ) {
         alert(EBAY_BAD_LOTS_ERROR);
         showElement( document.getElementById('quantity_content') );
         lots.focus();
         return false;
      }
   }  
   
   // -------- //
   // SHIPPING //
   // -------- //
   
   var isShipping = form['product.shipping.isShippable'];
   if( isShipping[0].value && isShipping[0].checked ) {
     // validate shipping stuff     
      
      var flat = document.getElementById( 'flatShipping' ).checked;
      
      var domestic = new Array(3);
      var international = new Array(3);
      
      if ( flat ) {
         domestic[0] = document.getElementById('flatDomesticService1');
         domestic[1] = document.getElementById('flatDomesticService2');
         domestic[2] = document.getElementById('flatDomesticService3');
         international[0] = document.getElementById('flatInternationalService1');
         international[1] = document.getElementById('flatInternationalService2');
         international[2] = document.getElementById('flatInternationalService3');      
      } else {
         domestic[0] = document.getElementById('calculatedDomesticService1');
         domestic[1] = document.getElementById('calculatedDomesticService2');
         domestic[2] = document.getElementById('calculatedDomesticService3');
         international[0] = document.getElementById('calculatedInternationalService1');
         international[1] = document.getElementById('calculatedInternationalService2');
         international[2] = document.getElementById('calculatedInternationalService3');      
         
         // validate positive weight
         var lbs = form['product.shipping.estimateWeightLbs'];
         if ( !isInteger( lbs.value ) || ( parseInt( lbs.value ) < 0 ) ) {
            alert(EBAY_BAD_LBS_ERROR);                  
            showElement( document.getElementById('shipping_content') );
            lbs.select();
            return false;
         }
         
         var ozs = form['product.shipping.estimateWeightOz'];
         if ( !isInteger( ozs.value ) || ( parseInt( ozs.value ) < 0 ) ) {
            alert(EBAY_BAD_OZS_ERROR);                  
            showElement( document.getElementById('shipping_content') );
            ozs.select();
            return false;
         }
         
         if ( (parseInt( lbs.value ) == 0) &&
              (parseInt( ozs.value ) == 0) ) {
              
            alert(EBAY_ZERO_WEIGHT_ERROR);
            showElement( document.getElementById('shipping_content') );
            lbs.select();
            return false;
         }      
         
         // validate package dimensions
         var pSize = form['product.shipping.packageSize'];
         if ( pSize.value == 5 || pSize.value == 6 ) {
           if ( !isInteger( form['product.shipping.packageLength'].value ) ) {
              alert(EBAY_BAD_PACKAGE_DIMENSION_ERROR);
              showElement( document.getElementById('shipping_content') );
              form['product.shipping.packageLength'].focus();
              return false;
           }
           
           if ( !isInteger( form['product.shipping.packageWidth'].value ) ) {
             alert(EBAY_BAD_PACKAGE_DIMENSION_ERROR);
             showElement( document.getElementById('shipping_content') );
             form['product.shipping.packageWidth'].focus();
             return false;
           }
           
           if ( !isInteger( form['product.shipping.packageDepth'].value ) ) {
             alert(EBAY_BAD_PACKAGE_DIMENSION_ERROR);
             showElement( document.getElementById('shipping_content') );
             form['product.shipping.packageDepth'].focus();
             return false;
           }
         
           var dims = new Array(3);
           dims[0] = form['product.shipping.packageLength'];
           dims[1] = form['product.shipping.packageWidth'];
           dims[2] = form['product.shipping.packageDepth'];
         
           dims.sort( function(a,b) {return a.value - b.value;} );
           
           if ( parseInt(dims[0].value) <= 0 ) {
              alert(EBAY_BAD_PACKAGE_DIMENSION_ERROR);
              showElement( document.getElementById('shipping_content') );
              dims[0].focus();
              return false;
           }
           
           var measure = (parseInt(dims[0].value) + parseInt(dims[1].value))*2 + parseInt(dims[2].value);
           if ( measure < 84 ) {
              if ( confirm(EBAY_PACKAGE_NOT_OVERSIZE_CONFIRM) ) {
                 pSize.value = 4;
                 changePackageType(pSize);
              } else {
                 showElement( document.getElementById('shipping_content') );
                 return false;
              }
           
           } else if ( measure < 108 ) {
              if ( pSize.value == 6 ) {
                 if ( confirm(EBAY_PACKAGE_NOT_OVERSIZE2_CONFIRM) ) {
                    pSize.value = 5;
                    changePackageType(pSize);
                 } else {
                    showElement( document.getElementById('shipping_content') );
                    return false;
                 }
              }           
           } else if ( measure < 130 ) {
              if ( pSize.value == 5 ) {
                 alert(EBAY_PACKAGE_VERY_LARGE_ERROR);
                 showElement( document.getElementById('shipping_content') );
                 form['product.shipping.packageSize'].focus();
                 return false;              
              }           
           } else {
              alert(EBAY_PACKAGE_TOO_BIG_ERROR);
              showElement( document.getElementById('shipping_content') );
              form['product.shipping.packageLength'].focus();
              return false;           
           }
         }
         
         if ( pSize.value == 5 || pSize.value == 6 ) {
           // check for irregular
           if ( parseInt(dims[1].value) > 30 || parseInt(dims[2].value) > 60 ) {
             if ( !form['product.shipping.irregularlyShapped'].checked ) {
                if ( confirm(EBAY_PACKAGE_IS_IRREGULAR_CONFIRM) ) {
                   form['product.shipping.irregularlyShapped'].checked = true;
                } else {
                   showElement( document.getElementById('shipping_content') );
                   form['product.shipping.packageLength'].focus();
                   return false;                            
                }
             }
           }
         } else {
           form['product.shipping.packageLength'].disabled = true;
           form['product.shipping.packageWidth'].disabled = true;
           form['product.shipping.packageDepth'].disabled = true;
         }         
         
         // validate handling cost      
         var hCost = form['product.shipping.packageHandlingCost'];
         if ( !isFloat( hCost.value ) || ( parseFloat( hCost.value ) < 0 ) ) {
            alert(EBAY_BAD_HANDLING_COST_ERROR);
            showElement( document.getElementById('shipping_content') );
            hCost.select();
            return false;         
         }

      }
      
      if (!ebayValidateServiceSet(form, domestic, 'domestic', flat, EBAY_NO_DOMESTIC_ERROR))
         return false;
         
      if (!ebayValidateServiceSet(form, international, 'international', flat, 
           anyShipCountriesSelected() ? EBAY_NO_INTERNATIONAL_ERROR : false))
         return false;
         
      // check countries regarding canada - UPS to canada does not count
                 // for shipment worldwide unless only country is Canada          
         
      if ( getSelectValue(international[0]) == 50013 ) {      
         checkCanada( international[0] );
         if ( getSelectValue(international[1]) == 0 &&
              anyShipCountriesBesidesCanadaSelected() ) {
            alert(EBAY_NO_NONCANADA_ERROR);
            showElement( document.getElementById('shipping_content') );
            international[1].focus(); 
            return false;            
         }      
      }
      
      checkCanada( international[1] );
      checkCanada( international[2] );
      
      if ( flat ) {
         // shipping insurance - positive price if applicable
         var insuranceOption = document.getElementById('flatInsuranceOption');
         if (( insuranceOption.selectedIndex == 1 || insuranceOption.selectedIndex == 2 )
             && !ebayValidateShipPrice(form['product.shipping.shippingInsuranceFee'], 'shipping insurance'))
         {
            return false;
         }
           
      }
   }
      
   // validate sales tax field ( positive if enabled )
   if ( getSelectValue(form['product.shipping.stateToTax']) != 'none' ) {
      if ( !isFloat( form['product.shipping.salesTaxPercentage'].value ) ||
           ( parseFloat( form['product.shipping.salesTaxPercentage'].value ) <= 0 ) ) 
      {
         alert(EBAY_BAD_SALES_TAX_ERROR);

         showElement( document.getElementById('shipping_content') );
         if (!isElementShown(form['product.shipping.salesTaxPercentage']))
            showElement( form['product.shipping.salesTaxPercentage'] );         
         form['product.shipping.salesTaxPercentage'].select();
         
         return false;      
      }
           
   }
   
   // ------- //   
   // PAYMENT //
   // ------- //
   
   if (!anyPaymentMethodsSelected()) {
      alert(EBAY_NO_PAYMENT_ERROR);
      showElement( document.getElementById('payment_content') );      
      return false;
   }
   
   // if paypal - email
   if ( form['product.payment.payPalAccepted'].checked &&
        !isEmail(form['product.payment.payPalEmail'].value) )
   {
      alert(EBAY_NO_PAYPAL_EMAIL_ERROR);
      showElement( document.getElementById('payment_content') );      
      form['product.payment.payPalEmail'].select();
      return false;
   }      
      
   return true;
}

function ebayPrepareToSubmit(form) {
   var formElements = form.elements;
   var isIndividualQtyType = isShown('type_individual_label');

   for(var i = 0; formElements[i]; i++)
   {
   	   // Make sure that quantities of the opposite type selected remain disabled and are not submitted.
   	   if (isIndividualQtyType)
   	   {
   	     if (formElements[i].id == 'lotsQuantity' || 
   	         formElements[i].id == 'lotsSize')
   	     {
   	       continue;
   	     }
   	   }
   	   else 
   	   {
   	   	 if (formElements[i].id == 'individualQuantity')
   	   	 {
   	       continue;
   	     }
   	   }

       if(formElements[i].disabled == true)
       {
          ebayTempEnable( formElements[i] );
       }
   }

   if ( document.getElementById( 'flatShipping' ).checked ) {
      // disable calculated      
      ebayTempDisable( document.getElementById( 'calculatedDomesticService1' ) );
      ebayTempDisable( document.getElementById( 'calculatedDomesticService2' ) );
      ebayTempDisable( document.getElementById( 'calculatedDomesticService3' ) );
      ebayTempDisable( document.getElementById( 'calculatedInternationalService1' ) );
      ebayTempDisable( document.getElementById( 'calculatedInternationalService2' ) );
      ebayTempDisable( document.getElementById( 'calculatedInternationalService3' ) );
      ebayTempDisable( document.getElementById( 'calculatedInsuranceOption' ) );
   } else {
      // disable flat
      ebayTempDisable( document.getElementById( 'flatDomesticService1' ) );
      ebayTempDisable( document.getElementById( 'flatDomesticService2' ) );
      ebayTempDisable( document.getElementById( 'flatDomesticService3' ) );
      ebayTempDisable( document.getElementById( 'flatInternationalService1' ) );
      ebayTempDisable( document.getElementById( 'flatInternationalService2' ) );
      ebayTempDisable( document.getElementById( 'flatInternationalService3' ) );
      ebayTempDisable( document.getElementById( 'flatInsuranceOption' ) );
   }
   
   return true;
}

function ebayTempEnable( elem ) {
   elem.disabled = false;
   elem.tempEnabled = true;
}

function ebayTempDisable( elem ) {
   elem.disabled = true;
   elem.tempDisabled = true;;
}

function ebayReenableForm(form) {
   var formElements = form.elements;
   
   for(var i = 0; formElements[i]; i++)
   {
       if(formElements[i].tempEnabled == true)
       {
         formElements[i].disabled = true;
         formElements[i].tempEnabled = null;
         
       } else if ( formElements[i].tempDisabled == true ) {
         formElements[i].disabled = false;
         formElements[i].tempDisabled = null;
       }
   }
   
   return true;
}

function anyPaymentMethodsSelected() {
   var form = document.forms['APIForm'];
   return ( form['product.payment.payPalAccepted'].checked ||
            form['product.payment.moneyOrderAccepted'].checked ||
            form['product.payment.personalCheckAccepted'].checked ||
            form['product.payment.visaAccepted'].checked ||
            form['product.payment.discoverAccepted'].checked ||
            form['product.payment.amExAccepted'].checked );
} 


/*******************************************************/
/*          Shipping on the listing form               */
/*******************************************************/

function ebayEnableShipping(rowCount) {
   var i;
   for ( i = 0; i < rowCount; i++ ) {
      shipShowElementWithId( "shippingRow" + i );
   }
   hideElementWithId( "shippingDisabled" );
}

function ebayDisableShipping(rowCount) {
   var i;
   for ( i = 0; i < rowCount; i++ ) {
      hideElementWithId( "shippingRow" + i );
   }
   showElementWithId( "shippingDisabled" );
}

function shipShowElementWithId(id, level) {
   if (!level)
      level = 1;
      
   var elem = document.getElementById( id );
   if (elem) {
     if ( !elem.shipHidden || elem.shipHidden < level ) {
        showElement(elem);             
     }
   }   
}

function shipWorldwide(prefix) {
   var form = document.forms['APIForm'];
   if ( form['product.shipping.shippableWorldwide'].checked ) {
     form['product.shipping.shippableToAmericas'].checked = true;
     form['product.shipping.shippableToAustralia'].checked = true;
     form['product.shipping.shippableToAsia'].checked = true;
     form['product.shipping.shippableToGermany'].checked = true;
     form['product.shipping.shippableToMexico'].checked = true;
     form['product.shipping.shippableToJapan'].checked = true;
     form['product.shipping.shippableToUnitedKingdom'].checked = true;
     form['product.shipping.shippableToCanada'].checked = true;
     form['product.shipping.shippableToEurope'].checked = true;
   } else {
     form['product.shipping.shippableToAmericas'].checked = false;
     form['product.shipping.shippableToAustralia'].checked = false;
     form['product.shipping.shippableToAsia'].checked = false;
     form['product.shipping.shippableToGermany'].checked = false;
     form['product.shipping.shippableToMexico'].checked = false;
     form['product.shipping.shippableToJapan'].checked = false;
     form['product.shipping.shippableToUnitedKingdom'].checked = false;
     form['product.shipping.shippableToCanada'].checked = false;
     form['product.shipping.shippableToEurope'].checked = false;
   }
}

function shipClick(prefix) {
   var form = document.forms['APIForm'];
   if ( form['product.shipping.shippableToAmericas'].checked &&
        form['product.shipping.shippableToAustralia'].checked &&
        form['product.shipping.shippableToAsia'].checked &&
        form['product.shipping.shippableToGermany'].checked &&
        form['product.shipping.shippableToMexico'].checked &&
        form['product.shipping.shippableToJapan'].checked &&
        form['product.shipping.shippableToUnitedKingdom'].checked &&
        form['product.shipping.shippableToCanada'].checked &&     
        form['product.shipping.shippableToEurope'].checked )
   {
     form['product.shipping.shippableWorldwide'].checked = true;
   } else {
     form['product.shipping.shippableWorldwide'].checked = false;
   }
}

function anyShipCountriesSelected() {
   var form = document.forms['APIForm'];
   return ( form['product.shipping.shippableToAmericas'].checked ||
            form['product.shipping.shippableToAustralia'].checked ||
            form['product.shipping.shippableToAsia'].checked ||
            form['product.shipping.shippableToGermany'].checked ||
            form['product.shipping.shippableToMexico'].checked ||
            form['product.shipping.shippableToJapan'].checked ||
            form['product.shipping.shippableToUnitedKingdom'].checked ||
            form['product.shipping.shippableToCanada'].checked ||     
            form['product.shipping.shippableToEurope'].checked );
}

function anyShipCountriesBesidesCanadaSelected() {
   var form = document.forms['APIForm'];
   return ( form['product.shipping.shippableToAmericas'].checked ||
            form['product.shipping.shippableToAustralia'].checked ||
            form['product.shipping.shippableToAsia'].checked ||
            form['product.shipping.shippableToGermany'].checked ||
            form['product.shipping.shippableToMexico'].checked ||
            form['product.shipping.shippableToJapan'].checked ||
            form['product.shipping.shippableToUnitedKingdom'].checked ||
            form['product.shipping.shippableToEurope'].checked );
}

function selectShippingType(type) {
   // type is 1 for flat, 2 for calc
   var start = type * 20 - 10;
   var end = start + 20;
   var i;
   for ( i = start; i < end; i++ ) {
      var elem = document.getElementById( "shippingRow" + i );
      if (elem && (!elem.shipHidden || elem.shipHidden < 2) ) {
        showElement( elem );
        elem.shipHidden = 0;
      }
   }
   var start = (3-type) * 20 - 10;
   var end = start + 20;
   for ( i = start; i < end; i++ ) {
      var elem = document.getElementById( "shippingRow" + i );
      if (elem && elem.shipHidden != 2) {
        hideElement( elem );
        elem.shipHidden = 1;
      }
   }   
}

function changeFlatService(type, num) {
  var shippingService = document.getElementById('flat' + type + 'Service' + num);
  if ( shippingService.selectedIndex != 0 ) {
    showElementWithId( 'flat' + type + num );
  } else {
    hideElementWithId( 'flat' + type + num );   
  }
}

/*function changeCalculatedInternationalService(num) {
   var form = document.forms['APIForm'];
   
   if ( form['calculatedInternationalShippingServiceOption[' + (num - 1) +'].ShippingService'].selectedIndex > 0 ) {
     showElementWithId( 'calculatedInternationalTo' + num );
   
   } else {
     hideElementWithId( 'calculatedInternationalTo' + num );   
   }
}
*/

function shipInsurance(type) {
  var insuranceOption = document.getElementById('flatInsuranceOption');
   if ( insuranceOption.selectedIndex == 1 || insuranceOption.selectedIndex == 2 ) {
     showElementWithId( type + 'Insurance' );
   } else {
     hideElementWithId( type + 'Insurance' );   
   }
}

function changeSalesTax() {
    var stateToTax = document.getElementById('stateToTax');
  
   if ( stateToTax.selectedIndex != 0 ) {
     showElementWithId( 'salesTax0' );
     showElementWithId( 'salesTax1' );
     showElementWithId( 'salesTax2' );
   } else {
     hideElementWithId( 'salesTax0' );
     hideElementWithId( 'salesTax1' );
     hideElementWithId( 'salesTax2' );
   }
}

// This functionality is based on the chart at
// http://pages.ebay.com/help/sell/ship-calc-package.html
ebayCalculatedServicesClone = new Object;
ebayCalculatedServicesClone['Domestic'] = null;
ebayCalculatedServicesClone['International'] = null;

function changePackageType(element) {
   internalChangePackageType(element, 'Domestic');
   internalChangePackageType(element, 'International');
   
   var form = document.forms['APIForm'];

   // determine whether to show the dimensions row
   var newVal = element.options[element.selectedIndex].value;
   var elem = document.getElementById( 'shippingRow45' );
   if ( newVal == 5 || newVal == 6 ) {
      elem.shipHidden = 0;
      showElement( elem );      
   
   // enabled the fields
      form['product.shipping.packageLength'].disabled = false;
      form['product.shipping.packageWidth'].disabled = false;
      form['product.shipping.packageDepth'].disabled = false;
      
      // insert the default value, if possible
      if ((!form['product.shipping.packageDimensionsSet'].value ||
           (form['product.shipping.packageDimensionsSet'].value == '0')
          ) ||
           ( !checkString( form['product.shipping.packageLength'] ) &&
             !checkString( form['product.shipping.packageWidth'] ) &&
             !checkString( form['product.shipping.packageDepth'] ) ))
      {
         var dim = element.options[element.selectedIndex].defaultDimension;
         form['product.shipping.packageLength'].value = dim;
         form['product.shipping.packageWidth'].value = dim;
         form['product.shipping.packageDepth'].value = dim;         
      }
            
   } else {
      hideElement( elem );
      elem.shipHidden = 2;
      
      // disable the fields
      form['product.shipping.packageLength'].disabled = true;
      form['product.shipping.packageWidth'].disabled = true;
      form['product.shipping.packageDepth'].disabled = true;
   }
}   

function changePackageDim() {
   var form = document.forms['APIForm'];
   form['product.shipping.packageDimensionsSet'].value = 1;
}

function internalChangePackageType(element, type) {
   var newMask = element.options[element.selectedIndex].mask;

   var services = new Array(3);
   services[0] = document.getElementById( 'calculated' + type + 'Service1' );
   services[1] = document.getElementById( 'calculated' + type + 'Service2' );
   services[2] = document.getElementById( 'calculated' + type + 'Service3' );

   if ( ebayCalculatedServicesClone[type] == null ) {
      ebayCalculatedServicesClone[type] = services[0].cloneNode(true);
   }
   
   var i;
   for ( i = 0; i < 3; i++ ) {  
     var temp = ebayCalculatedServicesClone[type].cloneNode(true);    
     
     temp.onChange = "changePackageType(this, 'domestic');";
     temp.id = 'calculated' + type + 'Service' + (i+1);
     temp.name = 'product.shipping.' + type.toLowerCase() + 'Service' + (i+1);
     
     var val = services[i].options[ services[i].selectedIndex ].value;     
     
     var removals = new Array();
     
     var j;
     for ( j = 0; j < temp.options.length; j++ ) {
        var opt = temp.options[j];
        if (!( opt.mask & newMask )) {
           removals.unshift( j );        
        }
     }
     
     for ( j = 0; j < removals.length; j++ ) {
        temp.remove( removals[j] );
     }
     
     temp.selectedIndex = 0;
     for ( j = 0; j < temp.options.length; j++ ) {
        if ( temp.options[j].value == val ) {
           temp.selectedIndex = j;
           break;
        }
     }
         
     services[i].parentNode.replaceChild( temp, services[i] );     
   }   

   return true;
}

function checkCanada( elem ) {
   if ( elem.options[ elem.selectedIndex ].value == 50013 ) {
      // the user has selected UPS Standard to Canada
      if (! document.getElementById('shippableToCanada').checked) {
         alert('Because you have selected \'UPS Standard to Canada\', Canada has been enabled in your ship-to locations.');
         document.getElementById('shippableToCanada').checked = true;
      }   
   }
}

/*******************************************************/
/*         Validation for the location form            */
/*******************************************************/

EBAY_LOCATION_BLANK_ERROR = "Please enter a name for this location.";
EBAY_LOCATION_BAD_ZIP_ERROR = "Please enter a valid zip code.";

function validateEbayLocationForm(form) {
  if ( !checkString( form['location.location'] ) ) {
    alert( EBAY_LOCATION_BLANK_ERROR );
    form['location.location'].focus();
    return false;
  }
  
  if (! isZIPCode( form['location.zipCode'].value ) ) {
    alert( EBAY_LOCATION_BAD_ZIP_ERROR );
    form['location.zipCode'].focus();
    return false;
  }
}


/**********************************************************/
/*        Prompt for removal of eBay account              */
/**********************************************************/

function removeAccountPrompt(){
	EBAY_ACCOUNT_REMOVAL_PROMPT = "Are you sure you want to remove your eBay account information from your Storefront?";
	if(confirm(EBAY_ACCOUNT_REMOVAL_PROMPT)){
		return true;
	}
	else{
	    return false;
	}
}
var errorPrefix = "You did not enter a value into the "
var errorSuffix = " field. This is a required field. Please enter it now."

var labelErrorMsg = errorPrefix + "Label" + errorSuffix;
var manufacturerNameErrorMsg = errorPrefix + "Manufacturer Name" + errorSuffix;
var sortOrderErrorMsg = errorPrefix + "Sort Order" + errorSuffix;
var searchableErrorMsg = errorPrefix + "Searchable" + errorSuffix;


var categoryNameErrorMsg = errorPrefix + "Name" + errorSuffix;
var categoryLabelErrorMsg = errorPrefix + "Label" + errorSuffix;

var upsRegistrationContactNameErrorMsg = errorPrefix + "Contact Name" + errorSuffix;
var upsRegistrationTitleErrorMsg = errorPrefix + "Title" + errorSuffix;
var upsRegistrationCompanyNameErrorMsg = errorPrefix + "Company Name" + errorSuffix;
var upsRegistrationStreetAddressErrorMsg = errorPrefix + "Street Address" + errorSuffix;
var upsRegistrationCityErrorMsg = errorPrefix + "City" + errorSuffix;
var upsRegistrationStateErrorMsg = errorPrefix + "State" + errorSuffix;
var upsRegistrationCountryErrorMsg = errorPrefix + "Country" + errorSuffix;
var upsRegistrationPostalCodeErrorMsg = errorPrefix + "Postal Code" + errorSuffix;
var upsRegistrationPhoneNumberErrorMsg = errorPrefix + "Phone Number" + errorSuffix;
var upsRegistrationWebSiteURLErrorMsg = errorPrefix + " Web Site URL" + errorSuffix;
var upsRegistrationEmailAddressErrorMsg = errorPrefix + "Email Address" + errorSuffix;


var manufacturerErrorMsg = errorPrefix + "Part Number (SKU)" + errorSuffix;
var partNumberErrorMsg = errorPrefix + "Part Number (SKU)" + errorSuffix;
var partNumberExistsErrorMsg = "The value you entered for Part Number (SKU) has already been used by another product.";
var titleErrorMsg = errorPrefix + "Title" + errorSuffix;
var shortDescriptionErrorMsg = errorPrefix + "Short Description" + errorSuffix;
var fullDescriptionErrorMsg = errorPrefix + "Full Description" + errorSuffix;
var vatErrorMsg = errorPrefix + "VAT Tax Percentage" + errorSuffix;
var featuredProductErrorMsg = errorPrefix + "Featured" + errorSuffix;
var discontinuedErrorMsg = errorPrefix + "Discontinued" + errorSuffix;
var inventoriedErrorMsg = errorPrefix + "Inventoried" + errorSuffix;
var backordableErrorMsg = errorPrefix + "Allow Backorder" + errorSuffix;
var quantityErrorMsg = "You must specify a whole number quantity in stock for all inventoried products.";
var negativeQuantityErrorMsg = "Only backorderable products can have a negative quantity in stock.";
var thresholdErrorMsg = "Please enter a whole number in the 'Email Me When Stock Is' field that represents when you want to be notified of low inventory";
var negativeThresholdErrorMsg = "Only backorderable products can have a negative 'Email Me When Stock Is' value.";
var weightErrorMsg = "You have entered an invalid shipping weight.  \nThe weight must be a positive number.";

var weightErrorMsg = "You have entered an invalid shipping weight.  \nThe weight must be a positive number.";
var lengthErrorMsg = "You have entered an invalid shipping length.  \nThe weight must be a positive number.";
var widthErrorMsg = "You have entered an invalid shipping width.  \nThe weight must be a positive number.";
var heightErrorMsg = "You have entered an invalid shipping height.  \nThe weight must be a positive number.";

var productTypeErrorMsg = errorPrefix + "Product Type" + errorSuffix;
var digitalDataErrorMsg = "You must specify the file to download when customers purchase this downloadable product";

var invalidDurationErrorMsg = "Please specify a positive integer representing the number of days a customer can download this product after purchase.";
var invalidNumberOfDownloadsErrorMsg = "Please specify a positive integer representing the number of times a customer can download this product after purchase.";

var toFewProductsInBundleErrorMsg = "You must specify at least 2 products, \nor one product with a quantity of 2, \nto bundle together to create this product.";
var bundleQtyErrorMsg = "You must specify a whole number quantity to bundle";
var listPriceErrorMsg = "You have specified a price of $0.00 or less for this product.  Are you sure you want to do this?";
var categoryErrorMessage = "You have not specified any categories this product resides in.  \n If you continue it may not display correctly on the storefront.  \n Are you sure you want to save this product without being in any categories?";

var invalidCostErrorMsg = "Your cost must be a decimal value.";
var invalidPriceErrorMsg = "Prices must be decimal values";
var warnNegativePriceMsg = "You are about to save a product with a negative selling price. \nAre you SURE you want to continue?";
var warnZeroPriceMsg = "You are about to save a product with a zero selling price. \nAre you SURE you want to continue?";
var warnZeroDiscountMsg = "You are about to save a product with a zero discount. \nAre you SURE you want to continue?";
var warnNotDiscounted = "You are about to sell a product with a sale price higher than the advertised price. \nAre you SURE you want to continue?";

var strongPasswordErrorMsg = "Passwords must contain at least 7 characters and comprise at least one letter and one number. Passwords are case sensitive.";
var confirmPasswordErrorMsg = "Your password and confirm password fields must match."
var optionPricingConfirmation = "At least one combination of list price, sale price and option decrements\n" +
                                "results in an adjusted price less than or equals to $0.00. If this\n" +
                                "combination of price and options is selected by the shopper, the price\n" +
                                "at checkout will be $0.00.";

function validateEditAttributeForm(formElement)
{
  var formElements = formElement.elements;
  for(var i = 0; i < formElements.length; i++)
  {
    if(formElements[i].name == "attribute.label" && !checkString(formElements[i]))
    {
      warnInvalid(formElements[i], labelErrorMsg);
      return false;
    }
    else if(formElements[i].name == "attribute.sortOrder" && !checkString(formElements[i]))
    {
      warnInvalid(formElements[i], sortOrderErrorMsg);
      return false;
    }
  }
  if(!checkSelection(formElement, "attribute.searchable"))
  {
    warnInvalid(formElements[i], searchableErrorMsg);
    return false;
  }
}

function validateEditManufacturerForm(formElement)
{
  var formElements = formElement.elements;
  for(var i = 0; i < formElements.length; i++)
  {
    if(formElements[i].name == "manufacturer.name" && !checkString(formElements[i]))
    {
      warnInvalid(formElements[i], manufacturerNameErrorMsg);
      return false;
    }
  }
}


function validateEditCategoryForm(formElement)
{
  var formElements = formElement.elements;

  for(var i = 0; formElements[i]; i++)
  {
    if(formElements[i].name == "category.label")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], categoryNameErrorMsg);
  return false;
      }
    }
  }

  return true;
}



function validateUPSRegistration(formElement)
{
  var formElements = formElement.elements;

  var i = 0;

  for(var i = 0; formElements[i]; i++)
  {
    if(formElements[i].name == "UPSRegistrationInfo.contactName")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationContactNameErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.title")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationTitleErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.companyName")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationCompanyNameErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.streetAddress")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationStreetAddressErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.city")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationCityErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.state")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationStateErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.country")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationCountryErrorMsg);
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.postalCode")
    {
      if(formElements[i-1].value == "US" || formElements[i-1].value == "CA")
      {
        if(!checkString(formElements[i]))
        {
    warnInvalid(formElements[i], upsRegistrationPostalCodeErrorMsg);
    return false;
        }
        else if(formElements[i-1].value == "US" && !isZIPCode(formElements[i].value))
        {
          warnInvalid(formElements[i], "The Postal Code must contain 5 or 9 digits. Please enter it now.");
    return false;
        }
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.phoneNumber")
    {
      if(!checkString(formElements[i]))
      {
  warnInvalid(formElements[i], upsRegistrationPhoneNumberErrorMsg);
  return false;
      }
      else if(!isInteger(formElements[i].value))
      {
        warnInvalid(formElements[i], "The Phone Number must contain digits (0-9) only. Please enter it now.");
  return false;
      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.webSiteURL")
    {
      var versionRegExp = new RegExp("^(http://|https://|)((www|shop|xn\\-\\-[-a-zA-Z0-9]+)\\.(.+))");      
      var result = versionRegExp.exec(formElements[i].value);
      if(!result || result.length < 3 || result[0].length != formElements[i].value.length)
      {
        warnInvalid(formElements[i], "Domain name must start with www or shop.");
        return false;
      }
      else
      {
        return validateDomainName(result[2]);
      }
//      if(!checkWebURL(formElements[i]))
//      {
//  return false;
//      }
    }
    else if(formElements[i].name == "UPSRegistrationInfo.emailAddress")
    {
      if(!checkEmail(formElements[i]))
      {
  return false;
      }
    }
  }

  return true;
}

function validateShippingConfig(formElement)
{
  var formElements = formElement.elements;

  var handlingFee = formElements["thirdPartyShippingBean.attributes(handlingFee)"];
  if(handlingFee != null)
  {
  	if (handlingFee.value == ""){} // do nothing, let the backend convert this to 0.00
    else if(!isSignedFloat(handlingFee.value))
    {
      warnInvalid(handlingFee, 'Please specify a valid handling fee.');
      return false;
    }
    else if(parseFloat(handlingFee.value) < 0)
    {
      warnInvalid(handlingFee, 'Handling Fee must be a positive value.');
      return false;
    }
  }
  
  var shipperPostalCode = formElements["thirdPartyShippingBean.attributes(shipperPostalCode)"];
  if(shipperPostalCode != null)
  {
    if (!isZIPCode(shipperPostalCode.value))
    {
      warnInvalid(shipperPostalCode, 'Please specify a valid postal code.');
      return false;
    }
  }

  // If Multi-Item packaging is enabled, warn if no shipping boxes were defined or none are active.
  var packMethod = getRadioButtonValue(document.getElementsByName("thirdPartyShippingBean.attributes(packMethod)"));
  if (packMethod == "same")
  {
    var shippingBoxTable = document.getElementById("shippingBoxTable");
    if (!shippingBoxTable)
    {
      return true;
    }

    var chks = shippingBoxTable.getElementsByTagName("input");
    if (chks)
    {
      var foundCheck = false, foundActive = false;
      for (var i = 0; i < chks.length; i++)
      {
        if (chks[i].type == "checkbox")
        {
          foundCheck = true;
          if (chks[i].checked == true)
          {
            foundActive = true;
          }
        }
      }

      if (!(foundCheck && foundActive))
      {
        var warning = "You have specified that multiple products ship in the same package, but no active shipping boxes have been defined." +
              "\nEach product will ship in its own box until at least one active shipping box is defined." +
              "\n\nClick 'OK' to save the configuration or 'Cancel' to edit it.";
        if (!confirm(warning))
        {
          return false;
        }
      }
    }
  }

  return true;
}



function validateProductTab(formElement, appHost, group)
{
  var formElements = formElement.elements;
  var isInventoriedProduct = document.getElementById('inventoryYes').checked;
  var isShippableProduct =document.getElementById('shippingYes').checked;
  var isDownloadableProduct = document.getElementById('productTypeDigital').checked;
  var isBundleProduct = document.getElementById('productTypeBundle').checked;
  var numItemsInBundle = 0;

  var i = 0;

  for(var i = 0; formElements[i]; i++)
  {
    if(formElements[i].name == "product.chars.manufacturerId")
    {
      if(!checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], manufacturerErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.partNumber")
    {
      if(!checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], partNumberErrorMsg);
        return false;
      }

      if(!formElement['originalPartNumber'] || (formElements[i].value != formElement['originalPartNumber'].value))
      {
        checkFound( formElement, group,
                   appHost + 'checkProductSKU.hg?sku=' + escape( formElements[i].value ) + '&productId=' + formElement['product.productId'].value,
                   partNumberExistsErrorMsg );
      }
    }
    else if(formElements[i].name == "product.chars.label")
    {
      if(!checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], titleErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.shortDescription")
    {
      if(!checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], shortDescriptionErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.longDescription")
    {
      if(!checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], fullDescriptionErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.vatPercentage")
    {
      if(!checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], vatErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.quantity")
    {
      if(isInventoriedProduct)
      {
        var isBackorderable = document.getElementById('backorderableYes').checked;

        if(!checkString(formElements[i]) || !isSignedInteger(formElements[i].value))
        {
        rollOpenSection('product', 50);
          warnInvalid(formElements[i], quantityErrorMsg);
          return false;
        }
        else if(!isBackorderable && isNegativeInteger(formElements[i].value))
        {
          rollOpenSection('product', 50);
          warnInvalid(formElements[i], negativeQuantityErrorMsg);
          return false;
        }
      }
    }
    else if(formElements[i].name == "product.chars.threshold")
    {
      if(isInventoriedProduct && !isSignedInteger(formElements[i].value))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], thresholdErrorMsg);
        return false;
      }
      else if(!isBackorderable && isNegativeInteger(formElements[i].value))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], negativeThresholdErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.weight")
    {
      if(isShippableProduct && !isPositiveFloat(formElements[i].value))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], weightErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.length")
    {
      if(isShippableProduct && !isPositiveFloat(formElements[i].value))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], lengthErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.width")
    {
      if(isShippableProduct && !isPositiveFloat(formElements[i].value))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], widthErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "product.chars.height")
    {
      if(isShippableProduct && !isPositiveFloat(formElements[i].value))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], heightErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "digitalProductData")
    {
      if(isDownloadableProduct && !document.getElementById("digitalDataId") && !checkString(formElements[i]))
      {
        rollOpenSection('product', 50);
        warnInvalid(formElements[i], digitalDataErrorMsg);
        return false;
      }
    }
    else if(formElements[i].name == "downloadDuration" &&
      document.getElementById('restrictDownloadDurationValue').checked && !isPositiveInteger(formElements[i].value))
    {
      rollOpenSection('product', 50);
      warnInvalid(formElements[i], invalidDurationErrorMsg);
      return false;
    }
    else if(formElements[i].name == "maxDownloads" &&
      document.getElementById('restrictMaxDownloadsValue').checked && !isPositiveInteger(formElements[i].value))
    {
      rollOpenSection('product', 50);
      warnInvalid(formElements[i], invalidNumberOfDownloadsErrorMsg);
      return false;
    }
    else if(isBundleProduct && formElements[i].name.indexOf("bundleItems[") == 0)
    {
      if(formElements[i].name.indexOf(".packagedQty") > 0)
      {
        if(isBundleProduct && !isPositiveInteger(formElements[i].value))
        {
          rollOpenSection('product', 50);
          warnInvalid(formElements[i], bundleQtyErrorMsg);
          return false;
        }
        else
        {
          numItemsInBundle += parseInt(formElements[i].value);
        }
      }
    }
  }

  if(isBundleProduct && numItemsInBundle < 2)
  {
    rollOpenSection('product', 50);
    alert(toFewProductsInBundleErrorMsg);
    return false;
  }
  return true;
}

function validatePricingTab(formElement)
{
  var formElements = formElement.elements;
  var hasZeroDiscount = false;

  for(var i = 0; formElements[i]; i++)
  {
    if (formElements[i].name.indexOf("percentDiscount_", 0)) {
      hasZeroDiscount = parseFloat(formElements[i].value) == "0";
    }
    if(formElements[i].name == "product.chars.cost" && !isFloat(formElements[i].value))
    {
      if(!isSignedFloat(formElements[i].value))
      {
        rollOpenSection('pricing', 50);
        warnInvalid(formElements[i], invalidCostErrorMsg);
        return false;
      }
      else if(parseFloat(formElements[i].value) < 0)
      {
        rollOpenSection('pricing', 50);
        formElements[i].focus();
        formElements[i].select();
        alert("You may not save a product with a negative selling price");
        return false;
      }
    }

    else if(formElements[i].name.indexOf("product.pricing[") == 0)
    {
      //make sure it ends with price
      if(formElements[i].name.indexOf(".price") == formElements[i].name.length - ".price".length)
      {
        if(!isSignedFloat(formElements[i].value))
        {
          rollOpenSection('pricing', 50);
          warnInvalid(formElements[i], invalidPriceErrorMsg);
          return false;
        }
        else if(parseFloat(formElements[i].value) < 0)
        {
          rollOpenSection('pricing', 50);
          formElements[i].focus();
          formElements[i].select();
          alert("You may not save a product with a negative selling price");
          return false;
        }
      }
      else if(formElements[i].name.indexOf("startDateByString") > 0)
      {
        var startDate = new Date(formElements[i].value);
        var dateRegExp = new RegExp("^\\d?\\d/\\d?\\d/\\d\\d\\d\\d$");

        if (isNaN(startDate) || !dateRegExp.test(formElements[i].value))
        {
          formElements[i].focus();
          formElements[i].select();
          warnInvalid(formElements[i], "Price start date is invalid.  Please use the format MM/DD/YYYY.");
          return false;
        }
      }
      else if(formElements[i].name.indexOf("endDateByString") > 0 &&
              formElements[i].value != '')
      {
        var endDate = new Date(formElements[i].value);
        var dateRegExp = new RegExp("^\\d?\\d/\\d?\\d/\\d\\d\\d\\d$");

        if (isNaN(endDate) || !dateRegExp.test(formElements[i].value))
        {
          formElements[i].focus();
          formElements[i].select();
          warnInvalid(formElements[i], "Price end date is invalid.  Please use the format MM/DD/YYYY.");
          return false;
        }

      }
    }
    else if(formElements[i].name.indexOf("percentDiscount") == 0 && parseFloat(formElements[i].value) < 0)
    {
      rollOpenSection('pricing', 50);
      formElements[i].focus();
      formElements[i].select();
      if(!confirm(warnNotDiscounted))
      {
        return false;
      }
    }

  }
  if (hasZeroDiscount) {
  	return confirm(warnZeroDiscountMsg);
  }
  return true;
}

function validateCategoriesTab(formElement)
{
  var formElements = formElement.elements;
  var inOneCategory = false;

  for(var i = 0; formElements[i]; i++)
  {
    if(formElements[i].name.indexOf("product.categories") > 0)
    {
//      alert("found: " + formElements[i].name);
      if(formElement[i].checked)
      {
        inOneCategory = true;
      }
    }
  }

  if(!inOneCategory)
  {
//    showProductEditorTab('category');
//    return confirm(categoryErrorMessage);
  }

  return true;
}

function validateImagesTab(formElement)
{

}

function validateAttributesTab(formElement)
{

}

function validateOptionsTab(formElement)
{
  var formElements = formElement.elements;
  var optionPattern = new RegExp("^product\\.options\\(\\d+\\)\\.values$");
  var pricePattern = new RegExp("^product\\.pricing\\[\\d+\\]\\.price$");
  var greatestDecrementPattern = new RegExp("^greatestDecrement_\\d+$");

  // First, initialize the greatest increment amount for each option.
  for(var j=0; formElements[j]; j++)
  {
    var elementName = formElements[j].name;
    if(greatestDecrementPattern.test(elementName))
    {
      formElements[j].value = '0.00';
    }
  }

  // Get the greatest price decrement for each option.
  var lowestPrice = parseFloat(document.getElementById('advertisedPrice').value);
  for(var i=0; formElements[i]; i++)
  {
    var elementName = formElements[i].name;

    if(!formElements[i].disabled && optionPattern.test(elementName) && formElements[i].checked)
    {
      var optionId = elementName.substring('product.options('.length,
                         elementName.indexOf(').values'));

      var priceIncrementId =  'optionValuePriceIncrement(' + optionId + ')_' + formElements[i].value;
      var increasePriceId =  'optionValueIncreasePrice_' + formElements[i].value;
      var priceIncrement = document.getElementById(priceIncrementId);
      var increasePrice = document.getElementById(increasePriceId);
      var greatestDecrement = document.getElementById('greatestDecrement_' + optionId);

      if (increasePrice.value=='false' && parseFloat(priceIncrement.value) > parseFloat(greatestDecrement.value))
      {
        greatestDecrement.value = priceIncrement.value;
      }  
      
   	  if (parseFloat(priceIncrement.value) > 999999.99)
      {
    	alert("You can not increase/decrease the price value by more than 999,999.99.");
    	return false;
      }	
    }
    else if(!formElements[i].disabled && pricePattern.test(elementName))
    {
      var price = parseFloat(formElements[i].value);
      if(price < lowestPrice)
      {
        lowestPrice = price;
      }
    }
  }

  // Get the greatest total decrement amount
  var totalGreatestDecrement = 0.00;
  for(var j=0; formElements[j]; j++)
  {
    var elementName = formElements[j].name;
    if(greatestDecrementPattern.test(elementName))
    {
      totalGreatestDecrement = totalGreatestDecrement + parseFloat(formElements[j].value);
    }
  }

  if ((lowestPrice - totalGreatestDecrement) <= 0)
  {
    return confirm(optionPricingConfirmation);
  }

  return true;
}

function validateAssociationsTab(formElement)
{
  var formElements = formElement.elements;

  for(var i=0; formElements[i]; i++)
  {
    var elementName = formElements[i].name;
    if(elementName == 'product.associations(upsell).values' ||
       elementName == 'product.associations(xsell).values')
    {
      var options = formElements[i].getElementsByTagName('OPTION');
      for(var l=0; l<options.length; l++)
      {
        options[l].selected='true';
      }
    }
  }
}



//    see http://www.blastradius.com/svgopen2003/docs/Intermediate_DOM.ppt for arg parameters
//    MouseEvent
//    This provides specific contextual information associated with Mouse events
//    In the case of nested elements mouse events are always targeted at the most deeply nested element
//    Inherits from the UIEvent interface
//
//    MouseEvents:
//    click
//    mousedown
//    mouseup
//    mouseover
//    mousemove
//    mouseout
//
//    MouseEvent - Properties
//    MouseEvent.screenX - screen x coordinate
//    MouseEvent.screenY - screen y coordinate
//    MouseEvent.clientX - client x coordinate
//    MouseEvent.clientY - client y coordinate
//    MouseEvent.ctrlKey - true if ctrl key pressed
//    MouseEvent.shiftKey - true if shift key pressed
//    MouseEvent.altKey -  true if alt key pressed
//    MouseEvent.metaKey - true if meta key pressed
//    MouseEvent.button - which mouse button was pressed
//    MouseEvent.relatedNode - secondary node related to event
//
//    MouseEvent - Methods
//    MouseEvent.initMouseEvent(typeArg, canBubbleArg,  cancelableArg, viewArg, detailArg,
//     screenXArg, screenYArg,
//     clientXArg, clientYArg,
//     ctrlKeyArg, altKeyArg,
//     shiftKeyArg, metaKeyArg,
//     buttonArg, relatedTargetArg)
function validateProductEditor(formElement, appHost)
{
  var group = setupFormForCallbacks( formElement );

  if(!validateProductTab(formElement, appHost, group))
  {
    return false;
  }
  if(!validatePricingTab(formElement))
  {
    return false;
  }
  if(!validateCategoriesTab(formElement))
  {

  }
  if(!validateImagesTab(formElement))
  {

  }
  if(!validateAttributesTab(formElement))
  {

  }
  if(!validateOptionsTab(formElement))
  {
	return false;
  }
  if(!validateAssociationsTab(formElement))
  {

  }

  formElement.runCallbacks( group );
  return false;
}


// checkSelection (FORM formElement, STRING radioCheckInputName, INT minSelected, INT maxSelected [, BOOLEAN emptyOK==false])
//
// Check that
//
function checkSelection(formElement, checkInputName, minSelected, maxSelected)
{
  var valid = false;
  var selectedCount = 0;
  if(!minSelected)
  {
    minSelected = 1;
  }
  if(!maxSelected)
  {
    maxSelected = 1;
  }
  var firstElement;
  for(var i = 0; i < formElement.elements.length; i++)
  {
    if(formElement.elements[i].name == checkInputName && formElement.elements[i].checked)
    {
      if(!firstElement || firstElement == null)
      {
        firstElement = formElement.elements[i];
      }
      selectedCount++;
    }
  }
  return valid = selectedCount >= minSelected && selectedCount <= maxSelected;
}

function warnRadioButton(formElement, radioInputName, errorMessage)
{
  for(var i = 0; i < formElement.elements.length; i++)
  {
    if(formElement.elements[i].name == radioInputName)
    {
      formElement.elements[i].focus();
      alert(errorMessage);
      return;
    }
  }
}

function validateAddOrderItemQty(form) {
  for ( field in form ) {
    if ( field.indexOf('].qty') != -1 ) {
      if ( ! isInteger( form[field].value ) ) {
        alert('Please enter a valid quantity.');
        form[field].select();
        return false;
      }
    }
  }

  return true;
}
function uncheckAllExcept()
{
  var methodArgs = uncheckAllExcept.arguments;
  var formFields = document.configureForm.elements;

  var uncheckElement = true;
  for(var i = 0; i < formFields.length; i++)
  {
    uncheckElement = true;
    if(formFields[i].type == "checkbox")
    {
      for(var j = 0; j < methodArgs.length; j++)
      {
        if(formFields[i].name == methodArgs[j] ||
          formFields[i].id == methodArgs[j])
        {
          uncheckElement = false;
          break;
        }
      }
      if(uncheckElement)
      {
        formFields[i].checked = false;
      }
    }
  }
}

function uncheck()
{
  var methodArgs = uncheck.arguments;
  var formFields = document.configureForm.elements;

  for(var i = 0; i < formFields.length; i++)
  {
    if(formFields[i].type == "checkbox")
    {
      for(var j = 0; j < methodArgs.length; j++)
      {
        if(formFields[i].name == methodArgs[j] ||
          formFields[i].id == methodArgs[j])
        {
          formFields[i].checked = false;
        }
      }
    }
  }  
}

function check()
{
  var methodArgs = check.arguments;
  var formFields = document.configureForm.elements;

  for(var i = 0; i < formFields.length; i++)
  {
    if(formFields[i].type == "checkbox")
    {
      for(var j = 0; j < methodArgs.length; j++)
      {
        if(formFields[i].name == methodArgs[j] ||
          formFields[i].id == methodArgs[j])
        {
          formFields[i].checked = true;
        }
      }
    }
  }  
}

function move(fbox, tbox)
{
  var arrFbox = new Array();
  var arrTbox = new Array();
  var arrLookup = new Array();
  var i;
  for (i = 0; i < tbox.options.length; i++)
  {
    arrLookup[tbox.options[i].text] = tbox.options[i].value;
    arrTbox[i] = tbox.options[i].text;
  }

  var fLength = 0;
  var tLength = arrTbox.length;
  for(i = 0; i < fbox.options.length; i++)
  {
    arrLookup[fbox.options[i].text] = fbox.options[i].value;
    if (fbox.options[i].selected && fbox.options[i].value != "")
    {
      arrTbox[tLength] = fbox.options[i].text;
      tLength++;
    } 
    else 
    {
      arrFbox[fLength] = fbox.options[i].text;
      fLength++;
    }
  }

  arrFbox.sort();
  arrTbox.sort();
  fbox.length = 0;
  tbox.length = 0;
  var c;
  for(c = 0; c < arrFbox.length; c++)
  {
    var no = new Option();
    no.value = arrLookup[arrFbox[c]];
    no.text = arrFbox[c];
    fbox[c] = no;
  }

  for(c = 0; c < arrTbox.length; c++)
  {
    var no = new Option();
    no.value = arrLookup[arrTbox[c]];
    no.text = arrTbox[c];
    tbox[c] = no;
  }
}


function multiMove(fromBox, toBox, insertSort)
{

    var fBox = document.getElementById(fromBox);
    var tBox = document.getElementById(toBox);
    
   
    if (fBox && tBox)
    {
    
        var fBoxOptions = fBox.getElementsByTagName('OPTION');
        var tBoxOptions = tBox.getElementsByTagName('OPTION');
        var fBoxSelected = new Array();
               
        if (fBoxOptions && fBoxOptions.length > 0)
        {    
            var index = 0;
            for (var i = 0; i < fBoxOptions.length; i++)
            {
                if (fBoxOptions[i].selected && fBoxOptions[i].value != '')
                {
                    fBoxSelected[index++] = fBoxOptions[i];
                }
            }

            if (fBoxSelected.length > 0)
            {
                for (var j = 0; j < fBoxSelected.length; j++)
                {
                  if(insertSort && insertSort == 'alpha' && tBoxOptions.length > 0)
                  {
                      for(var k = 0; k < tBoxOptions.length; k++)
                      {                    
                        //insert back in aphabetical order
                        if(tBoxOptions[k].text + "" > fBoxSelected[j].text + "")
                        {
                          tBox.insertBefore(fBoxSelected[j], tBoxOptions[k]);
                          break;
                        }
                      }
                      if ( k == tBoxOptions.length ) {
                        tBox.appendChild(fBoxSelected[j]);
                      }
                  }
                  else
                  {
                    tBox.appendChild(fBoxSelected[j]);
                  }
                }
            }

        }
    }

}


function selectAll(elementId)
{
  var selectBox = document.getElementById(elementId);
  var options = selectBox.getElementsByTagName('option');
  for(var i = 0; i < options.length; i++)
  {
    options[i].selected='true';
  }
}

function openColorPicker(id, f)
{
    var urlstring = 'colorpicker.jsp?id=' + id + '&color=' + escape(document.getElementById(id).value);
    var nw = window.open(urlstring,'colorpickerwin','height=228,width=352,toolbar=no,minimize=no,status=no,memubar=no,location=no,scrollbars=no,resizable=no,screenX=300,screenY=250');
		nw.callbackFunction = f;
}

function clearElementWithId(fieldName)
{
    if (fieldName)
    {
        var element = document.getElementById(fieldName);
        element.value = "";
    }
}


function clickTextToToggle(checkboxId)
{
    if (checkboxId)
    {
        var element = document.getElementById(checkboxId);
        if (element)
        {
            //alert(element.checked);
            element.checked = !element.checked;
        }
    }
}


function changeSelectionOnCheckbox(ckbox, unHideSelection, hideSelection)
{
  if (ckbox.checked)
  {
    showElementWithId(unHideSelection);
    hideElementsWithIds(hideSelection);
  }
  else
  {
    hideElementsWithIds(unHideSelection);
    showElementWithId(hideSelection);
  }  
  
}

function changeSelectionOnCheckboxWithAnimation(ckbox, unHideSelection, hideSelection, parentElement)
{
  var element = document.getElementById(parentElement);
  
  if (isIE() && element && element.filters && element.filters.length > 0)
  {
      var length = element.filters.length;
      element.filters[length - 1].Apply();

      if (ckbox.checked)
      {
        showElementWithId(unHideSelection);
        hideElementsWithIds(hideSelection);
      }
      else
      {
        hideElementsWithIds(unHideSelection);
        showElementWithId(hideSelection);
      }  

      element.filters[length - 1].Play();
  
  } else {
    changeSelectionOnCheckbox(ckbox, unHideSelection, hideSelection);
  }
} 

function setActionOnClick(elementId, actionURL)
{
  var element = document.getElementById(elementId);
  
  if (element)
  {
    if (element.action)
    {
        element.action = actionURL;    
    } 
    
  }
}

function autojump()
{
}


// CALLBACK BASED VALIDATION

function setupFormForCallbacks( form ) {
  if ( !form.callbacks || (form.callbacks == null) )
    form.callbacks = new Array(0);
    
  if ( !form.callbackReturns || (form.callbackReturns == null) )
    form.callbackReturns = new Array(0);    
    
  if ( !form.currentGroup || ( form.currentGroup == null ) )
    form.currentGroup = 0;
    
  form.startIndex = form.callbacks.length;
  form.currentGroup = form.currentGroup + 1;
  
  form.addCallback = 
    function ( group, cbFunc ) 
    { 
      if ( group == form.currentGroup ) { 
        form.callbacks.push( cbFunc ); 
        form.callbackReturns.push( false ); 
      } 
    };
    
  form.callbackSuccess = 
    function ( group, id )     
    {       
      form.callbackReturns[ id ] = true; 
      form.checkFinished( group ); 
    };
    
  form.callbackFailure = 
    function ( group, id ) {    
      form.callbackReturns[ id ] = false;
      form.checkFinished( group ); 
    };
    
  form.runCallbacks = 
    function( group ) {    
      if ( group == form.currentGroup ) { 
        var i; 
        for ( i = form.startIndex; i < form.callbacks.length; i++ ) { 
          form.callbacks[i]( i, form, form.currentGroup );
        } 
        
        form.checkFinished( group ); 
      }               
    };
    
  form.checkFinished = 
    function ( group ) {   
      if ( group == form.currentGroup ) 
      { 
        var i; 
        for ( i = form.startIndex; i < form.callbacks.length; i++ ) { 
          if ( ! form.callbackReturns[i] ) {
            return false; 
          }
        } 
               
        form.doSubmit(); 
        return true; 
      } 
    }; 
    
  form.isCurrentGroup = 
    function ( group ) 
    { 
      return group == form.currentGroup; 
    };
    
  form.doSubmit =
    function()    
    {
      if ( ! form.didSubmit ) {
        form.didSubmit = true;
        form.submit();
      }
    }
  
  return form.currentGroup;
}

function checkFound( form, group, url, errorMessage ) {
  form.addCallback( group, 
                    function ( index, formElement, group ) 
                    {
                      checkFoundCB( formElement, url, errorMessage, group, index ); 
                    } 
                  );
}

function checkFoundCB( form, url, errorMessage, group, index ) {
  xmlLoader( url,
             function ( xmlHttp ) { handleCheckFoundResponse( xmlHttp, index, form, group, errorMessage ); } );
}

function handleCheckFoundResponse( xmlHttp, index, form, group, errorMessage ) {
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);
  var rootElement = xmlDoc.getElementsByTagName("root")[0];
  var foundElement = rootElement.getElementsByTagName("found")[0];
  
  if ( foundElement.childNodes[0].nodeValue == 'true' ) {
    if ( form.isCurrentGroup( group ) )
     alert( errorMessage );
     
    form.callbackFailure( group, index );
     
  } else {
    form.callbackSuccess( group, index );
  }
}function validateOptionForm(form) {
  if ( !checkString(form['label']) ) {
    alert( 'You must give this option a name.' );
    form['label'].select();
    return false;
  }
  
  var found = false;
  for ( var i=0; i<form.length; i++) {
  	field = form[i];
	if ( field['name'].indexOf('optionLabel(') == 0 ) {
      		found = true;
      		break;
    	}
  }
  
  if ( !found ) {
    alert( 'You must define at least one option choice.' );
    form['addOptionLabel'].select();    
    return false;
  }
  
  if ( checkString(form['addOptionLabel']) ) {
    return confirm('You have not added the choice "' + form['addOptionLabel'].value + '" to the list of choices yet.  Do you still want to submit,which will discard this choice?' );
  }
  
  return true;
}

/*
 * Storefront validation functions.
 */
function validateCreditCard(form, prefix) {
  var selectedCard = form[ prefix + 'creditCardInfo.cardType'].options[form[ prefix + 'creditCardInfo.cardType'].selectedIndex].value;

//  if ( !isAnyCard( form[ prefix + 'creditCardInfo.cardNumber'].value ) ) {
  if ( !isCardMatch( selectedCard, form[ prefix + 'creditCardInfo.cardNumber'].value ) ) {
    alert('Please enter a valid credit card number.'); 
    form[ prefix + 'creditCardInfo.cardNumber'].select(); 
    return false;   
  }
  
  if ( !checkString( form[ prefix + 'creditCardInfo.nameOnAccount'] ) ) {
    alert('Please enter the name on your account.'); 
    form[ prefix + 'creditCardInfo.nameOnAccount'].select(); 
    return false;     
  }
  
  var expMonth = form[ prefix + 'creditCardInfo.expirationMonth'].value;
  var expYear = form[ prefix + 'creditCardInfo.expirationYear'].value;
  
  if ( !isMonth(expMonth) ) {
    alert('Please enter a valid month.'); 
    form[ prefix + 'creditCardInfo.expirationMonth'].select(); 
    return false;     
  }  
  
  if ( !isYear(expYear) ) {
    alert('Please enter a valid year.'); 
    form[ prefix + 'creditCardInfo.expirationYear'].select(); 
    return false;     
  }   
  
  // Create a date from the selected expiration fields (assumes midnight at the end of the selected month).
  var expDate = new Date("20" + expYear, expMonth, 1);
  var currDate = new Date();
  //alert("expDate = " + expDate);
  //alert("currDate = " + currDate);
  if (currDate > expDate) {
    alert('Please choose an expiration date that has not yet expired.');
    return false;
  }
  
  if ( !isInteger( form[ prefix + 'creditCardInfo.cvm'].value ) || (form[ prefix + 'creditCardInfo.cvm'].value.length != 3 && form[ prefix + 'creditCardInfo.cvm'].value.length != 4)) {
    alert('Please enter a valid credit card security id.'); 
    form[ prefix + 'creditCardInfo.cvm'].select(); 
    return false;     
  }   
  
  return true;
}

function validateECheckForm(form) {
  return validateECheck(form, '');
}

function validateECheck(form, prefix) {
  if ( !checkString( form[ prefix + 'checkBean.bankAcctName'] ) ) {
    alert('Please enter the name on the bank account.'); 
    form[ prefix + 'checkBean.bankAcctName'].select(); 
    return false;   
  }
  
  if ( !checkString( form[ prefix + 'checkBean.bankAcctNum'] ) ) {
    alert('Please enter your bank account number.'); 
    form[ prefix + 'checkBean.bankAcctNum'].select(); 
    return false;     
  }
  
  if ( !checkString( form[ prefix + 'checkBean.bankAbaCode'] ) ) {
    alert('Please enter your account routing number.'); 
    form[ prefix + 'checkBean.bankAbaCode'].select(); 
    return false;     
  }  
  
  if ( !checkString( form[ prefix + 'checkBean.bankName'] ) ) {
    alert('Please enter the name of your bank.'); 
    form[ prefix + 'checkBean.bankName'].select(); 
    return false;     
  }   
  
  return true;
}


function validateAddress( form, prefix ) {
  if ( isWhitespace( form[ prefix + '.firstName' ].value ) ) {
    alert('Please enter your first name.');
    form[ prefix + '.firstName' ].select();  
    return false;
  }

  if ( isWhitespace( form[ prefix + '.lastName' ].value ) ) {
    alert('Please enter your last name.');
    form[ prefix + '.lastName' ].select();  
    return false;
  }
  
  if ( isWhitespace( form[ prefix + '.address1' ].value ) ) {
    alert('Please enter your mailing address.');
    form[ prefix + '.address1' ].select();  
    return false;
  }
  
  if ( isWhitespace( form[ prefix + '.city' ].value ) ) {
    alert('Please enter a city for your mailing address.');
    form[ prefix + '.city' ].select();  
    return false;
  }

  /*
  	Only performs zip code region code validation if the selected country is US
  */
  if (!form[ prefix + '.countryCode'] ||
      (form[ prefix + '.countryCode'].options[form[ prefix + '.countryCode'].selectedIndex ].value == 'US' ))
  {
    if ( !isZIPCode( form[ prefix + '.postalCode' ].value) )
    {
      alert('Please enter a valid postal code.');
      form[ prefix + '.postalCode' ].select();  
      return false;
    }
    
	form[ prefix + '.regionCode' ].value = form[ prefix + '.regionCode' ].value.toUpperCase();
	if ( !isStateCode( form[ prefix + '.regionCode' ].value ) ) {
	  alert('Please enter a valid state/prov. code.');
	  form[ prefix + '.regionCode' ].focus();  
	  return false;
	}    
  }

  var phFullNumber = form[ prefix + '.phoneFullNumber' ]; 
  var phExtension = form[ prefix + '.phoneExtension' ]; 
  
  if ( phFullNumber.value.length == 0 )
  {
    alert( 'Please enter a valid phone number.' );
    phFullNumber.select();
    return false;    
  }
  if ( phExtension.value.length>0 && !isInteger( phExtension.value ) )
  {
    alert( 'Please enter a valid extension for the phone number.' );
    phExtension.select();
    return false;    
  }
  
  if (form[ prefix + '.email' ] && !isEmail( form[ prefix + '.email' ].value ) ) {
    alert('Please enter a valid email address.');
    form[ prefix + '.email' ].select();
    return false;  
  }
  
  return true;
}


function termsConditionsConfirm()
{
    var message = "Important Disclaimer!\n\nThe default terms and conditions provided on this page can be used with the following disclaimer:\n\nThe following descriptions and suggestions are not legal, tax or financial advice.\nQuick Shopping Cart does not guarantee to the legality of any phrasing or provisions offered\nor derived from these descriptions and suggestions.  You should consult with an attorney\nto ensure that your terms and conditions are sufficient to meet your needs, appropriate\nfor your jurisdiction and are legally binding on your customers.";
    if (confirm(message))
    {
        return true;
    } else {
        return false;
    }
}

function validateSetupAccount(form) 
{
  var domainName = form['domain'].value;
  var domainPrefix = document.getElementById('domainPrefix').innerHTML;

  if(domainName.indexOf( 'www.' ) == 0)
  {
    alert("Do not type the www. or your ext. before your domain name when registering\nas it is automatically inserted.");
    return false;
  }
  if(domainPrefix == 'shop.')
  {
    if (domainName.indexOf('shop.') == 0)
    {
      alert("Do not type the 'shop.' before your domain name when registering\nas it is automatically inserted.");
      return false;
    }
  }
  if(validateDomainNameForSetup(domainName))
  {
    if(isAgent('IE'))
    {
	    var domainArray = new Array();
		domainArray[0] = domainPrefix;
		domainArray[1] = domainName;
		//return value specifies whether or not to continue
	    var cont = showModalDialog("domainNameConfirmation.sc", domainArray, "dialogHeight: 200px;");
	    if(cont)
	    {
	    	document.getElementById('submit').disabled=true;
	    	return true;
	    } 
		else 
		{
	    	return false;
	    }    
    }else
    {
	    if (confirm("You have specified the domain name '" + domainPrefix + domainName + "' for your storefront. Do you want to continue?"))
	    {
	      document.getElementById('submit').disabled=true;
	      return true;
	    }
    }
  }
  return false;
}

function validateDomainName(domainName)
{
  if(!domainName || domainName.length == 0)
  {
    alert("Please specify a domain name.");
    return false;
  }
  if(domainName.indexOf("-") == 0)
  {
    alert("The domain you have specified is invalid.\nA domain name cannot start with \"-\"");
    return false;
  }
  if(domainName.indexOf("-") == domainName.length - 1)
  {
    alert("The domain you have specified is invalid.\nA domain name cannot end with \"-\"");
    return false;
  }
  if(domainName.length > 67)
  {
    alert("Domain names cannot exceed 67 characters.");
    return false;
  }
  var versionRegExp = new RegExp("[a-zA-Z0-9](([a-zA-Z0-9\\.])*(-+[a-zA-Z0-9\\.])*)*\\.(xn\\-\\-[-a-zA-Z0-9]+|[a-zA-Z]{2,4})");
  var result = versionRegExp.exec(domainName);

  if(!result || result.length == 0 || result[0].length != domainName.length)
  {
    alert("The domain you have specified is invalid.\nThe only valid characters for a domain name are letters, numbers and a hyphen \"-\".\nIt must start with a letter, and have a 2 to 4 letter suffix (.com, .biz, .tv, etc) or a suffix that begins with xn--.");
    return false;
  }

  return true;
}

function validateDomainNameForSetup(domainName)
{
  if(!domainName || domainName.length == 0)
  {
    alert("Please specify a domain name.");
    return false;
  }
  if(domainName.length > 67)
  {
    alert("Domain names cannot exceed 67 characters.");
    return false;
  }

  return true;
}

function validateMerchantEmail(form)
{
	var a = form['contactUsEmail'].value.split(',');
  for(var i = 0; i < a.length; i++)
  {
		if (!isEmail(a[i]))
		{
			alert("'Contact Request Notices' contains an invalid email address.");
			return false;
		}
  }

	var b = form['replyToEmail'].value.split(',');
	if (b.length > 1)
	{
		alert("'System Notices' does not allow multiple email addresses.\nPlease enter a valid e-mail address.");	
		return false;
	}
  for(var i = 0; i < b.length; i++)
  {
		if (!isEmail(b[i]))
		{
			alert("'System Notices' contains an invalid email address.");
			return false;
		}
  }

	var c = form['newOrderEmail'].value.split(',');
  for(var i = 0; i < c.length; i++)
  {
		if (!isEmail(c[i]))
		{
			alert("'New Order Notices' contains an invalid email address.");
			return false;
		}
  }

	var d = form['lowInventoryEmail'].value.split(',');
  for(var i = 0; i < d.length; i++)
  {
		if (!isEmail(d[i]))
		{
			alert("'Low Inventory Notices' contains an invalid email address.");
			return false;
		}
  }	
	return true;
}

function minimizeHelp(helpId, helpTableId)
{
  rollUp(helpId, 50);
  hideElementWithId("minimizeHelp");
  showElementWithId("maximizeHelp");  
  
}

function maximizeHelp(helpId, helpTableId)
{
  rollDown(helpId, 50);
  hideElementWithId("maximizeHelp");
  showElementWithId("minimizeHelp");  
}

/* HELP WINDOW NAVIGATION */

function selectTopic( id, jump, open, def ) {
  if ( !open )
    openTopic( id, jump, open );
  else {
  
    if ( isElementShown( frames['contents'].document.getElementById( id ) ) ) {
    
      hideElement( frames['contents'].document.getElementById( id ) );
      frames['contents'].document.getElementById( id + '_image' ).src = 'images/help_category_closed.gif';
      
      if ( jump ) {
        jumpToTopic( id );
      }
    
    } else {
      openTopic( id, jump, open );
      if ( !jump && def ) {
        jumpToTopic( def );
      }
    }
    
  }
}

function openTopic( id, jump, open ) { 
  if ( jump ) {
    jumpToTopic( id );    
  }

  var steps = id.split('/');
  var i;
  
  var str = '';
  for ( i = 0; i < steps.length; i++ ) {
     if ( i == 0 )
       str = steps[0];
     else 
       str = str + '/' + steps[i];
       
     if ( ( i < steps.length - 1) ) {
       showElement( frames['contents'].document.getElementById( str ) );
       showElement( frames['contents'].document.getElementById( str ) );
            
       frames['contents'].document.getElementById( str + '_image' ).src = 'images/help_category_open.gif';
     }
     
     if ( (i == steps.length - 1) && open ) {
       showElement( frames['contents'].document.getElementById( str ) );
       showElement( frames['contents'].document.getElementById( str ) );
       
       frames['contents'].document.getElementById( str + '_image' ).src = 'images/help_category_open.gif';
     }
  }
}

function jumpToTopic( id ) {      
  if ( !frames['topics'].document.shownId || 
        frames['topics'].document.shownId != id ) {           
        
    if ( frames['contents'].document.topicHistory ) {    
      if ( frames['contents'].document.shownIndex != (frames['contents'].document.topicHistory.length - 1) ) {
        frames['contents'].document.topicHistory = frames['contents'].document.topicHistory.slice( 0, frames['contents'].document.shownIndex + 1 );
      }

      frames['contents'].document.shownIndex = frames['contents'].document.topicHistory.length;    
    } else {
      frames['contents'].document.shownIndex = 0;
      frames['contents'].document.topicHistory = new Array(0);
    }

    frames['contents'].document.topicHistory.push( id );   
      
    helpUpdateButtons();
  }
  
  displayTopic( id );
}

function displayTopic( id ) {
  if ( frames['topics'].document.shownId ) {
    hideElement( frames['topics'].document.getElementById( frames['topics'].document.shownId ) );    
  }

  showElement( frames['topics'].document.getElementById( id ) );
  frames['topics'].document.shownId = id;
  
  if ( frames['contents'].document.shownId ) {
    frames['contents'].document.getElementById( frames['contents'].document.shownId ).style.color = 'black';
    frames['contents'].document.getElementById( frames['contents'].document.shownId ).style.backgroundColor = 'white';
  }

  frames['contents'].document.getElementById( id + "_item" ).style.color = "white";
  frames['contents'].document.getElementById( id + "_item" ).style.backgroundColor = "#003366";
  frames['contents'].document.shownId = id + "_item";
}

/* TOPIC HISTORY */

function helpGoBack() {
  if ( frames['contents'].document.shownIndex > 0 ) {
    frames['contents'].document.shownIndex = frames['contents'].document.shownIndex - 1;
    displayTopic( frames['contents'].document.topicHistory[ frames['contents'].document.shownIndex ] );
  }
  
  helpUpdateButtons();
}

function helpGoForward() {
  if ( frames['contents'].document.shownIndex < ( frames['contents'].document.topicHistory.length - 1 ) ) {
    frames['contents'].document.shownIndex = frames['contents'].document.shownIndex + 1;
    displayTopic( frames['contents'].document.topicHistory[ frames['contents'].document.shownIndex ] );
  }

  helpUpdateButtons();
}

function helpUpdateButtons() {
  if ( frames['contents'].document.shownIndex > 0 ) {
    frames['tabs'].document.getElementById("helpBackBtn").src = 'images/ibtn_arrowleft.gif';
    frames['tabs'].document.getElementById("helpBackBtn").style.cursor = "pointer";
  } else {
    frames['tabs'].document.getElementById("helpBackBtn").src = 'images/ibtn_arrowleft_dis.gif';  
    frames['tabs'].document.getElementById("helpBackBtn").style.cursor = "normal";
  }
  
  if ( frames['contents'].document.shownIndex < ( frames['contents'].document.topicHistory.length - 1 ) ) {
    frames['tabs'].document.getElementById("helpForwardBtn").src = 'images/ibtn_arrowright.gif';
    frames['tabs'].document.getElementById("helpForwardBtn").style.cursor = "pointer";
  } else {
    frames['tabs'].document.getElementById("helpForwardBtn").src = 'images/ibtn_arrowright_dis.gif';  
    frames['tabs'].document.getElementById("helpForwardBtn").style.cursor = "normal";
  }
}

/* MAIN TABS */

function showHelpContents() {
   if (frames['contents'].document.getElementById('contentDiv') != null)
   	 showElement( frames['contents'].document.getElementById( 'contentDiv' ) );
   else if (frames['contents'].document.getElementById('contentDiv_jsp') != null)
   	 showElement( frames['contents'].document.getElementById( 'contentDiv_jsp' ) );

   hideElement( frames['contents'].document.getElementById( 'searchDiv' ) );
}

function showHelpSearch() {
   showElement( frames['contents'].document.getElementById( 'searchDiv' ) );
   hideElement( frames['contents'].document.getElementById( 'contentDiv' ) );
}

/* HELP SEARCH */

var HELP_ON_PAGE_COUNT = 5;

function helpSearch() {
  var queryString = frames['contents'].document.getElementById( 'query' ).value;     
  
  var resultsDiv = frames['contents'].document.getElementById( 'searchResultsDiv' );
  showElement( resultsDiv );
  resultsDiv.innerHTML = "<center>Searching...</center>";
  
  xmlLoader( 'searchHelp.hg?query=' + escape( queryString ), 
             helpSearchCallback );  
}

function helpSearchCallback( xmlHttp ) {
  var resultsDiv = frames['contents'].document.getElementById( 'searchResultsDiv' );

  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);

  var rootElement = xmlDoc.getElementsByTagName("data")[0];
  
  var hitCountElement = rootElement.getElementsByTagName("hitCount")[0];
  resultsDiv.hitCount = parseInt( hitCountElement.childNodes[0].nodeValue );
 
  var matchesElement = rootElement.getElementsByTagName("matches")[0]; 
  var matches = new Array(0);
  var items = matchesElement.getElementsByTagName("item");
  
  var i;
  for ( i = 0; i < resultsDiv.hitCount; i++ ) {    
    var topic = { name:items[i].getElementsByTagName("name")[0].childNodes[0].nodeValue,
                  id:items[i].getElementsByTagName("id")[0].childNodes[0].nodeValue };    
    
    matches.push( topic );  
  }
  
  resultsDiv.matches = matches;
  
  displaySearchMatches( );
}

function displaySearchMatches( ) {
  var resultsDiv = frames['contents'].document.getElementById( 'searchResultsDiv' );

  var innerHTML = 'Found ' + resultsDiv.hitCount + ' results:<br/><br/>';
  
  var i;
  for ( i = 0; i < resultsDiv.hitCount; i++ ) {
    var topic = resultsDiv.matches[i];     
     
    innerHTML += '<p style="margin-left: 5px; margin-bottom: 5px; margin-top: 0px"><a href="#" onClick="window.parent.selectTopic(\'' + topic.id + '\', 1, 0); return false;">' + topic.name + '</a></p>';  
  }
   
  resultsDiv.innerHTML = innerHTML;
}/**
These are utility functions for growing/shrinking tables that represent lists
*/

function tlNullFilter( id ) {
   return 0;
}

function tlFirstNumberParser( id ) {
   var r = /(\d+)/;
   r.test( id );
   return parseInt(RegExp.$1);
}

function tlLastNumberParser( id ) {
   var r = /(\d+)/;
   r.test( strReverse(id) );
   return parseInt(strReverse(RegExp.$1));
}   

function tlAddRow( tBody, idFilter, idParser, rowGenerator )
{
   var params = new Array( arguments.length - 4 );
   var i;
   for ( i = 4; i  < arguments.length; i++ ) {
      params[i-4] = arguments[i];
   }

   // get a valid row id
   var maxIndex = 0;
   var trNodeList = tBody.getElementsByTagName("TR");
   for (var i = 0; i < trNodeList.length; i++)
   {
      var tempId = trNodeList[i].id;        
      if ( !idFilter( tempId ) )
      {     
         var intId = idParser( tempId );
         if ( intId > maxIndex ) {
            maxIndex = intId;
         }
      }           
   }

   index = maxIndex + 1;
   
   var trTag = rowGenerator( index, params );
   tBody.appendChild(trTag);
   
   return index;
}

function tlDeleteRow(tBody, itemId)
{
   var trToDelete = document.getElementById(itemId);

   if (trToDelete)
   {      
      tBody.removeChild(trToDelete);
   }
}

function tlClear( tBody, idFilter )
{
   var trNodeList = tBody.getElementsByTagName("TR");
   var trIdList = new Array(0);
   var i;
   
   for (i = 0; i < trNodeList.length; i++)
   {
      var tempId = trNodeList[i].id;        
      if ( !idFilter( tempId ) )
      {     
         trIdList.push( tempId );
      }           
   }
   
   for (i = 0; i < trIdList.length; i++)
   {
      tlDeleteRow( tBody, trIdList[i] );   
   }
   
   tBody.selectedRow = null;
}

function tlIsEmpty( tBody, idFilter ) {
   var trNodeList = tBody.getElementsByTagName("TR");
   for (var i = 0; i < trNodeList.length; i++)
   {
      var tempId = trNodeList[i].id;        
      if ( !idFilter( tempId ) )
      {     
         return false;
      }              
   }
   
   return true;
}

function tlRestoreAlternatingRowStyle( tBody, idFilter ) {
   var trNodeList = tBody.getElementsByTagName("TR");
   var j = 1;
   for (var i = 0; i < trNodeList.length; i++)
   {
      if ( !idFilter( trNodeList[i].id ) )
      {  
         if ( tBody.selectedRow == trNodeList[i].firstChild.id ) {
           trNodeList[i].firstChild.oldClassName = 'selection-row' + (( j % 2 ) + 1);
         } else {
           trNodeList[i].firstChild.className = 'selection-row' + (( j % 2 ) + 1);
         }
         
         j++;
      }           
   }
}

function tlSelectRow( tBody, idString, selectedClass ) {
   var tr = document.getElementById( idString );
     
   if ( tBody.selectedRow ) {
      if ( tBody.selectedRow == idString) 
         return;
   
      tlDeselectRow( tBody );
   }   
         
   tr.oldClassName = tr.className;   
   tr.className = selectedClass;
   tBody.selectedRow = idString;
}

function tlDeselectRow( tBody ) {
   var trOld = document.getElementById( tBody.selectedRow );     
   if ( trOld ) {
     trOld.className = trOld.oldClassName;   
   }
   tBody.selectedRow = null;
   return trOld;
}

function tlClickRow( tBody, idString, selectedClass ) {  
   if ( tBody.selectedRow && tBody.selectedRow == idString ) {     
      tlDeselectRow( tBody );   
      return false;
   } else {   
      tlSelectRow( tBody, idString, selectedClass );   
      return true;
   }
}

function tlGetNextSibling( tr, idFilter ) {
   var sib = tr.nextSibling;
   while ( sib != null && idFilter( sib.id ) ) {
      sib = sib.nextSibling;   
   }
   return sib;
}

function tlGetPreviousSibling( tr, idFilter ) {
   var sib = tr.previousSibling;
   while ( sib != null && idFilter( sib.id ) ) {
      sib = sib.previousSibling;   
   }
   return sib;
}/*
 	getMaintTaskStatus (uri) {
 		- make XHR
 		- readystatechange -> statusHandler {
 			- success -> redirect
 			- wait -> setTimeout (getMaintTaskStatus, 5000)
 			- error -> show error
 		}
 	}
*/
var appHost='';
var confirmSuccess=0;
/*
 * getHTTPObject()
 * courtesy of Jeremy Keith, _Bullet Proof AJAX_
 * http://bulletproofajax.com/code/
 * 
 */
function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}

function getMaintTaskStatus(uri)
{
	var timestamp = new Date();
	if (window.console) console.log (uri);
	uri = uri + 'loginMaintTaskStatus.hg';
	var uniqueURI = uri+(uri.indexOf('?') > 0 ? '&amp;' : '?')+'timestamp='+timestamp.getTime();
	var req = getHTTPObject();
	req.onreadystatechange = function () {
		statusHandler(req);
	};
	
	req.open('GET', uniqueURI, true);
	req.send(null);
}

function statusHandler(req)
{
	if (req.readyState == 4 ) {
		if (window.console) console.log ("req.status: " + req.status);
		if (req.status == 200) {
			var xmlDoc = XmlDocument.create();
			xmlDoc.loadXML(req.responseText);
			var	statusElement =	xmlDoc.getElementsByTagName("status")[0];
			var	status = statusElement.getAttribute("name");
			
			if (status == "success") {
				
				if (confirmSuccess==1) {
					updateMaintTaskStatus('Status: Update Completed...');
					setTimeout ('location=\'adminHeaderProcessor.hg\'', 1000);
				} else {
					confirmSuccess=1;
					updateMaintTaskStatus('Status: Confirming Update...');
					setTimeout ('getMaintTaskStatus(\'' + appHost + '\');', 1000);
				} 
			} else if (status == "wait") {
				updateMaintTaskStatus('Status: Updating...');		
				setTimeout ('getMaintTaskStatus(\'' + appHost + '\');', 5000);
			} else if (status=='error') {
				document.getElementById('progress-meter').style.display='none';
				updateMaintTaskStatus('<span style="color: #900;">There has been an error updating your site. Please contact customer service.</span>');	
			}
		}
	}
}

/* update the page */
function updateMaintTaskStatus(statusText)
{
	var statusMsg =	document.getElementById('statusText');
	if (statusMsg)
	{
		statusMsg.innerHTML = "<p>" + statusText + "</p>";
	}
}// member.js
// functions used in forms related to members

function validatePasswords(formElement) {
  return (validatePasswordsInternal(formElement) > 0);
}

function validatePasswordsInternal(formElement, group) {
   if ( formElement['credential.password'].value != formElement['credential.confirmPassword'].value ) {
      alert( confirmPasswordErrorMsg );
      formElement['credential.password'].focus();
      formElement['credential.password'].select();   
      return 0;
   }  

   if ( ! isStrongPassword( formElement['credential.password' ].value ) ) {
      alert( strongPasswordErrorMsg );
      formElement['credential.password'].focus();
      formElement['credential.password'].select();   
      return 0;   
   }

   if ( document.forms['editMember'] || document.forms['changePassword'] ) {  
      checkFound( formElement, group, 
                  'checkPasswordHistory.hg?userId=' + document.getElementsByName( 'userId' )[0].value + 
                    '&password=' + escape( formElement['credential.password' ].value ) +
                    '&siteId=' + document.getElementsByName( 'siteId' )[0].value,                    
                  'This password already exists in your password history.' );
                  
      return -1;
   }

   return 1;
}

function clickChangePassword() {
   if (document.getElementById( 'changePassword' ).checked ) {
      document.getElementById('password1e').disabled = false; 
      document.getElementById('password2e').disabled = false; 
      
      document.getElementById('password1t').style.color = 'black'; 
      document.getElementById('password2t').style.color = 'black'; 
      
      if ( ! document.getElementById( 'changePassword' ).changed ) {             
         document.getElementById('password1e').value = '';
         document.getElementById('password2e').value = '';
         
         document.getElementById( 'changePassword' ).changed = true;
      }
      
   } else {
      document.getElementById('password1e').disabled = true; 
      document.getElementById('password2e').disabled = true; 
      
      document.getElementById('password1t').style.color = 'gray'; 
      document.getElementById('password2t').style.color = 'gray'; 
      
   }
}
var onMenuWithId;

function showMenu(menuId, menuParentElementId, alignPosition)
{
	var menuElement = document.getElementById(menuId);
	var menuParentElement = document.getElementById(menuParentElementId);
	
	if(menuParentElement)
	{
		if(alignPosition == "bottom-left")
		{
			menuElement.style.left = getElementLeft(menuParentElement) - 200 +"px";
			menuElement.style.top = menuParentElement.style.height;
			//menuElement.style.top = parseInt(getElementTop( menuParentElement )) + parseInt(menuParentElement.style.height)+"px";
		}
		else if ( alignPosition == "bottom-right" )
		{
			//alert(menuParentElement.style.width);
			menuElement.style.left = getElementLeft(menuParentElement) - (parseInt( menuParentElement.width ) + parseInt(menuElement.width)) + "px";
			//(parseInt( getElementLeft( menuParentElement ) ) + parseInt( menuParentElement.width ) - parseInt( menuElement.width )) + "px";
			//menuElement.style.top = menuParentElement.style.height +"px";
			//menuElement.style.top = parseInt(getElementTop( menuParentElement )) + parseInt(menuParentElement.style.height)+"px";
		}
	}
	
	if(isIE())
	{
		showIEMenu(menuElement);
	}
	else
	{
		showNonIEMenu(menuElement);
	}
}

function hideMenu(menuId, force)
{
  if(menuId != onMenuWithId)
  {
    if(isIE())
    {
      hideIEMenu(menuId);
    }
    else
    {
      hideNonIEMenu(menuId);
    }  
  }
}

function showIEMenu(menuElement)
{
	if(!menuElement.style.filter || !menuElement.filters.blendTrans)
	{
		menuElement.style.filter += " blendTrans(duration=.3)";
	}
	menuElement.filters.blendTrans.apply();
	menuElement.style.display="block";
	menuElement.style.visibility = "visible";
	menuElement.filters.blendTrans.play();
}



function showNonIEMenu(menuElement)
{
	menuElement.style.display="block";
	menuElement.style.visibility="visible";
}



function hideIEMenu(menuId)
{
  var menuElement = document.getElementById(menuId);
  if(!menuElement.style.filter || !menuElement.filters.blendTrans)
  {
    menuElement.style.filter+= " blendTrans(duration=.3)";
  }
  if(menuElement.style.visibility != "hidden")
  {
    menuElement.filters.blendTrans.apply();
    menuElement.style.visibility="hidden";
    menuElement.filters.blendTrans.play();
  }
}

function hideNonIEMenu(menuId)
{
  var menuElement = document.getElementById(menuId);
  if(menuElement)
  {
    menuElement.style.visibility="hidden";
    menuElement.style.display="none";  
  }
}

function onMenu(menuId)
{
  onMenuWithId = menuId;
}

function resizeMenu(menuName)
{
  var adminFlyDownElement = document.getElementById('adminFlyDownDiv');
  if(parent && parent.document)
  {
    var frameElement = parent.document.getElementById(menuName+'MenuFlyDown');
    if(frameElement)
    {
      frameElement.style.width = adminFlyDownElement.offsetWidth;
      frameElement.style.height = adminFlyDownElement.offsetHeight;
    }
  }
}

function testMouseLeftMenu( e, menuRoot ) 
{
  if (!e) var e = window.event;
  var tg = (window.event) ? e.srcElement : e.target;
  //if (!isChild( tg, menuRoot ) ) return false;
  var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
  while (reltg != menuRoot && reltg.nodeName != 'BODY')
    reltg= reltg.parentNode
  if (reltg== tg) return false;
  
  // Mouseout took place when mouse actually left layer
  // Handle event
  return true;
}
// javascript for menu customization and menu item edit pages in the admin tool.
function submitMenuCustomizationForm(menuType, index, direction) {
	var form = document.getElementById("menuForm");
	var menuTypeInput = document.getElementById("menuType");
	var i = document.getElementById("i");
	var j = document.getElementById("j");

	// this is to get us to 0 based indexes.
	index = index - 1;
	menuTypeInput.value = menuType;
	i.value = index;
	if (direction == "up") {
		j.value = index - 1;
	} else {
		j.value = index + 1;
	}
	form.submit();
}

function resetMenu(menuType) {
	var form = document.getElementById("menuForm");
	var menuTypeInput = document.getElementById("menuType");
	var requestType = document.getElementById("requestType");
	menuTypeInput.value = menuType;
	requestType.value = "RESET";
	form.submit();
}

function deleteItem(menuType, index) {
	var confirmResult = confirm("Would you like to permanently remove this menu item?");
	
	if (confirmResult) {
		var form = document.getElementById("menuForm");
		var menuTypeInput = document.getElementById("menuType");
		var requestType = document.getElementById("requestType");
		var deleteIndex = document.getElementById("deleteIndex");
		menuTypeInput.value = menuType;
		requestType.value = "DELETE";
		deleteIndex.value = index - 1;
		form.submit();
	}
}

function hideErrors() {
	document.getElementById("errors").style.display = "none";
}

// menu item edit stuff
function closeForm() {
	var parentDoc = window.parent.document;
	var row = parentDoc.getElementById("editForm");
	row.style.display = "none";
	parentDoc.getElementById("errors").style.display = "none";
}

function openForm() {
	var parentDoc = window.parent.document;
	var row = parentDoc.getElementById("editForm");
	row.style.display = "";
}

var customLabel = '';
var lastSelected = "CUSTOM";
var customURL = "";

function pageTypeOnChangeHandler() {
	var select = document.getElementById("pageType");
	var options = select.getElementsByTagName("option");
	if (options.length > 0) {
		var label = document.getElementById('label');
		var urlRow = document.getElementById("urlRow");
		var url = document.getElementById("url");
		var domainRow = document.getElementById("domainRow");
		var targetRow = document.getElementById("targetRow");
		var selectedItem = options[select.selectedIndex];
		if (lastSelected != selectedItem.value) {
			if (lastSelected == "CUSTOM") {
				customLabel = label.value;
				label.value = selectedItem.text;
				targetRow.style.display = "none";

				urlRow.style.display = "none";
				customURL = url.value;
				url.value = "";
			} else if (lastSelected == "WST") {
				customLabel = label.value;
				label.value = selectedItem.text;
				targetRow.style.display = "none";

				domainRow.style.display = "none";
			}

			if (selectedItem.value == "CUSTOM") {
				label.value = customLabel;
				targetRow.style.display = "";

				urlRow.style.display = "";
				url.value = customURL;
			} else if (selectedItem.value == "WST") {
				label.value = customLabel;
				targetRow.style.display = "";

				domainRow.style.display = "";
			}
			lastSelected = selectedItem.value;
		}
	}
	resizeIframe();
}

function targetOnChangeHandler() {
	var select = document.getElementById("target");
	var options = select.getElementsByTagName("option");
	var customTarget = document.getElementById("customTarget");

	var selectedItem = options[select.selectedIndex];
	if (selectedItem.value == "CUSTOM") {
		customTarget.style.display = "";
	} else {
		customTarget.style.display = "none";
	}
	resizeIframe();
}

function onloadHandler() {
	targetOnChangeHandler();
	pageTypeOnChangeHandler();
	openForm();
	resizeIframe();
}

function resizeIframe() {
	var form = document.getElementById("menuItemForm");
	var iframe = window.frameElement;
	iframe.height = form.offsetHeight;
}

// end menu customization section.

// order navigation functions
function orderNavToggle(status) {
  var fiftyYears = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 50);
  toggleElementWithId('order_items_' + status ); 
  if (isShown('order_items_' + status) ) { 
    document.getElementById('collapse_img_' + status).src='images/minus.gif'; 
    setCookie( 'oNav' + status, 1, fiftyYears );
  } else {
    document.getElementById('collapse_img_' + status).src='images/plus.gif';
    if ( getCookie( 'oNav' + status ) ) {
      setCookie( 'oNav' + status, 0, fiftyYears );
    }
    removeCookie( 'oNav' + status );
  }
}

function initOrderNavTable() {
  var statuses = new Array('new','invoiced','pending','shipping_error','payment_error','payment_dispute');
  var x;
  for ( x in statuses ) {
    if ( document.getElementById( 'order_items_' + status ) != null &&
         getCookie( 'oNav' + statuses[x] ) 
       ) 
    {
      orderNavToggle(statuses[x]);
    }
  }
  hideElementWithId('orderNavigationTableLoading');
  showElementWithId('orderNavigationTable');
}

// functions for use in the order manager
function updateOrderContact(contactType, fullName, companyName, address1, address2, formattedPhoneNum, city, regionCode, postalCode, country)
{
	document.getElementById(contactType + 'FullName').innerHTML = fullName;
	document.getElementById(contactType + 'CompanyName').innerHTML = companyName;
	if (companyName && companyName!='')
	{
	  document.getElementById(contactType + 'CompanyNameRow').style.display="";
	}
	else
	{
	  document.getElementById(contactType + 'CompanyNameRow').style.display="none";
	}
	document.getElementById(contactType + 'Address1').innerHTML = address1;
  var address2Ele = document.getElementById(contactType + 'Address2');
  if (address2 == '')
  {
    address2Ele.style.display = 'none';
    address2Ele.style.visibility = 'hidden';
  }
  else
  {
    address2Ele.style.display = 'block';
    address2Ele.style.visibility = 'visible';
  }
  address2Ele.innerHTML = address2;
	document.getElementById(contactType + 'City').innerHTML = city;
	document.getElementById(contactType + 'RegionCode').innerHTML = regionCode;
	document.getElementById(contactType + 'PostalCode').innerHTML = postalCode;
	document.getElementById(contactType + 'Phone').innerHTML = formattedPhoneNum;
	document.getElementById(contactType + 'Country').innerHTML = country;
	if (country=='' || country=='United States' )
	{
	  document.getElementById(contactType + 'CountryRow').style.display="none";
	}
	else
	{
	  document.getElementById(contactType + 'CountryRow').style.display="";
	}
}



function viewOrderSubmit(formElement, orderTotal, orderId)
{
	if (!validateDateViewOrderSubmit())
	{
		return false;
	}

  var formAction =  document.getElementById('changeStatus').action;
  var paymentStatus = document.getElementById('paymentStatus').value;
//  alert('Total:'     + orderTotal +  '; orderId=' + orderId + '; form action=' + formAction);
  if (document.getElementById('orderStatus').value == 'cancel' &&
      formAction.indexOf('updateOrderStatus') >= 0)
  {
    var cancelDate = document.getElementById('cancelDate');  
    if (cancelDate && cancelDate.value != '')
    {
		  if (!validateDate(cancelDate.value))
		  {
		  	alert("Cancel date is invalid. Please use the format MM/DD/YYYY.");
				cancelDate.focus();
				cancelDate.select();
				return false;
		  }
    }

    // The UPDATE ORDER button was pressed and user want to cancel the order
    if (paymentStatus == 'PreAuth')
    {
      if (confirm('Note: The Pre-auth of $' + orderTotal + ' will be voided by cancelling this order.'))
      {
        document.getElementById('creditCardAction').value = 'void';
        document.getElementById('changeStatus').action = 'processCreditCardForOrder.hg?orderId=' + orderId;
        return true;
      }      
      return false;
    }
    else if (paymentStatus == 'Completed')
    {
      return confirm('Note: This is an invoiced order. Please refund $' + orderTotal + ' to the customer');  
    }
  } 
  else if (document.getElementById('orderStatus').value == 'refunded' &&
           formAction.indexOf('updateOrderStatus') >= 0) 
  {
    // The UPDATE ORDER button was pressed and user want to refund the order		
   	if (paymentStatus == 'Completed')
    {
 	    return confirm('Note: This is an invoiced order. Please refund $' + orderTotal + ' to the customer');
		}
  } 
  else if (document.getElementById('orderStatus').value == 'new' &&
           formAction.indexOf('updateOrderStatus') >= 0)
  {
    if (paymentStatus == 'Completed' && document.getElementById('creditCardAction'))
    {
      return confirm('Note: The amount of $' + orderTotal + ' has not been charged.\n' +
                     'Please use the payment gateway to charge the credit card manually.');
    }
  } 
  else if (formAction.indexOf('updateShippingChargeForOrder') >= 0)
  {
    // Apply the shipping and handling charge to the order
    return confirm('The shipping and handling charge will be applied to this order.');
  }
  else if (formAction.indexOf('processCreditCardForOrder') >= 0)
  {
  	var revertChangeStatusAction = 'updateOrderStatus.hg?orderId=' + orderId;

    // Check for voice auth button press.
    if (document.getElementById('creditCardAction').value == 'voiceAuth')
    {
      var voiceAuthCode = document.getElementById('voiceAuthCode');
		  if (voiceAuthCode.value.length == 0)
		  {
		    alert('Performing a Voice Auth Capture requires a Voice Authorization Code.');
		    voiceAuthCode.select();
	      document.getElementById('changeStatus').action = revertChangeStatusAction;
		    return false;
		  }
	    
		  var keepGoing = confirm('Note: The amount of $' + orderTotal + ' will be captured\n' +
		                          'using the supplied Voice Authorization Code.');
		  if (!keepGoing)
		  {
	      document.getElementById('changeStatus').action = revertChangeStatusAction;
      }
      else
      {
      	// Prevent form resubmit.
      	disableInputsOnCapture();
      }
	  
		  return keepGoing;
    }
    // The user want to pre-auth capture the payment for this order
    else if (paymentStatus == 'PreAuth')
    {      
      var keepGoing = confirm('Note: The Pre-auth of $' + orderTotal + ' will be captured.');   
      if (!keepGoing)
      {
        document.getElementById('changeStatus').action = revertChangeStatusAction;
      }
      else
      {
      	// Prevent form resubmit.
      	disableInputsOnCapture();
      }
      
      return keepGoing;
    }
    // The user want to capture the payment for this order
    else 
    {
      var keepGoing = confirm('Note: The amount of $' + orderTotal + ' will be captured.');
      if (!keepGoing)
      {
        document.getElementById('changeStatus').action = revertChangeStatusAction;
      }
      else
      {
      	// Prevent form resubmit.
      	disableInputsOnCapture();
      }
      
      return keepGoing;
    }
  }

	return true;
}

function validateDateViewOrderSubmit()
{
	var orderShipDate = document.getElementById('orderShipDate'); 
	if (orderShipDate && orderShipDate.value != '')
	{
		if (!validateDate(orderShipDate.value))
		{
			alert("Ship date is invalid. Please use the format MM/DD/YYYY.");
			orderShipDate.focus();
			orderShipDate.select();
			return false;
		}
	}

  var packageInfo = document.forms['changeStatus'].elements;
  for (var i=0; i<packageInfo.length; i++)
  {
    if (packageInfo[i].name.indexOf(".shipDateByString") > 0 && packageInfo[i].value != '')
    {
		  if (!validateDate(packageInfo[i].value))
		  {
		  	alert("Ship date is invalid. Please use the format MM/DD/YYYY.");
				packageInfo[i].focus();
				packageInfo[i].select();
				return false;
		  }
    }
  }

	return true;
}

function disableInputsOnCapture()
{
  // Attempt to disable the Pre-Auth Capture / Capture button (same Id for both).
  var btnCapture = document.getElementById('chargeCC');
  if (btnCapture)
  {
    btnCapture.disabled = true;
  }

  // Attempt to disable the Voice-Auth Capture button.
  var btnVoiceAuth = document.getElementById('voiceAuthCC');
  if (btnVoiceAuth)
  {
    btnVoiceAuth.disabled = true;
  }
  
  // Attempt to disable the Order Status select box.
  var selOrderStatus = document.getElementById('orderStatus');
  if (selOrderStatus)
  {
  	selOrderStatus.disabled = true;
  }
  
  // Attempt to disable the Payment Status select box.
  var selPaymentStatus = document.getElementById('paymentStatus');
  if (selPaymentStatus)
  {
  	selPaymentStatus.disabled = true;
  }
  
  // Attempt to disable the Update button.
  var btnUpdate = document.getElementById('updateOrder');
  if (btnUpdate)
  {
    btnUpdate.disabled = true;
  }
}

function orderStatusChange()
{
	var status = document.getElementById('orderStatus').value;
	var applyShippingCharge = document.getElementById('applyShippingCharge');
	var chargeCC = document.getElementById('chargeCC');
	var shippingCompleted = document.getElementById('shippingCompleted');

	if (status == 'shipped')
	{
		shippingCompleted.checked = true;
	}
  else if (status == 'cancel')
  {
	  showElementWithId('cancelDateRow');
	  document.getElementById('cancelDate').disabled = false;
	  
	  if (applyShippingCharge != null)            
	  {
	    document.getElementById('applyShippingCharge').style.visibility = "hidden";
	  }
	  if (chargeCC != null)
	  {
	    document.getElementById('chargeCC').style.visibility = "hidden";
	  }
  }
  else
  {
	  hideElementWithId('cancelDateRow');
	  document.getElementById('cancelDate').disabled = true;
	  if (applyShippingCharge != null)            
	  {
	    applyShippingCharge.style.visibility = "visible";
	  }
	  if (chargeCC != null)
	  {
	    chargeCC.style.visibility = "visible";
	  }
	  
	  if (shippingCompleted != null)
	  {
		  if (!shippingCompleted.disabled)
		  {
			shippingCompleted.checked = false;
		  }
	  }
	}
}
        
function shipCompleteStatusChange()
{
	var shippingCompleted = document.getElementById('shippingCompleted');
	if (shippingCompleted.checked)
	{
	 	document.getElementById('orderStatus').value = 'shipped';						
	}
	else
	{
		document.getElementById('orderStatus').value = 'invoiced';
	}
}

function paymentStatusChange(type)
{
  var prevVal = document.getElementById('previousPaymentStatus').value;
  var status = document.getElementById('paymentStatus').value;
  var paymentMethodValue = type;

    if (status == 'Completed')
    {
      if( paymentMethodValue == 'CreditCard')
      {
        if(!confirm("Have you captured the funds for this order?\n If you can see the Capture Funds button, you have not captured the payment for this order.\n If you mark the payment as Completed, you will lose the opportunity to capture the funds via QSC."))
        {
          document.getElementById('paymentStatus').options[prevVal].selected=true;
          document.getElementById('previousPaymentStatus').value = prevVal;
      	  document.getElementById('paymentStatus').blur();
          return;
        }
      }
    
      hideElementWithId('orderStatus');
      document.getElementById('orderStatus').disabled = true;      
      showElementWithId('orderInvoiced');
      document.getElementById('orderInvoiced').disabled = false;      
      hideElementWithId('cancelDateRow');
      document.getElementById('cancelDate').disabled = true;
    }
    else
    {
      hideElementWithId('orderInvoiced');
      document.getElementById('orderInvoiced').disabled = true;
      showElementWithId('orderStatus');
      document.getElementById('orderStatus').disabled = false;
    }
    document.getElementById('paymentStatus').blur();
}

  function changeAddress(optionValue, billShip)
  {
    if (billShip == 'billing')
    {
      document.getElementById('billFirstName').value = document.getElementById('firstName' + optionValue).value;
  	  document.getElementById('billMidInit').value = document.getElementById('midInit' + optionValue).value;
  	  document.getElementById('billLastName').value = document.getElementById('lastName' + optionValue).value;
  	  document.getElementById('billCompanyName').value = document.getElementById('companyName' + optionValue).value;
      document.getElementById('billEmail').value = document.getElementById('email' + optionValue).value;
      document.getElementById('billAddress1').value = document.getElementById('addressLine1' + optionValue).value;
      document.getElementById('billAddress2').value = document.getElementById('addressLine2' + optionValue).value;
      document.getElementById('billPhoneFullNumber').value = document.getElementById('phoneFullNumber' + optionValue).value;
      document.getElementById('billPhoneExtension').value = document.getElementById('phoneExtension' + optionValue).value;
      document.getElementById('billCity').value = document.getElementById('city' + optionValue).value;
      document.getElementById('billRegionCode').value = document.getElementById('state' + optionValue).value;
      document.getElementById('billPostalCode').value = document.getElementById('zip' + optionValue).value;
      
      /*
        Find the corresponding index of the country code
      */
      /*for(var i = 0; i &lt; document.getElementById('billCountryCode').options.length; i++)
      {
        if(document.getElementById('billCountryCode').options[i].value == document.getElementById('country' + optionValue).value )
        {
          document.getElementById('billCountryCode').selectedIndex = i;
          break;
        }
      }*/
      
    }
    else
    {
      document.getElementById('shipFirstName').value = document.getElementById('firstName' + optionValue).value;
  	  document.getElementById('shipMidInit').value = document.getElementById('midInit' + optionValue).value;
  	  document.getElementById('shipLastName').value = document.getElementById('lastName' + optionValue).value;
  	  document.getElementById('shipCompanyName').value = document.getElementById('companyName' + optionValue).value;
      document.getElementById('shipAddress1').value = document.getElementById('addressLine1' + optionValue).value;
      document.getElementById('shipAddress2').value = document.getElementById('addressLine2' + optionValue).value;
      document.getElementById('shipPhoneFullNumber').value = document.getElementById('phoneFullNumber' + optionValue).value;
      document.getElementById('shipPhoneExtension').value = document.getElementById('phoneExtension' + optionValue).value;
      document.getElementById('shipCity').value = document.getElementById('city' + optionValue).value;
      document.getElementById('shipRegionCode').value = document.getElementById('state' + optionValue).value;
      document.getElementById('shipPostalCode').value = document.getElementById('zip' + optionValue).value;
      /* document.getElementById('billCountryCode').selectedIndex = document.getElementById('country' + optionValue).selectedIndex; */

    }

    copyContact();
  }
  
  /*
    Disable "Shipping Method" selection if the order is international
  */
  
  /*function isInternational()
  {
    if( document.getElementById('shipCountryCode').
    options[document.getElementById('shipCountryCode').selectedIndex].value != 'US' )
    {
  //document.getElementById('shippingSelection').disabled = true;
  hideElementWithId('shippingBlock');
  showElementWithId('noShippingInfo');        
    }
    else
    {
      //document.getElementById('shippingSelection').disabled = false;
      showElementWithId('shippingBlock');
      hideElementWithId('noShippingInfo');   
    }
  } */

function copyContact()
{
  if($("#billIsShip").attr("checked"))
  {
	var countryCode = $('#billCountryCode').val();
	var regionCode = $('#billRegionCode').val();

    var shipCountryCode = $('#shipCountryCode').children("option[value='" + countryCode + "']");
    if (!shipCountryCode.attr("selected"))
    {
		shipCountryCode.attr("selected","selected");
	    getCountryRegions(countryCode, 'getCountryRegions.hg', [SHIPPING_REGION_DATA_DISABLED], regionCode);
    }
    else
  {
	  $("#shipRegionCode").children("option[value='" + regionCode + "']").attr("selected","selected");    
  }
  
  	$('#shipFirstName').val($('#billFirstName').val());
  	$('#shipMidInit').val($('#billMidInit').val());
  	$('#shipLastName').val($('#billLastName').val());  	
  	$('#shipCompanyName').val($('#billCompanyName').val());
    $('#shipAddress1').val($('#billAddress1').val());
    $('#shipAddress2').val($('#billAddress2').val());
    $('#shipPhoneFullNumber').val($('#billPhoneFullNumber').val());
    $('#shipPhoneExtension').val($('#billPhoneExtension').val());
    $('#shipCity').val($('#billCity').val());
    $('#shipPostalCode').val($('#billPostalCode').val());
    
    $(".ship-field").attr("disabled", "disabled");
  }
  else
  {
    $(".ship-field").removeAttr("disabled");
  }
}    

var BILLING_REGION_DATA = {id: 'billRegionCode', name: 'orderBean.billingInfo.regionCode', onchange: 'copyContact();', styleClass: 'formfield', disabled: false, divId: 'billRegionCodeDiv'};
var SHIPPING_REGION_DATA = {id: 'shipRegionCode', name: 'orderBean.shippingInfo.regionCode', styleClass: 'formfield ship-field', disabled: false, divId: 'shipRegionCodeDiv'};
var SHIPPING_REGION_DATA_DISABLED = {id: 'shipRegionCode', name: 'orderBean.shippingInfo.regionCode', styleClass: 'formfield ship-field', disabled: true, divId: 'shipRegionCodeDiv'};
function newOrderChangeAddress(optionValue, prefix, regionData)
{
  	var countryCode = $('#countryCode' + optionValue).val();
    var regionCode = $('#state' + optionValue).val();
    var option = $("select#" + prefix + "CountryCode").children("option[value='" + countryCode + "']");
    if (!option.attr("selected"))
    {
      option.attr("selected","selected");
	  if(prefix == 'bill' && $("#billIsShip").attr("checked"))
  	  {
	    getCountryRegions($("#" + prefix + "CountryCode").val(), 'getCountryRegions.hg', [BILLING_REGION_DATA, SHIPPING_REGION_DATA_DISABLED], regionCode);
	  }
	  else
	  {
	    getCountryRegions($("#" + prefix + "CountryCode").val(), 'getCountryRegions.hg', [regionData], regionCode);
	  }
    }
    else
    {
	  if(prefix == 'bill' && $("#billIsShip").attr("checked"))
	  {
	    $("select#" + BILLING_REGION_DATA.id).children("option[value='" + regionCode + "']").attr("selected","selected");
	    $("select#" + SHIPPING_REGION_DATA.id).children("option[value='" + regionCode + "']").attr("selected","selected");
	  }
	  else
	  {
	    $("select#" + regionData.id).children("option[value='" + regionCode + "']").attr("selected","selected");	  
	  }
    }
  	$('#' + prefix + 'FirstName').val($('#firstName' + optionValue).val());
  	$('#' + prefix + 'MidInit').val($('#midInit' + optionValue).val());
  	$('#' + prefix + 'LastName').val($('#lastName' + optionValue).val());
  	$('#' + prefix + 'CompanyName').val($('#companyName' + optionValue).val());
    $('#' + prefix + 'Email').val($('#email' + optionValue).val());
    $('#' + prefix + 'Address1').val($('#addressLine1' + optionValue).val());
    $('#' + prefix + 'Address2').val($('#addressLine2' + optionValue).val());
    $('#' + prefix + 'PhoneFullNumber').val($('#phoneFullNumber' + optionValue).val());
    $('#' + prefix + 'PhoneExtension').val($('#phoneExtension' + optionValue).val());
    $('#' + prefix + 'City').val($('#city' + optionValue).val());
    $('#' + prefix + 'PostalCode').val($('#zip' + optionValue).val());

	if(prefix == 'bill' && $("#billIsShip").attr("checked"))
  {
	    $('#shipCountryCode').children("option[value='" + countryCode + "']").attr("selected","selected");
	    $("#shipRegionCode").children("option[value='" + regionCode + "']").attr("selected","selected");    
	  	$('#shipFirstName').val($('#billFirstName').val());
	  	$('#shipMidInit').val($('#billMidInit').val());
	  	$('#shipLastName').val($('#billLastName').val());  	
	  	$('#shipCompanyName').val($('#billCompanyName').val());
	    $('#shipAddress1').val($('#billAddress1').val());
	    $('#shipAddress2').val($('#billAddress2').val());
	    $('#shipPhoneFullNumber').val($('#billPhoneFullNumber').val());
	    $('#shipPhoneExtension').val($('#billPhoneExtension').val());
	    $('#shipCity').val($('#billCity').val());
	    $('#shipPostalCode').val($('#billPostalCode').val());
    }
}

function changeNewOrderCountry(countryCode, prefix, regionData)
{
  if(prefix == 'bill' && $("#billIsShip").attr("checked"))
  {
	$('#shipCountryCode').children("option[value='" + countryCode + "']").attr("selected","selected");
	getCountryRegions(countryCode, 'getCountryRegions.hg', [BILLING_REGION_DATA, SHIPPING_REGION_DATA_DISABLED]);    
  }
  else
  {
	getCountryRegions(countryCode, 'getCountryRegions.hg', [regionData]);    
  }
}

function showPaymentType()
{
  var paymentMethodElement = document.getElementById('paymentMethod').value;

//  alert('paymentMethod=' + paymentMethodElement);
  
  var rollDownPaymentType = function()
  {
    var paymentMethodElement = document.getElementById('paymentMethod').value;

    if(paymentMethodElement == 'CreditCard' || paymentMethodElement == 'simpleCreditCard')
    {
      rollDown('creditCardPaymentTable', 50);
    }
    else if(paymentMethodElement == 'ECheck')
    {
      rollDown('eCheckPaymentTable', 50);
    }
  }
      
  if(isShown('creditCardPaymentTable'))
  {
  
//    alert('CreditCardTable is shown');
  
    if(paymentMethodElement != 'CreditCard' && paymentMethodElement != 'simpleCreditCard')
    {
      document.getElementById('paymentMethod').disabled = true;
      rollUp('creditCardPaymentTable', 50, rollDownPaymentType);
      document.getElementById('paymentMethod').disabled = false;
    }
  }
  else if(isShown('eCheckPaymentTable'))
  {
    if(paymentMethodElement != 'ECheck')
    {
      document.getElementById('paymentMethod').disabled = true;
      rollUp('eCheckPaymentTable', 50, rollDownPaymentType);
      document.getElementById('paymentMethod').disabled = false;
    }
  } 
  else 
  {
    if(paymentMethodElement == 'CreditCard' || paymentMethodElement == 'simpleCreditCard')  
    {
      document.getElementById('paymentMethod').disabled = true;
      rollDown('creditCardPaymentTable', 50);
      document.getElementById('paymentMethod').disabled = false;
    }
    else if(paymentMethodElement == 'ECheck')
    {
      document.getElementById('paymentMethod').disabled = true;
      rollDown('eCheckPaymentTable', 50);
      document.getElementById('paymentMethod').disabled = false;
    }
  }
}

function getUserContacts()
{

  var userId = document.getElementById('userId').value;

  var userEmail = document.getElementById('userId').options[document.getElementById('userId').selectedIndex].text;
  
  userEmail = userEmail.substring(userEmail.indexOf("(")+1, userEmail.indexOf("\)"));
  
//  alert('User Email:[' + userEmail + ']');

  if (userId != '') 
  {
    var uri = "newOrderHelper.hg?action=userContacts&userId=" + userId;

    var xmlDoc =  XmlDocument.create();
    xmlDoc.loadXML(getXMLFromHelper(uri));

    var contacts = xmlDoc.getElementsByTagName("contact");
//  var fullName = contacts.getAttribute("fullName");
//  document.getElementById('billName').value = fullName;

    //////// Set the billing contacts options
    var billingContacts =   document.getElementById('billingContacts').options;

//    alert("Billing length before remove:" + billingContacts.length);

    for(var i = 0; i < billingContacts.length; i++)
    {
      billingContacts[i] = null;
    }
    billingContacts[0] = new Option("None", "0", false, false);    

    // Element that contains contact information
    var contactInfo = document.getElementById('contactInfo');
    var contactInfoContent = "";
    
    for(var i = 0; i < contacts.length; i++)
    {
      var firstName = contacts[i].getAttribute("firstName");
      var midInit = contacts[i].getAttribute("midInit");
      var lastName = contacts[i].getAttribute("lastName");
      var companyName = contacts[i].getAttribute("companyName");
      var text = contacts[i].getAttribute("nickName");
      var email = contacts[i].getAttribute("email");
      var addressLine1 = contacts[i].getAttribute("addressLine1");
      var addressLine2 = contacts[i].getAttribute("addressLine2");
      var phoneFullNumber = contacts[i].getAttribute("phoneFullNumber");
      var phoneExtension = contacts[i].getAttribute("phoneExtension");
      var city = contacts[i].getAttribute("city");
      var state = contacts[i].getAttribute("state");
      var zip = contacts[i].getAttribute("zip");
      var countryCode = contacts[i].getAttribute("countryCode");

      var value = contacts[i].getAttribute("id");
      billingContacts[i+1] = new Option(text, value, false, false);

      // Set the contact information into hidden fields
      contactInfoContent = 
        contactInfoContent + 
        '<input type="hidden" name="firstName' + value + '" id="firstName' + value + '" value="' + firstName  +'" disabled="disabled"/>' +
        '<input type="hidden" name="midInit' + value + '" id="midInit' + value + '" value="' + midInit  +'" disabled="disabled"/>' +
        '<input type="hidden" name="lastName' + value + '" id="lastName' + value + '" value="' + lastName  +'" disabled="disabled"/>' +
        '<input type="hidden" name="companyName' + value + '" id="companyName' + value + '" value="' + companyName  +'" disabled="disabled"/>' +
        '<input type="hidden" name="nickName' + value + '" id="nickName' + value + '" value="' + text  +'" disabled="disabled"/>' +
        '<input type="hidden" name="email'    + value + '" id="email'    + value + '" value="' + userEmail +'" disabled="disabled"/>' +
        '<input type="hidden" name="addressLine1' + value + '" id="addressLine1' + value + '" value="' + addressLine1 +'" disabled="disabled"/>' +
        '<input type="hidden" name="addressLine2' + value + '" id="addressLine2' + value + '" value="' + addressLine2 +'" disabled="disabled"/>' +
        '<input type="hidden" name="phoneFullNumber' + value + '" id="phoneFullNumber' + value + '" value="' + phoneFullNumber +'" disabled="disabled"/>' +
        '<input type="hidden" name="phoneExtension'   + value + '" id="phoneExtension'   + value + '" value="' + phoneExtension   +'" disabled="disabled"/>' +
        '<input type="hidden" name="city'  + value + '" id="city'  + value + '" value="' + city  +'" disabled="disabled"/>' +
        '<input type="hidden" name="state' + value + '" id="state' + value + '" value="' + state +'" disabled="disabled"/>' +
        '<input type="hidden" name="zip' + value + '" id="zip'   + value + '" value="' + zip   +'" disabled="disabled"/>' +
        '<input type="hidden" name="countryCode' + value + '" id="countryCode' + value + '" value="' + countryCode + '" disabled="disabled"/>'
    }
    contactInfo.innerHTML =  contactInfoContent;

    //////// Set the shipping contacts options
    var shippingContacts =   document.getElementById('shippingContacts').options;

//    alert("Shipping Length before remove: " + shippingContacts.length);

    for(var i = 0; i < shippingContacts.length; i++)
    {
      shippingContacts[i] = null;
    }  
    shippingContacts[0] = new Option("None", "0", false, false);    
    for(var i = 0; i < contacts.length; i++)
    {
      var text = contacts[i].getAttribute("nickName");
      var value = contacts[i].getAttribute("id");
      shippingContacts[i+1] = new Option(text, value, false, false);
    }

//    alert("After replace - Billing length:" + billingContacts.length + "; Shipping Length: " + shippingContacts.length);

  }
  else
  { 
    //////// Set the billing contacts options
    var billingContacts =   document.getElementById('billingContacts').options;

//    alert("Billing length before remove:" + billingContacts.length);

    for(var i = 0; i < billingContacts.length; i++)
    {
      billingContacts[i] = null;
    }  
    billingContacts[0] = new Option("None", "0", false, false);    
    //////// Set the shipping contacts options
    var shippingContacts =   document.getElementById('shippingContacts').options;

//    alert("Shipping Length before remove: " + shippingContacts.length);

    for(var i = 0; i < shippingContacts.length; i++)
    {
      shippingContacts[i] = null;
    }
    shippingContacts[0] = new Option("None", "0", false, false);

//    alert("After replace - Billing length:" + billingContacts.length + "; Shipping Length: " + shippingContacts.length);
  }
}


function getXMLFromHelper(uri, unique)
{
  if ( unique ) {
    // append a timestamp to avoid browser caching
    var timestamp = new Date();
    uri = uri+(uri.indexOf("?") > 0 ? "&" : "?")+"timestamp="+timestamp.getTime();
  }

  var xmlHttp = XmlHttp.create();

  xmlHttp.open("GET", uri, false);
  xmlHttp.send(null);
  return xmlHttp.responseText;
}


/***********************************************************************************************************/
/*                                               New Order's Items                                         */
/***********************************************************************************************************/

function newOrderMultiItems(fromBox)
{
  var fBox = document.getElementById(fromBox);
  
  if (fBox)
  {
    var fBoxOptions = fBox.getElementsByTagName('OPTION');
    var fBoxSelected = new Array();

    if (fBoxOptions && fBoxOptions.length > 0)
    {     
      var index = 0;
      for (var i = 0; i < fBoxOptions.length; i++)
      {
        if (fBoxOptions[i].selected && fBoxOptions[i].value != '')
        {
          fBoxSelected[index++] = fBoxOptions[i];
        }
      }

      if (fBoxSelected.length > 0)
      {
        var tbody = document.getElementById("itemsInOrderTBody");
        hideElementWithId('noOrderItems');
        
        
        // Set the URI 
        var uri = "newOrderHelper.hg?action=productOptions&productId=";
          
        for (var i = 0; i < fBoxSelected.length; i++)
        {
          var numberOfItemsInOrder = orderItemCount();
          var now = new Date().getTime();
          
//          alert('Number of item in order:' + numberOfItemsInOrder);
//          alert('Now:' + now);

          var productId = fBoxSelected[i].value;
          var orderItemRow = document.createElement("tr");
          
//          orderItemRow.setAttribute("id", "orderItem"+fBoxSelected[i].value);
          orderItemRow.setAttribute("id", "orderItem"+now);
          orderItemRow.setAttribute("height", "25");


          // Get the product options for this product
          var xmlDoc =  XmlDocument.create();

//          alert('"' + uri + productId + '"');

          xmlDoc.loadXML(getXMLFromHelper(uri + productId));    


          // Create the option list HTML
          var optionHTML = '<table border="0" cellspacing="0" width="100%" cellpadding="1" style="">';

          var options = xmlDoc.getElementsByTagName("option");

//          alert('Option length:' + options.length);

          optionHTML = optionHTML + 
            "<input id=\"orderItemOptionLength_"+now+"\" type=\"hidden\" value=\""+options.length+"\" disabled=\"disabled\"/>";

          for(var ii= 0; ii < options.length; ii++)
          {
            var optionId = options[ii].getAttribute("id");
            var optionLabel = options[ii].getAttribute("label");

//            alert('Option Id:' + optionId + 'Label:' + document.getElementById(optionLabel).value);

            var optionValueHTML = 
              "<input name=\"orderItems[" + numberOfItemsInOrder + "].options[" + ii + "].optionId\" type=\"hidden\" " +
              "id=\"orderItemOptionId_" + now + "_" + ii + "\" value=\""+optionId+"\"/>"+
              "<select name=\"orderItems[" + numberOfItemsInOrder + "].options[" + ii + "].optionValueId\" " +
              "id=\"orderItemOption_"+now+"_" + ii + "\" class=\"formfield\">";

            var optionValues = options[ii].childNodes;        

            for (var iii=0; iii<optionValues.length; iii++)
            {
              var tagName = optionValues[iii].tagName;
              var valueLabel = optionValues[iii].getAttribute("label");
              var valueId = optionValues[iii].getAttribute("id");
			  var increment = optionValues[iii].getAttribute("increment");

			  // get the price increment amount, and modify the label for display
			  var amount = parseFloat(increment);
			  if (amount > 0.0)
			  {
				valueLabel = valueLabel + ' (+$' + increment + ')';
			  }
			  else if (amount < 0.0)
			  {
				valueLabel = valueLabel + ' (-$' + increment.substring(1, increment.length) + ')';
			  }
			  
              optionValueHTML = 
                optionValueHTML +
                "<option value=\"" + valueId + "\">" + htmlEscape(valueLabel) + "</option>";              
            }
            var optionValueHTML = optionValueHTML + "</select>";
            
            optionHTML = 
              optionHTML +
              '<tr>' +
              '  <td width="40%" align="right">' + htmlEscape(optionLabel) + ':</td>' +
              '  <td>' + optionValueHTML + '</td>' +
              '</tr>';
          }

          optionHTML = optionHTML + '</table>';

          var orderItemRowCell = document.createElement("td");
          var tableHTML = "<table border=\"0\" cellspacing=\"0\" width=\"100%\" cellpadding=\"0\" style=\"\" id=\"transitionTable"+now+"\" ";

          if(isIE())
          {
            tableHTML += "style=\"visibility='hidden'; display='none';\" ";
          }
          tableHTML += ">"+
          "  <tr>" + 
          "    <input id=\"orderItemId_"+now+"\" type=\"hidden\" name=\"orderItems["+numberOfItemsInOrder+"].productId\" value=\""+productId+"\"/>"+
          "    <input id=\"orderItemPart_"+now+"\" type=\"hidden\" name=\"orderItems["+numberOfItemsInOrder+"].partNumber\" value=\""+htmlEscape(fBoxSelected[i].getAttribute("partnumber"))+"\"/>"+
          "    <input id=\"orderItemLabel_"+now+"\" type=\"hidden\" name=\"orderItems["+numberOfItemsInOrder+"].label\" value=\""+htmlEscape(fBoxSelected[i].getAttribute("label"))+"\"/>"+
          "    <td align=\"left\" id=\"bulkProductTitle"+now+"\">"+htmlEscape(fBoxSelected[i].text)+"</td>" +
          "    <td align=\"left\" valign=\"top\" width=\"22\"><input class=\"formfield\" id=\"orderItemQty_"+now+"\" type=\"text\" value=\"1\" name=\"orderItems["+numberOfItemsInOrder+"].qty\" size=\"3\"/></td>" + 
          "    <td align=\"right\" valign=\"top\" width=\"55\"><img id='deleteItem"+now+"' src='images/ibtn_delete.gif' onClick='deleteProductFromOrder(\""+now+"\",\""+fromBox+"\");' onMouseOut='swapImageRestore()' onMouseOver=\"swapImage('deleteItem"+now+"','','images/ibtn_delete_over.gif',1)\"/></td>"+
          "  </tr>"+

          "  <tr>" +
          optionHTML +
          "  </tr>" +

          "</table>";
          orderItemRowCell.innerHTML = tableHTML;
          tbody.appendChild(orderItemRow);           
          orderItemRow.appendChild(orderItemRowCell);
          if(isIE())
          {         
//            transition('transitionTable'+fBoxSelected[i].value);
            transition('transitionTable'+now);
          }
          else
          {
            // manually reset height after new row has been added - mozilla will not resize otherwise
            document.getElementById('orderItemTable').height = document.getElementById('orderItemTable').offsetHeight;          
          }
//          fBox.removeChild(fBoxSelected[i]);
        }
      }
    }
  }
}

function orderItemCount()
{
  var tbody = document.getElementById("itemsInOrderTBody");
  var tableRows = tbody.getElementsByTagName("TR");
  var count = 0;
  for(var i = 0; i < tableRows.length; i++)
  {
    if(tableRows[i].getAttribute("id") && tableRows[i].getAttribute("id").indexOf("orderItem") == 0)
    {
      count++;
    }
  }
  return count;
}

function deleteProductFromOrder(id, returnSelectBoxId)
{
  var tbody = document.getElementById("itemsInOrderTBody");
  var orderItemRow = document.getElementById('orderItem'+id);

  //step on name - browsers send hidden input fields even when parent node is removed.
  var orderItemIdElement = document.getElementById('orderItemId_'+id);
  if(orderItemIdElement && orderItemIdElement.name)
  {
    orderItemIdElement.name = "";
  }
    
  tbody.removeChild(orderItemRow);
  realignOrderItem(tbody);
  if(orderItemCount() == 0)
  {
    showElementWithId('noOrderItems');
  }
}

function realignOrderItem(tbody)
{
  var tableRows = tbody.getElementsByTagName("TR");
  var index = 0;

  for(var i = 0; i < tableRows.length; i++)
  {
    var potentialOrderItem = tableRows[i].getAttribute("id");

//    alert('In recalculateSortOrder, potentialOrderItem=' + potentialOrderItem);

    if(potentialOrderItem && potentialOrderItem.indexOf("orderItem") == 0)
    {
      var id = potentialOrderItem.substring("orderItem".length, potentialOrderItem.length);
      var productId = document.getElementById("orderItemId_"+id).value;

//      alert('In recalculateSortOrder, id=' + id + '; i=' + i + ';index=' + index + ';productId=' + productId);
      
      var orderItemIdElement = document.getElementById("orderItemId_"+id);
      if(orderItemIdElement)
      {
        orderItemIdElement.name="orderItems[" + index + "].productId";

//        alert('After reset, productId=' + orderItemIdElement.name);
      }

      var orderItemQtyElement = document.getElementById("orderItemQty_"+id);
      if(orderItemQtyElement)
      {
        orderItemQtyElement.name="orderItems[" + index + "].qty";

//        alert('After reset, qty=' + orderItemQtyElement.name);
      }
      
      var orderItemPartElement = document.getElementById("orderItemPart_"+id);
      if(orderItemPartElement)
      {
        orderItemPartElement.name="orderItems[" + index + "].partNumber";
      }
      
      var orderItemLabelElement = document.getElementById("orderItemLabel_"+id);
      if(orderItemLabelElement)
      {
        orderItemLabelElement.name="orderItems[" + index + "].label";
      }

      var orderItemOptionLength = document.getElementById("orderItemOptionLength_" + id).value;
      for (var ii=0; ii<orderItemOptionLength; ii++)
      {
        var orderItemOptionValue = document.getElementById("orderItemOption_" + id + "_" + ii);
        var orderItemOptionId = document.getElementById("orderItemOptionId_" + id + "_" + ii);
        orderItemOptionValue.name = "orderItems[" + index + "].options[" + ii + "].optionValueId";
        orderItemOptionId.name = "orderItems[" + index + "].options[" + ii + "].optionId";

//        alert('After reset option[' + ii + ']=' + orderItemOptionValue.name);
      }

      index = index + 1;
    }
  }
}

function newOrderSubmit(formElement)
{
  var result = validateAddress(formElement, "orderBean.billingInfo") && validateAddress(formElement, "orderBean.shippingInfo");

//  alert('Payment Method is (' + document.getElementById("paymentMethod").value + ')');
//  alert('validation result=' + result);
//var tempText = '';
//var allElements = formElement.elements;
//for (var index=0; index<formElement.length; index++)
//{
//  tempText = tempText + index + '. name=' + allElements[index].name + '\n';
//  if (index!=0 && index%20 == 0)
//  {
//    alert("Form elements:\n" + tempText);
//    tempText = '';
//  }
//  else if (index == formElement.length-1)
//  {
//    alert("Form elements:\n" + tempText);  
//  }
//}   
  if (result)
  {    
    if (formElement['orderItems[0].productId'] == null)
    {
      alert('Please select an item for your order');
      document.getElementById("availableProducts").focus();  
      return false;
    }
    else if (!validateAddOrderItemQty(formElement))
    {
      return false;
    }
    else if (document.getElementById("shippingMethod").value == "")
    {
      alert('Please select your shipping method.');
      document.getElementById("shippingMethod").focus();  
      return false;
    } 
    else if (document.getElementById("paymentMethod").value == "")
    {
      alert('Please select your payment type.');
      document.getElementById("paymentMethod").focus();  
      return false;
    }
    else if (document.getElementById("userId").value == "-1" && document.getElementById("paymentMethod").value == "payPal")
    {
      alert('PayPal is only available for registered user. Please select another payment type');
      document.getElementById("").focus();  
      return false;
    }
    else if (document.getElementById("paymentMethod").value == "CreditCard")
    {
      return validateCreditCard(formElement, 'orderBean.');                
    }
    else if (document.getElementById("paymentMethod").value == "ECheck")
    {
      return validateECheck(formElement, 'orderBean.');                
    }
    else
    {
      return true;
    }
  } 
  else
  {    
    return false;
  }
}

/***********************************************************************************************************/
/*                                                Mailing Labels                                           */
/***********************************************************************************************************/

function mailingLabelPostUpdate(uri) {
  var xmlDoc =  XmlDocument.create();
  var xml = getXMLFromHelper( uri, 1 ); 
  xmlDoc.loadXML(xml);
  
  var rootElement = xmlDoc.getElementsByTagName("data")[0];
  if (rootElement)
  {
    return parseInt( rootElement.getElementsByTagName("newCount")[0].childNodes[0].nodeValue );
  } else {
    return -1;
  }
}

function mailingLabelUpdateValue( orderId, type, baseURI ) {
  var uri = baseURI + "?orderId=" + orderId + "&addressType=" + type;
  
  var newCount = mailingLabelPostUpdate( uri );
  
  if (newCount != -1)
  {
    var cell = document.getElementById("labelValue_" + orderId + "_" + type);
    if (cell)
    {
        cell.value = newCount;
    }
  }

}

function mailingLabelPlus(orderId, type) {
  mailingLabelUpdateValue(orderId, type, "addAddressToExportList.hg");
}

function mailingLabelMinus(orderId, type) {
  mailingLabelUpdateValue(orderId, type, "removeAddressFromExportList.hg");
}

function mailingLabelClear(orderId, type) {
  mailingLabelUpdateValue(orderId, type, "clearAddressFromExportList.hg");
}

function mailingLabelToggle(orderId, type, elementId)
{
  var element = document.getElementById(elementId);
  
  if (element)
  {
      if (element.checked)
      {
        mailingLabelPlus(orderId, type);
      } else {
        mailingLabelClear(orderId, type);  
      }
  }
  
}

function mailingLabelBulkUpdate( elementId, orderId, type ) 
{

  var element = document.getElementById(elementId);
  if (element)
  {
      var count = element.value;
      mailingLabelClear(orderId, type);
      var uri = "addAddressToExportList.hg?orderId=" + orderId + "&addressType=" + type + "&items=" + count;
      var newCount = mailingLabelPostUpdate( uri );
  }
}

/***********************************************************************************************************/
/*                                                Email Notifications                                      */
/***********************************************************************************************************/

function resendDownloadEmail(orderId)
{
  var date = new Date();
  var uri = "resendDownloadEmail.hg?orderId=" + orderId + "&nocache=" + date.getHours() + date.getMinutes() + date.getSeconds();
  var xml = getXMLFromHelper( uri, 1 ); 
  var xmlDoc =  XmlDocument.create();

  xmlDoc.loadXML(xml);
  
  var rootElement = xmlDoc.getElementsByTagName("data")[0];
  if (rootElement && (rootElement.getElementsByTagName("sent")[0].childNodes[0].nodeValue == 'true'))
  {
    alert("Email successfully sent to " + rootElement.getElementsByTagName("emailAddress")[0].childNodes[0].nodeValue);
  } 
  else 
  {
    alert("Unable to send Email.");
  }
}

function resendEmail(invoiceId)
{
	var date = new Date();
	var uri = "resendEmail.hg?invoiceId=" + invoiceId + "&nocache=" + date.getHours() + date.getMinutes() + date.getSeconds();
  	var xmlHttp = XmlHttp.create();
  	xmlHttp.open("GET", uri, false);
  	xmlHttp.send(null);
  	alert("An e-mail notification has been sent to the customer."); 
}

/************************************************************************************/
/*                     Order Manager - View and Search Orders                       */
/************************************************************************************/
function displayNewPackage(packageId, url, numOfPackage)
{
  var fullURL = url + '?packageId=' + packageId + '&position=' + numOfPackage;
  xmlLoader(fullURL, displayNewPackageHandler);
}

function displayNewPackageHandler(xmlHttp)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);

	// Display error message
	displayShippingPackageError(xmlDoc);

	// Display the new package
	//alert(xmlElementToString(xmlDoc));

  var pid = xmlDoc
  	.getElementsByTagName("shippingPackage")[0]
  	.firstChild.getAttribute('id')
	.split('_')[1];

  var dateFieldId = "package_"+pid+"_shipDate";

  var dateField;
  var inputs = xmlDoc.getElementsByTagName('input');
  
  for ( var i=0, il=inputs.length; i<il; i++) {
  	var input_field = inputs[i];
  	if (input_field && input_field.nodeType && input_field.getAttribute('id')==dateFieldId) {
		dateField = input_field;
	}
  }
  
  //package_2819_shipDate
  if (dateField && dateField.getAttribute('value')=="") {
	var d = new Date();
	
	var curr_date = d.getDate();						
	var curr_month = d.getMonth()+1;						
	var curr_year = d.getFullYear();
	
	dateField.setAttribute("value", curr_month + "/" + curr_date + "/" + curr_year);
  }	
  
  var the_package = xmlDoc.getElementsByTagName("shippingPackage")[0].firstChild;
  
  var div = document.createElement("div");
  div.innerHTML = xmlElementToString(the_package);
  var packageSection = document.getElementById('packageSection');
  packageSection.appendChild(div);
	// Reset the shipping_content height to display correctly in FF
  document.getElementById('shipping_content').style.height="";
}

function displayUpdatePackage(packageId, url)
{
  var fullURL = url + '?packageId=' + packageId;
  xmlLoader(fullURL, displayUpdatePackageHandler);
}

function displayUpdatePackageHandler(xmlHttp)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);

	// Display error message
	displayShippingPackageError(xmlDoc);
	
	// display updated package content  
  var packageId = xmlDoc.getElementsByTagName("packageId")[0].firstChild.data;
  var newContent = xmlDoc.getElementsByTagName("packageContent")[0].firstChild;
	var content = document.getElementById('packageContent_' + packageId);
	content.innerHTML = xmlElementToString(newContent);

	// Reset the shipping_content height to display correctly in FF
  document.getElementById('shipping_content').style.height="";
}

function removeShippingPackage(packageId, orderId, url)
{
  if (confirm('Are you sure you want to remove this package? Items in this package will no longer be associated \nwith a package.  You will need to reassign the items to a new package.'))
	{
	  var position = document.getElementById('packageLabel_' + packageId).firstChild.data;
	  var fullURL = url + '?packageId=' + packageId + '&orderId=' + orderId + '&position=' + position;
	  xmlLoader(fullURL, displayRemovePackageHandler);
	}
}

function displayRemovePackageHandler(xmlHttp)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);  

	// display error message
	displayShippingPackageError(xmlDoc);

  var packageId = xmlDoc.getElementsByTagName("packageId")[0].firstChild.data;
	var position = xmlDoc.getElementsByTagName("packagePosition")[0].firstChild.data;
	var numOfPackage = xmlDoc.getElementsByTagName("numOfPackage")[0].firstChild.data;
  var the_package = document.getElementById('package_' + packageId);
  the_package.style.fontSize = "1px";
  the_package.style.lineHeight = "0px";
  the_package.innerHTML = "&#160;";
	
	// Reset the shipping_content height to display correctly in FF
  document.getElementById('shipping_content').style.height="";

	// Update the package number
  var start = position - 0;
  var end = numOfPackage - 0;
  while(start<=end)
  {
    var tmp = start;
    start += 1;
    var packageIdByPos = document.getElementById('packageIdByPos_' + start);
    var packageLabel = document.getElementById('packageLabel_' + packageIdByPos.value);
    packageLabel.innerHTML = tmp;
    packageIdByPos.id = 'packageIdByPos_' + tmp;

		// Update pacakge number in the popup title label
    var popupTitleEle = document.getElementById('editPackagePopup_'+packageIdByPos.value+'-title-bar');
    var popupTitleBar = popupTitleEle.firstChild.data;
    var newTitle = 'Package ' + tmp;
    var titleLabel = popupTitleBar.replace(/Package \d+/gi, newTitle);
    popupTitleEle.innerHTML = titleLabel;
  }
}

function displayShippingPackageError(xmlDoc)
{
	// unpacked content error message
	var error = xmlDoc.getElementsByTagName("unpackedContentErrorMesage");
	var errorSection = document.getElementById('unpackedContentError');
	if (error.length > 0)
	{
		// there is an error, display the error message
    errorSection.style.lineHeight = "normal";
		errorSection.innerHTML = xmlElementToString(error[0].firstChild);
	}  
	else
	{
		errorSection.innerHTML = "";
    errorSection.style.lineHeight = "0px";
	}	

	// overpacked content error message
	var error = xmlDoc.getElementsByTagName("overpackedContentErrorMesage");
	var errorSection = document.getElementById('overpackedContentError');
	if (error.length > 0)
	{
		// there is an error, display the error message
    errorSection.style.lineHeight = "normal";
		errorSection.innerHTML = xmlElementToString(error[0].firstChild);
	}  
	else
	{
		errorSection.innerHTML = "";
    errorSection.style.lineHeight = "0px";
	}
}

// updateElemId - the element whose innerHTML will be updated with the loaded default value.
function retrieveForcedCcNumber(orderId, buttonElem, updateElemId)
{
  var updateElem = document.getElementById(updateElemId);
  var fullURL = 'retrieveForcedCreditCardNumber.hg?orderId=' + orderId;
  xmlLoader(fullURL, retrieveForcedCcNumberHandler, updateElemId);
}
function retrieveForcedCcNumberHandler(xmlHttp, updateElementId)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);  

  var ccNode = xmlDoc.getElementsByTagName("creditCardNumber")[0];
  var creditCardNumber = "";
  if (ccNode.childNodes.length > 0)
  {
    creditCardNumber = ccNode.firstChild.data;
  }
  var ccNode = xmlDoc.getElementsByTagName("statusMessage")[0];
  var statusMessage = "";
  if (ccNode.childNodes.length > 0)
  {
    statusMessage = ccNode.firstChild.data;
  }
  if (updateElementId)
  {
    var ccDiv = document.getElementById(updateElementId)
    if (ccDiv)
    {
      ccDiv.innerHTML=creditCardNumber + "  ("+statusMessage+")";
    }
  }
}

/**
These are utility functions for the admin payment screens
*/
function verifyGateway(gatewayType, userName, password, signature)
{
	var date = new Date();
	var uri = "verifyGateway.hg?gatewayType=" + gatewayType + "&userName=" + userName + "&password=" + password + "&nocache=" + date.getHours() + date.getMinutes() + date.getSeconds();
	if ( signature !== null && signature!=="" ){
		uri += "&signature=" + signature;
	}
  	var xmlHttp = XmlHttp.create();
  	xmlHttp.open("GET", uri, false);
  	xmlHttp.send(null);
  	alert(xmlHttp.responseText.replace(/^[\s]+/g, "")); 
}

function verifyPayPalExpressGateway()
{ 
  var userName = strTrim(document.getElementById("bean.username").value);
  var password = strTrim(document.getElementById("bean.password").value);
  var signature = strTrim(document.getElementById("bean.signature").value);
  if (userName == "" || password == "" || signature == "") 
  	alert("Account Username, Password and Signature cannot be blank.");
  else
  	verifyGateway("PAYPALEXPRESS", userName, password, signature);
}

function verifyIMSGateway()
{ 
  var userName = document.getElementById("Attributes(userName)").value;
  var password = document.getElementById("Attributes(password)").value;
  if (userName == "" || password == "") 
  	alert("Account Username and Account Password cannot be blank.");
  else
  	verifyGateway("IMS", userName, password);
}

function verifyChaseGateway()
{ 
  var userName = document.getElementById("Attributes(userName)").value;
  if (userName == "") 
  	alert("Merchant Account Number cannot be blank.");
  else
  	verifyGateway("CHASE", userName);
}

function verifyAuthorizeNETGateway()
{ 
  var userName = document.getElementById("Attributes(loginId)").value;
  var password = document.getElementById("Attributes(tranKey)").value;
  if (userName == "" || password == "")
  	alert("Login ID and Transaction Key cannot be blank.");
  else  
  	verifyGateway("AUTHORIZE.NET", userName, password);
}

function verifyQbmsGateway()
{
	verifyGateway("QBMS", "", "");
}

function verifyVeloCTGateway()
{
	var userName = document.getElementById("Attributes(accountId)").value;
	if (userName == "")
	{
		alert("Account ID cannot be blank.");
	}
	else
	{
		verifyGateway("VELOCT", userName, "");
	}
}
/***********************************************************************************************************/
/*                                             ATTRIBUTES                                                  */
/***********************************************************************************************************/

/**
 * This function is used by the attribute tab to add an attribute to the
 * overall form.
 */
function addNewAttributeToProductEditorForm()
{
  var selectBox = document.getElementById('newAttributeName');
  if (selectBox)
  {
    var tBody = document.getElementById('selectedAttributesTbody');
    if (tBody)
    {
      var trTag = document.createElement("tr");
      trTag.setAttribute("height", "25");
      if(tBody.childNodes.length % 2 == 0)
      {
        trTag.className = "selection-row2";
      }
      else
      {
        trTag.className = "selection-row1";
      }
      
      var tdTag1 = document.createElement("td");
      var tdTag2 = document.createElement("td");
      var tdTag3 = document.createElement("td");
      var tdTag4 = document.createElement("td");
      var tdTag5 = document.createElement("td");
      
      tdTag2.setAttribute("width", "100");
      tdTag3.setAttribute("width", "200");
      tdTag4.setAttribute("width", "100");
      
      tdTag2.align = "right";
	  
      tdTag1.innerHTML = "&#160;";
      tdTag2.innerHTML = "<span class=\"fieldlabel\" id=\"label_" + selectBox.value + "\">" + document.getElementById(selectBox.value).text + ":</span>";
      tdTag3.innerHTML = "<input class=\"formfield\" type=\"text\" name=\"product.attributes(" + selectBox.value + ").value\" value=\"\" size=\"35\"/>";
      tdTag3.innerHTML += "<input type=\"hidden\" name=\"product.attributes(" + selectBox.value + ").attributeId\" value=\"" + selectBox.value + "\"/>";
      tdTag4.innerHTML = "<a href=\"\" onClick=\"removeAttributeFromProductEditorForm('" + selectBox.value + "'); addAttributeEntryToSelectBox('" + selectBox.value + "', '" + document.getElementById(selectBox.value).text + "'); return false;\" onMouseOut=\"swapImageRestore()\" onMouseOver=\"swapImage('deleteAttributeButton_" + selectBox.value + "','','images/ibtn_delete_over.gif',1)\"><img id=\"deleteAttributeButton_" + selectBox.value + "\" src=\"images/ibtn_delete.gif\" alt=\"Delete\" border=\"0\"/></a>"
      tdTag5.innerHTML = "&#160;";

      trTag.setAttribute("id", "row_" + selectBox.value);
      trTag.appendChild(tdTag1);
      trTag.appendChild(tdTag2);
      trTag.appendChild(tdTag3);
      trTag.appendChild(tdTag4);
      trTag.appendChild(tdTag5);

      tBody.appendChild(trTag);
      
      hideElementWithId('noSelectedAttributesTable');
      if(selectBox.options.length == 0)
      {
        showElementWithId('allSelectedAttributesTable');      
      }
    }
  }
}


function removeAttributeFromProductEditorForm(attrName)
{
  var trElement = document.getElementById('row_' + attrName);

  if (trElement)
  {
    var tBody = document.getElementById('selectedAttributesTbody');
    if (tBody)
    {
      tBody.removeChild(trElement);
      if (tBody.childNodes.length == 0)
      {
        showElementWithId('noSelectedAttributesTable');
      }
      for(var i = 0; i < tBody.childNodes.length; i++)
      {
        if(i % 2 == 0)
        {
          tBody.childNodes[i].className = "selection-row2";
        }
        else
        {
          tBody.childNodes[i].className = "selection-row1";      
        }
      }
    }
  }
}


function addAttributeEntryToSelectBox(optionName, optionText)
{
  var selectBox = document.getElementById('newAttributeName');
  if (selectBox)
  {
    if (selectBox.length == 0)
    {
      hideElementWithId('noAttributesDefined');
      hideElementWithId('addAttributeFormLabel');
      showElementWithId('newAttributeTable');
    }

    var optionTag = document.createElement("option");
    optionTag.setAttribute('value', optionName);
    optionTag.setAttribute('id', optionName);
    optionTag.appendChild(document.createTextNode(optionText));
    selectBox.appendChild(optionTag);
    
    return optionTag;
  }
}

function removeAttributeEntryFromSelectBox(optionName)
{
  var optionElement;
  var selectBox = document.getElementById('newAttributeName');
  if (selectBox)
  {
    if (selectBox.options.length > 1)
    {
      for (i = 0; i < selectBox.options.length; i++)
      {
        if (optionName == selectBox.options[i].value)
        {
          optionElement = selectBox.options[i];
        }
      }

      if (optionElement)
      {
        selectBox.removeChild(optionElement);
      }
    } 
    else if (selectBox.options.length == 1) 
    {
      selectBox.removeChild(selectBox.options[0]);
      hideElementWithId('newAttributeTable');
      showElementWithId('addAttributeFormLabel');
    } 
    else 
    {
      alert("Somehow you tried to remove an attribute from an empty select box, the system is currently impressed.");
    }
  }
}

function insertNewAttribute( id, label ) {
   var newAttribute = addAttributeEntryToSelectBox( id, label );
   newAttribute.selected = true;
   
   hideElementWithId('newAttributePopup-table');
     
   //frames['newAttributePopup-frame'].history.go(-1);
   frames['newAttributePopup-frame'].location.href='newAttribute.hg';
}

/***********************************************************************************************************/
/*                                               PRICES                                                    */
/***********************************************************************************************************/

function calculatePrice(advertisedPriceId, percentageId, salePriceId) 
{
	var advertisedPriceElement = document.getElementById(advertisedPriceId);
	var percentageElement = document.getElementById(percentageId);
	var salePriceElement = document.getElementById(salePriceId);
	if (percentageElement.value == '' && salePriceElement.value != '') 
	{
     // do something
	} 
	else 
	{
		var adPrice = advertisedPriceElement.value;
		var percent = parseFloat(percentageElement.value);
		if (isNaN(percent)) 
		{
			alert("You must enter a decimal value for Discount.");
			return;
		}
		var nonDiscount = parseFloat(adPrice) < parseFloat(salePriceElement.value);
		if ((percent < 0 || percent > 100) && !nonDiscount) 
		{
			alert("Discount must be between 0 and 100 percent.");
			return;
		}
		var price = Math.floor(((1 - (percent / 100)) * adPrice) * 100) / 100;
		salePriceElement.value = price;
		setPriceColor(salePriceElement);
		setPriceColor(percentageElement);
	}
}

function setPriceColor(priceElement)
{
   if(parseFloat(priceElement.value) < 0.0)
   {
     priceElement.style.color = "#CC0000";
   }
   else
   {
     priceElement.style.color = "#000000";
   }
}

function calculatePercentage(advertisedPriceId, percentageId, salePriceId) 
{
	var advertisedPriceElement = document.getElementById(advertisedPriceId);
	var percentageElement = document.getElementById(percentageId);
	var salePriceElement = document.getElementById(salePriceId);
	if (salePriceElement.value == '' && percentageElement.value != '') 
	{
     // do something
	} 
	else 
	{
		var adPrice = advertisedPriceElement.value;
		var salePrice = salePriceElement.value;	
	 	if (adPrice == 0 && salePrice > 0)
	 	{
     		alert("Your List Price is zero, please set a List Price greater than zero before setting a new Sale Price.");     
     		return;
     	}
     	if (adPrice == 0 && salePrice == 0)
     	{
     		percentageElement.value = 0.00;
     	}
     	else
     	{
     		var percent = Math.floor((1 - (salePrice / adPrice)) * 10000) / 100;
			percentageElement.value = percent;
			setPriceColor(salePriceElement);
			setPriceColor(percentageElement);
     	}	
	}
}

function addNewSalePrice(productId)
{
  if(!isShown('salesPricesTable'))
  {
    showElementWithId('salesPricesTable');
  }
  
  var trTag = document.createElement("tr");
  trTag.setAttribute('height', '30');
  var tBody = document.getElementById('salesPricingTbody');
  if (tBody)
  {
    var index = tBody.childNodes.length + 1; // 1 based indexing
    if(index % 2 == 0)
    {
      trTag.className = 'selection-row1';
    }
    else
    {
      trTag.className = 'selection-row2';
    }

    var newPrice = document.getElementById('advertisedPrice').value;
    var percentage = 0;
    var startDate = '';
    var endDate = '';

    trTag.setAttribute('id', 'salesPricingRow' + index);

    var tdTagPrice = document.createElement("td");
    tdTagPrice.align = "center";
    tdTagPrice.width = "100";
    tdTagPrice.innerHTML = '$&#160;<input class="formfield" style="text-align: right;" type="text" '+
      'value="' + newPrice + '" name="product.pricing[' + index + '].price"' +
                           ' id="price_' + index + '" size="8" onBlur="this.value = validatePrice(this.value); calculatePercentage(\'advertisedPrice\', \'percentDiscount_' + index + '\',' +
                           '\'price_' + index + '\');" maxlength="8"/>' +
                           '<input type="hidden" name="product.pricing[' + index + '].priceLabel" value="Sale Price"/>';

    tdTagPrice.innerHTML += '<input type="hidden" '+
      'value="' + productId + '" name="product.pricing[' + index + '].productId"/>';
    tdTagPrice.innerHTML += '<input type="hidden" '+
      'value="Sales Price" name="product.pricing[' + index + '].productLabel"/>';
    tdTagPrice.innerHTML += '<input type="hidden" '+
      'value="sale" name="product.pricing[' + index + '].priceName"/>';

    var tdTagDiscount = document.createElement("td");
    tdTagDiscount.align = "right";
    tdTagDiscount.width = "125";
    tdTagDiscount.innerHTML = '<input class="formfield" style="text-align: right;" type="text" value="' + percentage + '" name="percentDiscount_' + index + '"' +
                              ' id="percentDiscount_'  + index + '" size="5" onBlur="calculatePrice(\'advertisedPrice\', \'percentDiscount_' + index + '\', \'price_' + index + '\');" onKeyDown="" maxlength="15"/>&#160;%';

    var tdTagStartDate = document.createElement("td");
    tdTagStartDate.align = "center";
    tdTagStartDate.width = "150";
    tdTagStartDate.innerHTML = '<table><tr><td>'+
                               '  <input class="formfield" type="text" value="' + startDate + '" name="product.pricing[' + index + '].startDateByString" id="startDate_' + index + '" size="12" maxlength="10"/>&#160;' +
                               '</td><td>'+
                               '  <img id="startDateButton_' + index + '" src="images/ibtn_calendar.gif" alt="Start Date" border="0" onClick="openDlgCalendar(\'startDate_' + index + '\',\'startDateButton_' + index + '\');"  onMouseOut="swapImageRestore()" onMouseOver="swapImage(\'startDateButton_' + index + '\',\'\',\'images/ibtn_calendar_over.gif\',1)"/>'+
                               '</td></tr></table>';
                               

    var tdTagEndDate = document.createElement("td");
    tdTagEndDate.align = "center";
    tdTagEndDate.width = "150";
    tdTagEndDate.innerHTML = '<table><tr><td>'+
                             '  <input class="formfield" type="text" value="' + endDate + '" name="product.pricing[' + index + '].endDateByString" id="endDate_' + index + '" size="12" maxlength="10"/>&#160;' +
                             '</td><td>'+
                             '  <img id="endDateButton_' + index + '" src="images/ibtn_calendar.gif" alt="End Date" border="0" onClick="openDlgCalendar(\'endDate_' + index + '\',\'endDateButton_' + index + '\');" onMouseOut="swapImageRestore()" onMouseOver="swapImage(\'endDateButton_' + index + '\',\'\',\'images/ibtn_calendar_over.gif\',1)"/>'+
                             '</td></tr></table>';

    var tdTagDeleteButton = document.createElement("td");
    tdTagDeleteButton.align = "center";
    tdTagDeleteButton.innerHTML = '<a href="" onClick="deletePrice(\'salesPricingRow' + index + '\'); return false;" onMouseOut="swapImageRestore()" onMouseOver="swapImage(\'deletePriceButton_' + index + '\',\'\',\'images/ibtn_delete_over.gif\',1)">' +
                                  '<img id="deletePriceButton_' + index + '" src="images/ibtn_delete.gif" alt="Delete" border="0"/></a>';
    
    hideElementWithId('noSalesPricesText');
    trTag.appendChild(tdTagPrice);
    trTag.appendChild(tdTagDiscount);
    trTag.appendChild(tdTagStartDate);
    trTag.appendChild(tdTagEndDate);
    trTag.appendChild(tdTagDeleteButton);
    tBody.appendChild(trTag);
  }
}
 
function deletePrice(priceId)
{
  var tBody = document.getElementById('salesPricingTbody');

  if (tBody)
  {
    var trToDelete = document.getElementById(priceId);

    if (trToDelete)
    {
      tBody.removeChild(trToDelete);

      var trNodeList = tBody.childNodes;
      for (var i = 0; i < trNodeList.length; i++)
      {
        if(i % 2 == 0)
        {
          trNodeList[i].className = 'selection-row2';
        }
        else
        {
          trNodeList[i].className = 'selection-row1';
        }
      }

      if(trNodeList.length == 1)
      {
        hideElementWithId('salesPricesTable');      
      }
      
    }
  }
}

/***********************************************************************************************************/
/*                                             ??????????                                                  */
/***********************************************************************************************************/
function toggleCategoryToProduct(categoryId, labelElement)
{
  if (categoryId)
  {
    var checkbox = document.getElementById("product_category_"+categoryId);
    if (checkbox)
    {
      if (checkbox.checked == false)
      {
        /*var categoryRowToRemove = document.getElementById("selected_product_category_row_"+categoryId);
        if(categoryRowToRemove)
        {
          categoryRowToRemove.parentNode.removeChild(categoryRowToRemove);
        }*/
        labelElement.className = 'product-not-in-category';
      } 
      else 
      {
        labelElement.className = 'product-in-category';
        /*var categoryDisplayString = "";

        var productCategoryTreeSpan = document.getElementById("product_category_tree_"+categoryId);
        var overflowCounter = 0;
        
        do
        {
          if(productCategoryTreeSpan)
          {
            var labelElement = productCategoryTreeSpan.getElementsByTagName('A');
            if(labelElement && labelElement.length > 0)
            {
              categoryDisplayString = labelElement[0].lastChild.nodeValue  + (categoryDisplayString == "" ? "" : " >> "+categoryDisplayString);
            }
          }
          productCategoryTreeSpan = productCategoryTreeSpan.parentNode;
          overflowCounter ++;
        } 
        
        while(productCategoryTreeSpan && productCategoryTreeSpan.id != "product_category_tree" && overflowCounter < 10);

        var tbody = document.getElementById("product_category_tree_tbody");
        if(!tbody)
        {
          var categoryLinkSummaryElement = document.getElementById("categoryLinkSummary");
          var categoryLinkTable = document.createElement("table");
          tbody = document.createElement("tbody");
          
          tbody.setAttribute("id", "product_category_tree_tbody");
          categoryLinkTable.appendChild(tbody);
          categoryLinkSummaryElement.appendChild(categoryLinkTable);  
        }
        
        var categoryRow = document.createElement("tr");
        categoryRow.setAttribute("id", "selected_product_category_row_"+categoryId);

        var categoryCellLeft = document.createElement("td");
        categoryCellLeft.setAttribute("align", "left");
        categoryCellLeft.innerHTML = categoryDisplayString;


        var categoryCellRight = document.createElement("td");
        categoryCellRight.setAttribute("align", "right");
        categoryCellRight.innerHTML = "<input class=\"formfield\" type=\"button\" value=\"Delete\" onClick=\"document.getElementById('product_category_"+categoryId+"').checked = false; toggleCategoryToProduct('"+categoryId+"');\"/>"

        hideElementWithId("noCategoryLink");

        categoryRow.appendChild(categoryCellLeft);
        categoryRow.appendChild(categoryCellRight);
        tbody.appendChild(categoryRow);  
        */
      }
    }
  }
}

/***********************************************************************************************************/
/*                                              OPTIONS                                                    */
/***********************************************************************************************************/
function selectAllOptions(arr)
{
	for(var i=0; i<arr.length; i++)
	{
		var optionValueId = arr[i];
		document.getElementById('optionValueCheckbox_'+optionValueId).checked = true;
		showOptionPrice(optionValueId);
	}
}

function deselectAllOptions(arr)
{
	for(var i=0; i<arr.length; i++)
	{
		var optionValueId = arr[i];
		document.getElementById('optionValueCheckbox_'+optionValueId).checked = false;
		showOptionPrice(optionValueId);
	}
}

function checkOptionContainerSize(optionValues)
{
	for(var i=0; i<optionValues.length; i++)
	{
		var optionContainer = document.getElementById('optionContainer_'+optionValues[i]);
		if(optionContainer.offsetHeight > 200)
		{
			optionContainer.style.height = '200px';
		}
	}
}

function showOptionPrice(optionValueId)
{
  var optionValue = 'optionValueCheckbox_' + optionValueId;
  var optionValueCheckbox = document.getElementById(optionValue).checked;
  var optionPricing = 'optionPricing_' + optionValueId;
  if (optionValueCheckbox)
  {
    document.getElementById(optionPricing).style.display = '';
    document.getElementById(optionPricing).style.visibility = "visible";
  }
  else 
  {
    hideElementWithId(optionPricing);
  }
}

function addOptionToProduct(optionId)
{
  //alert('Option Id: ' + optionId);
  var selectElement = document.getElementById('availableOptionSelectBox');

  if (selectElement)
  {
    var optionElement = document.getElementById('option_value_' + optionId);    
    if (optionElement)
    {
      //lets remove this from the list and check to see if this was the last one
      selectElement.removeChild(optionElement);
      var optionCount = (selectElement.getElementsByTagName('option')).length;
      if (optionCount == 0)
      {
        hideElementWithId('addOptionDiv');
        showElementWithId('hasAllOptionsText');
      }


      // now lets shot the div and enable the select box
      hideElementWithId('noOptionsSelectedText');
      showElementWithId('optionFillerTable');
      showElementWithId('option_' + optionId);
      showElementWithId('optionFillerTable');
			
			// Reset the height of the 'option_content' div so it will display correctly in FF
      document.getElementById('option_content').style.height="";
      
      var toBoxElement = document.getElementById('option_' + optionId + '_to_box');
      if (toBoxElement)
      {
        toBoxElement.removeAttribute('disabled');
      }
    }
	
	var optionContainer = 'optionContainer_' + optionId;
	if(document.getElementById(optionContainer).offsetHeight > 200)
	{
		document.getElementById(optionContainer).style.height = '200px';
	}
  }
}


function removeOptionFromProduct(optionId)
{
  //alert('Option Id: ' + optionId);

  hideElementWithId('option_' + optionId);
  var toBoxElement = document.getElementById('option_' + optionId + '_to_box');
  if (toBoxElement)
  {
    toBoxElement.setAttribute('disabled', 'true');
  }

  var optionCount = (document.getElementById('selectBoxOptionCount')).value;
  var selectElement = document.getElementById('availableOptionSelectBox');
  if (selectElement)
  {        
    var newOption = document.createElement('OPTION');
    newOption.setAttribute('id', 'option_value_' + optionId);
    newOption.value = optionId;
    newOption.innerHTML = (document.getElementById('option_label_' + optionId)).innerHTML;

    selectElement.appendChild(newOption);

    if (optionCount == selectElement.options.length)
    {
        showElementWithId('noOptionsSelectedText');
        hideElementWithId('optionFillerTable');
    }

    showElementWithId('addOptionDiv');        
    hideElementWithId('hasAllOptionsText');
  }
}



var currentOptionSelectBox = null;
var currentOptionTable = null;
function createOption( id, label ) {   
  // Add the new option to the select box
  var optionTag = document.createElement("option");
  optionTag.setAttribute('value', id);
  optionTag.setAttribute('id', 'option_value_' + id);
  optionTag.appendChild(document.createTextNode(label));
  var optionSelectBox = document.getElementById("availableOptionSelectBox");  
  optionSelectBox.appendChild(optionTag);
  optionTag.selected = true;
  document.getElementById("selectBoxOptionCount").value =
     parseInt( document.getElementById("selectBoxOptionCount").value ) + 1;  

  // The main TR, TD for each option
  var mainTrTag = document.createElement( "tr" );
  mainTrTag.id = "option_" + id;
  mainTrTag.style.display = "none";
  var mainTdTag = document.createElement("td");

  // The table for the option's label and values. (OPTION TABLE)
  var optionTable = document.createElement( "table" );
  optionTable.border = 0;
  optionTable.cellSpacing = 0;
  optionTable.cellPadding = 3;
  optionTable.style.width = '100%';
  var optionBody = document.createElement( "tbody" );

  // The TR for OPTION_TABLE
  var optionTr = document.createElement("tr");
  // First column. The TD for the TR above
  var column1 = document.createElement( "td" );
  column1.width = 120;
  column1.className = 'fieldlabel';
  column1.style.fontSize = "11px";
  column1.vAlign = 'top';
  column1.align = 'right';
  column1.innerHTML = "<span id=\"option_label_" + id + "\">" + label + "</span>:&#160;" +
            "<br/>" +
            "<img id=\"deleteOptionButton_" + id + "\" src=\"images/ibtn_delete.gif\" " +
            "alt=\"Select\" onClick=\"removeOptionFromProduct('" + id + 
            "');deselectAllOptions(optionArr['" + id + 
            "']);\" onMouseOut=\"swapImageRestore()\" " + 
            "onMouseOver=\"swapImage('deleteOptionButton_" + id + 
            "','','images/ibtn_delete_over.gif',1)\" border=\"0\"/>";    
  optionTr.appendChild(column1);
  // Second column
  var column2 = document.createElement("td");
  column2.width = 20;
  column2.innerHTML = "&#160;";
  optionTr.appendChild(column2);
  // Third column, the option values
  var column3 = document.createElement("td");
  column3.align = 'left';
  //// Start: Option values table
  var valueTable = document.createElement("table");
  valueTable.border = 0;
  valueTable.cellSpacing = 0;
  valueTable.cellPadding = 0;
  valueTable.style.backgroundColor = 'white'; 
  valueTable.style.border = '1px solid #003366';
  var valueBody = document.createElement( "tbody" );
  var valueTr = document.createElement("tr");
  var valueTd = document.createElement("td");
  // Start: The option value header table
  var valueHeaderTable = document.createElement("table");
  valueHeaderTable.border = 0;
  valueHeaderTable.cellSpacing = 0;
  valueHeaderTable.cellPadding = 3;
  valueHeaderTable.width = '100%';
  var valueHeaderBody = document.createElement( "tbody" );
  var valueHeaderTr = document.createElement("tr");
  // The first row of the option value header
  var valueHeaderTd = document.createElement("td");
  valueHeaderTd.colSpan = 3;
  valueHeaderTd.style.backgroundColor = '#F2F2F2';
  valueHeaderTd.style.fontWeight = 'bold';
  valueHeaderTd.style.borderWidth = '1px';
  valueHeaderTd.style.borderColor = '#000000'; 
  valueHeaderTd.style.borderStyle = 'none none solid none';
  valueHeaderTd.innerHTML = "Available Values" +
                            "<input type=\"hidden\" disabled=\"true\" id=\"greatestDecrement_" + id + "\" name=\"greatestDecrement_" + id + "\" value=\"0.00\"/>";
  valueHeaderTr.appendChild( valueHeaderTd );
  valueHeaderBody.appendChild(valueHeaderTr);
  // The second row of the option value header
  var valueHeader2Tr = document.createElement("tr");
  var valueHeader2Td = document.createElement("td");
  valueHeader2Td.colSpan = 3;
  valueHeader2Td.style.borderWidth = '1px';
  valueHeader2Td.style.borderColor = '#000000'; 
  valueHeader2Td.style.borderStyle = 'none none solid none';
  optionArr[id] = new Array();
  valueHeader2Td.innerHTML = "<a href=\"javascript:selectAllOptions(optionArr['" +
                             id + "']);\">Select All</a> | <a href=\"" +
                             "javascript:deselectAllOptions(optionArr['" + id + "']);\">Deselect All</a>";
  valueHeader2Tr.appendChild( valueHeader2Td );
  valueHeaderBody.appendChild(valueHeader2Tr);
  valueHeaderTable.appendChild(valueHeaderBody);
  // End: option value header table
  valueTd.appendChild(valueHeaderTable);
  // Start: Div and javascript for the option values
  var div = document.createElement("div");
  div.id = "optionContainer_" + id;
  div.style.minHeight = 'auto';
  div.style.maxHeight = '350px';
  div.style.overflow = 'auto';
  div.style.backgroundColor = '#fff';
  valueTd.appendChild(div);
  // End: Div and javascript for the option values
  valueTr.appendChild(valueTd);
  valueBody.appendChild(valueTr);
  valueTable.appendChild(valueBody);
  //// End: Option values table
  column3.appendChild(valueTable);
  optionTr.appendChild(column3);
  // Append optionTr to optionTable
  optionBody.appendChild(optionTr);
  optionTable.appendChild(optionBody);
  mainTdTag.appendChild(document.createElement("br"));
  mainTdTag.appendChild(optionTable);
  mainTrTag.appendChild(mainTdTag);

  document.getElementById("optionRowsTable").appendChild( mainTrTag );  
  currentOptionTable = document.getElementById("optionContainer_" + id);

  var addOptionDiv = document.getElementById("addOptionDiv")
  addOptionDiv.style.display = '';
  addOptionDiv.style.visibility= "visible";
  document.getElementById("hasAllOptionsText").style.display = 'none';
}

function optionInsertionComplete( noBack ) {
  currentOptionSelectBox = null;  
  hideElementWithId('newOptionPopup-table');       
  if (!noBack) {
    //frames['newOptionPopup-frame'].history.go(-1);
	frames['newOptionPopup-frame'].location.href='newOption.hg';  
  }
}

function addOptionValue( optionId, valueId, label ) {
  var valueTable = document.createElement("table");
  valueTable.cellpadding = 2;
  valueTable.cellspacing = 0;
  var valueBody = document.createElement("tbody");
  var trTag = document.createElement("tr");
  var tdTag = document.createElement( "td" );
  optionArr[optionId].push(valueId);

  // The checkbox for option value
  tdTag.width = 20;
  tdTag.align = 'left';
  tdTag.innerHTML = 
            "<script type=\"text/javascript\">optionArr['" + optionId + 
            "'].push('" + valueId + "');</script>" +
            "<input type=\"checkbox\" id=\"optionValueCheckbox_" + valueId +
            "\" name=\"product.options(" + optionId + ").values\" value=\"" + valueId +
            "\" onClick=\"showOptionPrice(" + valueId + ");\">";
  trTag.appendChild( tdTag );
  // The option value label
  tdTag = document.createElement( "td" );
  tdTag.align = 'left';
  tdTag.width = 100;
  // Add div to constrain text and make it wrap
  _div = document.createElement( "div" );
  _div.style.width = '100px';
  _div.innerHTML = label;
  tdTag.appendChild( _div );
  trTag.appendChild( tdTag );
  // The option pricing
  tdTag = document.createElement( "td" );
  tdTag.align = 'left';
  tdTag.width = 250;
  var div = document.createElement("div");
  div.id = "optionPricing_" + valueId;
  div.style.display = "none";
  div.style.visibility = 'hidden';
  div.innerHTML = "<select class=\"formfield\" id=\"optionValueIncreasePrice_" + valueId + "\" "+
                  "name=\"product.optionPricing(" + valueId + ").increasePrice\">" +
                  "<option value=\"true\">Increase</option>" +
                  "<option value=\"false\">Decrease</option>" +           
                  "</select>&#160;" +
                  "price by $ &#160;" +
            "<input class=\"formfield\" type=\"text\" id=\"optionValuePriceIncrement(" + 
            optionId + ")_" + valueId + "\" name=\"product.optionPricing(" + valueId + 
            ").priceIncrement\" size=\"8\" onBlur=\"this.value = validatePrice(this.value)\"/>";
  tdTag.appendChild(div);
  trTag.appendChild( tdTag );
  valueBody.appendChild(trTag);
  valueTable.appendChild(valueBody);
  currentOptionTable.appendChild(valueTable);
}

/***********************************************************************************************************/
/*                                               BUNDLES                                                   */
/***********************************************************************************************************/

function multiBundle(fromBox)
{
  var fBox = document.getElementById(fromBox);
  
  if (fBox)
  {
    var fBoxOptions = fBox.getElementsByTagName('OPTION');
    var fBoxSelected = new Array();

    if (fBoxOptions && fBoxOptions.length > 0)
    {    
      var index = 0;
      for (var i = 0; i < fBoxOptions.length; i++)
      {
        if (fBoxOptions[i].selected && fBoxOptions[i].value != '')
        {
          fBoxSelected[index++] = fBoxOptions[i];
        }
      }

      if (fBoxSelected.length > 0)
      {
        var tbody = document.getElementById("productsInBundleTBody");
        hideElementWithId('noBundleItems');
        for (var i = 0; i < fBoxSelected.length; i++)
        {
          var numberOfItemsInBundle = productBundleItemCount();
          var productId = fBoxSelected[i].value;
          var bundleItemRow = document.createElement("tr");
          
          bundleItemRow.setAttribute("id", "productBundleItem"+fBoxSelected[i].value);
          bundleItemRow.setAttribute("height", "25");
          
          var bundleItemRowCell = document.createElement("td");
          var tableHTML = "<table border=\"0\" cellspacing=\"0\" width=\"100%\" cellpadding=\"0\" style=\"\" id=\"transitionTable"+productId+"\" ";
          if(isIE())
          {
            tableHTML += "style=\"visibility='hidden'; display='none'; filter:progid:DXImageTransform.Microsoft.Fade(duration=0.5,overlap=1.0);\" ";
          }
          tableHTML += ">"+
          "  <tr>" + 
          "    <input id=\"bundleItemId_"+productId+"\" type=\"hidden\" name=\"bundleItems["+numberOfItemsInBundle+"].productId\" value=\""+productId+"\"/>"+
          "    <td align=\"left\" id=\"bulkProductTitle"+productId+"\">"+fBoxSelected[i].text+"</td>" +
          "    <td align=\"left\" valign=\"top\" width=\"22\"><input class=\"formfield\" id=\"bundleItemQty_"+productId+"\" type=\"text\" value=\"1\" name=\"bundleItems["+numberOfItemsInBundle+"].packagedQty\" size=\"3\"/><td>" + 
          "    <td align=\"right\" valign=\"top\" width=\"55\"><img id='deleteItem"+productId+"' src='images/ibtn_delete.gif' onClick='deleteProductFromBundle("+productId+",\""+fromBox+"\");' onMouseOut='swapImageRestore()' onMouseOver=\"swapImage('deleteItem"+productId+"','','images/ibtn_delete_over.gif',1)\"/></td>"+
          "  </tr>"+
          "</table>";
          bundleItemRowCell.innerHTML = tableHTML;
          tbody.appendChild(bundleItemRow);           
          bundleItemRow.appendChild(bundleItemRowCell);
          if(isIE())
          {         
            transition('transitionTable'+fBoxSelected[i].value);
          }
	        // manually reset height after new row has been added - mozilla will not resize otherwise
          document.getElementById('bundleProductTable').style.height = "";          

          fBox.removeChild(fBoxSelected[i]);
        }
      }
    }
  }
}

function productBundleItemCount()
{
  var tbody = document.getElementById("productsInBundleTBody");
  var tableRows = tbody.getElementsByTagName("TR");
  var count = 0;
  for(var i = 0; i < tableRows.length; i++)
  {
    if(tableRows[i].getAttribute("id") && tableRows[i].getAttribute("id").indexOf("productBundleItem") == 0)
    {
      count++;
    }
  }
  return count;
}

function deleteProductFromBundle(productId, returnSelectBoxId)
{
  var tbody = document.getElementById("productsInBundleTBody");
  var bundleItemRow = document.getElementById('productBundleItem'+productId);
  var fBox = document.getElementById(returnSelectBoxId);
  var productTitle = document.getElementById("bulkProductTitle"+productId).innerHTML;
  if (fBox)
  {
    var fBoxOptions = fBox.getElementsByTagName('OPTION');
    var newOption = document.createElement("OPTION"); 
    newOption.innerHTML = productTitle;
    newOption.value = productId;

    if (fBoxOptions && fBoxOptions.length > 0)
    {    
      for (var i = 0; i < fBoxOptions.length; i++)
      {
        if (fBoxOptions[i].text + ""  > productTitle + "")
        {
          fBox.insertBefore(newOption, fBoxOptions[i]);

          break; 
        }
        if(i == fBoxOptions.length - 1)
        {
          fBox.appendChild(newOption);
        }
      }
    }
    else
    {
      fBox.appendChild(newOption);
    }
    if(!isIE())
    {
      // manually reset height after new row has been removed - mozilla will not resize otherwise
      document.getElementById('bundleProductTable').height = document.getElementById('bundleProductTable').offsetHeight;
    }
  }
  
  //step on name - browsers send hidden input fields even when parent node is removed.
  var bundleItemIdElement = document.getElementById('bundleItemId_'+productId);
  if(bundleItemIdElement && bundleItemIdElement.name)
  {
    bundleItemIdElement.name = "";
  }
    
  tbody.removeChild(bundleItemRow);
  recalculateSortOrder(tbody);
  if(productBundleItemCount() == 0)
  {
    showElementWithId('noBundleItems');
  }
}

function recalculateSortOrder(tbody)
{
  var tableRows = tbody.getElementsByTagName("TR");
  for(var i = 0; i < tableRows.length; i++)
  {
    var potentialBundleItem = tableRows[i].getAttribute("id");
    if(potentialBundleItem && potentialBundleItem.indexOf("productBundleItem") == 0)
    {
      var productId = potentialBundleItem.substring("productBundleItem".length, potentialBundleItem.length);
      var bundleItemIdElement = document.getElementById("bundleItemId_"+productId);
      if(bundleItemIdElement)
      {
        bundleItemIdElement.name="bundleItems["+i+"].productId";
      }
      var bundleItemQtyElement = document.getElementById("bundleItemQty_"+productId);
      if(bundleItemQtyElement)
      {
        bundleItemIdElement.name="bundleItems["+i+"].packagedQty";
      }
    }
  }
}

/***********************************************************************************************************/
/*                                             ??????????                                                  */
/***********************************************************************************************************/

function transition(elementId)
{
  var element = document.getElementById(elementId);
  if (isIE() && element && element.filters && element.filters.length > 0)
  {
    var length = element.filters.length;
    element.filters[length - 1].Apply();
    if(element.style.visibility == 'hidden' || element.style.display == 'none')
    {
      showElement(element);
    }
    else
    {
      hideElement(element);
    }
    element.filters[length - 1].play();
  }
  else
  {
    if(!isShown(elementId))
    {
      showElement(element);
    }
    else
    {
      hideElement(element);
    }
  }
}

function enableInventory()
{
  var inventoryYesElement = document.getElementById('inventoryYes');
  var inventoryNoElement = document.getElementById('inventoryNo');
  inventoryYesElement.disabled = false;
  inventoryNoElement.disabled = false; 
  if(inventoryYesElement.checked)
  {
    inventoryYesElement.focus();
  }
  else if(inventoryNoElement.checked)
  {
    inventoryNoElement.focus();
  }
}

function disableInventory()
{
  document.getElementById('inventoryYes').disabled = true;
  document.getElementById('inventoryNo').disabled = true;
}

function enableShipping()
{
  var shippingYesElement = document.getElementById('shippingYes');
  var shippingNoElement = document.getElementById('shippingNo');
  shippingYesElement.disabled = false;
  shippingNoElement.disabled = false; 
  if(shippingYesElement.checked)
  {
    shippingYesElement.focus();
  }
  else if(shippingNoElement.checked)
  {
    shippingNoElement.focus();
  }
}


function disableShipping()
{
  document.getElementById('shippingYes').disabled = true;
  document.getElementById('shippingNo').disabled = true;
}

function enableProductType()
{
  var physicalElement = document.getElementById('productTypePhysical');
  var digitalElement = document.getElementById('productTypeDigital');
  var bundleElement = document.getElementById('productTypeBundle');
  physicalElement.disabled = false;
  digitalElement.disabled = false; 
  bundleElement.disabled = false; 
  if(physicalElement.checked)
  {
    physicalElement.focus();
  }
  else if(digitalElement.checked)
  {
    digitalElement.focus();
  }
  else if(bundleElement.checked)
  {
    bundleElement.focus();
  }
}

function disableProductType()
{
  document.getElementById('productTypePhysical').disabled = true;
  document.getElementById('productTypeDigital').disabled = true;
  document.getElementById('productTypeBundle').disabled = true;
}


function showProductType()
{
  disableProductType();
  var physicalProductElement = document.getElementById('productTypePhysical');
  var digitalProductElement = document.getElementById('productTypeDigital');
  var bundleProductElement = document.getElementById('productTypeBundle');
  
  var rollDownProdutType = function()
  {
    var physicalProductElement = document.getElementById('productTypePhysical');
    var digitalProductElement = document.getElementById('productTypeDigital');
    var bundleProductElement = document.getElementById('productTypeBundle');
    if(physicalProductElement.checked)
    {
      rollDown('physicalProductTable', 50, enableProductType);
    }
    else if(digitalProductElement.checked)
    {
      disableShipping()
      rollUp('shippingAttributeTable', 50);
      rollDown('digitalProductTable', 50, enableProductType);
    }
    else if(bundleProductElement.checked)
    {
      rollDown('bundleProductTable', 75, enableProductType);
    }
  }
      
  if(isShown('physicalProductTable'))
  {
    if(!physicalProductElement.checked)
    {
      rollUp('physicalProductTable', 0, rollDownProdutType);
    }
    else
    {
      enableProductType();
    }
  }
  if(isShown('digitalProductTable'))
  {
    if(!digitalProductElement.checked)
    {
      rollUp('digitalProductTable', 50, rollDownProdutType);
      enableShipping();
      if(document.getElementById('shippingYes').checked)
      {
        rollDown('shippingAttributeTable', 50);
      }
    }
    else
    {
      enableProductType();
    }
  }
  if(isShown('bundleProductTable'))
  {
    if(!bundleProductElement.checked)
    {
      rollUp('bundleProductTable', 75, rollDownProdutType);
    }
    else
    {
      enableProductType();    
    }
  }
}

/* needed if a tabbed product editor is used*/
function showProductEditorTab(tabName)
{
  var tabNameArray = new Array("product", "pricing", "category", "attributes",
    "options", "associations", "images");  
  
  for(var i = 0; i < tabNameArray.length; i++)
  {
    if(tabName != tabNameArray[i])
    {
      hideElementWithId(tabNameArray[i]+'Tab');
      hideElementWithId(tabNameArray[i]+'TabFooter');
      swapImage('tab_image_'+tabNameArray[i], '', 'images/tab_'+tabNameArray[i]+'.gif', 1);
    }    
  }
  if(tabName == "images")
  {
    refreshProductImages();  
  }
  showElementWithId(tabName+'Tab');
  showElementWithId(tabName+'TabFooter');
  swapImage('tab_image_'+tabName, '', 'images/tab_'+tabName+'_selected.gif', 1);
}


function swapHelpBoxes(helpBoxName)
{
  var helpBoxNameArray = new Array("productTabHelpTable", "pricingTabHelpTable", "categoryTabHelpTable", 
                                   "attributesTabHelpTable", "optionsTabHelpTable", "imagesTabHelpTable",
                                   "associationsTabHelpTable");
  var element = document.getElementById(helpBoxName);
  
  if (isIE() && element && element.filters && element.filters.length > 0)
  {                                   
    element.filters[element.filters.length - 1].Apply();
  }
  
  for (var i = 0; i < helpBoxNameArray.length; i++)
  {
    if (helpBoxName != helpBoxNameArray[i])
    {
        hideElementWithId(helpBoxNameArray[i]);
    }
  }
  
  showElementWithId(helpBoxName);
  
  if (isIE() && element && element.filters && element.filters.length > 0)
    {                                   
      element.filters[element.filters.length - 1].Play();
  }
}

function rollSection(sectionId, animationTime)
{
  var elementToRoll = document.getElementById(sectionId+"_content");
  if(elementToRoll && isShown(sectionId+"_content"))
  {
    rollUp(sectionId+"_content", animationTime);
    var sectionImage = document.getElementById(sectionId+"_plusMinusImage");
    if(sectionImage)
    {
      sectionImage.src = "images/plus.gif";
    }
  }
  else if(elementToRoll)
  {
    rollDown(sectionId+"_content", animationTime, function(elementID){
		document.getElementById(elementID).style.height='auto';
	});
    var sectionImage = document.getElementById(sectionId+"_plusMinusImage");
    if(sectionImage)
    {
      sectionImage.src = "images/minus.gif";
    }
  }
}

function rollOpenSection(sectionId, animationTime)
{
  var elementToRoll = document.getElementById(sectionId+"_content");
  if(elementToRoll && !isShown(sectionId+"_content"))
  {
    rollDown(sectionId+"_content", animationTime)
    var sectionImage = document.getElementById(sectionId+"_plusMinusImage");
    if(sectionImage)
    {
      sectionImage.src = "images/minus.gif";
    }
  }
}


function toggleEditorMode(mode)
{
    var result = false;

    if (toggleEditorModeConfirm(mode))
    {
        var element1 = document.getElementById('productTypePhysical');
        var element2 = document.getElementById('productTypeDigital');
        var element3 = document.getElementById('productTypeBundle');

        var s = 'standard';

        if (element1.checked)
        {
          s = 'standard';
        } else if (element2.checked) {
          s = 'digital';
        } else if (element3.checked) {
          s = 'bundle';
        }

				document.getElementById('editMode').value = mode;
        if (s == 'standard')
        {
          toggleStandardProduct();
        } else if (s == 'digital') {
          toggleDigitalProduct();
        } else if (s == 'bundle') {
          toggleProductBundle();
        } else {
          toggleStandardProduct();
        }
        
        result = true;
    }
    
    return result;
}

function toggleStandardProduct()
{
    document.getElementById('editProductForm').action='newProduct.hg'; 
    document.getElementById('editProductForm').submit();
}

function toggleDigitalProduct()
{
    document.getElementById('editProductForm').action='digitalProductEdit.hg'; 
    document.getElementById('editProductForm').submit();
}

function toggleProductBundle()
{
    document.getElementById('editProductForm').action='newProduct.hg'; 
    document.getElementById('editProductForm').submit();
}


function toggleEditorModeConfirm(mode)
{
    var digitalProductType = document.getElementById('productTypeDigital');
    
    var result = true;
    var digitalProductFlag = false;
    var smallImageFlag = false;
    var largeImageFlag = false;
    var zoomImageFlag = false;
    
    if (digitalProductType)
    {
        if (digitalProductType.checked)
        {
            var digitalProductName = document.getElementById('digitalFileName');
            if (digitalProductName)
            {
                if (digitalProductName.value != '')
                {
                    digitalProductFlag = true;
                }
            }
        }
    }
    
    var smallImageType = document.getElementById('smallImageFileCheckBox');
    if (smallImageType)
    {
        if (smallImageType.checked)
        {
            var smallImageName = document.getElementById('smallImageFile');
            if (smallImageName)
            {
                if (smallImageName != '')
                {
                    smallImageFlag = true;
                }
            }
        }
    }

    var largeImageType = document.getElementById('largeImageFileCheckBox');
    if (largeImageType)
    {
        if (largeImageType.checked)
        {
            var largeImageName = document.getElementById('largeImageFile');
            if (largeImageName)
            {
                if (largeImageName != '')
                {
                    largeImageFlag = true;
                }
            }
        }
    }
    
    var zoomImageType = document.getElementById('zoomImageFileCheckBox');
    if (zoomImageType)
    {
        if (zoomImageType.checked)
        {
            var zoomImageName = document.getElementById('zoomImageFile');
            if (zoomImageName)
            {
                if (zoomImageName != '')
                {
                    zoomImageFlag = true;
                }
            }
        }
    }
    
    
    if (digitalProductFlag || smallImageFlag || largeImageFlag || zoomImageFlag)
    {
        result = confirm('You are attempting to change between the Advanced and Basic Product forms. Any files recently uploaded, for either downloadable products or product images, must be saved prior to switching forms.\n\nIf you proceed without saving, you will have to upload the files again. This affects files uploaded to the Quick Shopping Cart servers, it will not remove or "lose" any files on your computer hard drive.\n\nClick OK to switch forms. Click Cancel to return to the active form and save all recent changes.');
    }
    
    return result;
}

/***********************************************************************************************************/
/*                                           MANUFACTURERS                                                 */
/***********************************************************************************************************/

function createManufacturer(eventObj)
{


  var manufacturerFrame = document.getElementById("newManufacturerFrame");
  if(!manufacturerFrame)
  {
    var eventX = eventObj.clientX;
    var eventY = eventObj.clientY;
    manufacturerFrame = document.createElement("IFRAME");
    document.body.appendChild(manufacturerFrame);
    manufacturerFrame.src = "newManufacturer.hg";
    manufacturerFrame.style.visibility='visible';
    manufacturerFrame.style.display = "block";
    manufacturerFrame.style.position="absolute";
    manufacturerFrame.style.width="350px";
    manufacturerFrame.style.height="100px";
    manufacturerFrame.style.top = (eventY + document.body.scrollTop) + 'px';
    manufacturerFrame.style.left = (eventX + document.body.scrollLeft) + 'px';    
  }
}

function insertNewManufacturer(mfgId, mfgName)
{
  var newOption = document.createElement("OPTION");
  newOption.setAttribute('value', mfgId);
  newOption.innerHTML = mfgName;
  
  var selectBox = document.getElementById('manufacturerDropDown');
  if (selectBox)
  {
    selectBox.appendChild(newOption);
  }
  
  newOption.selected = true;
  
  hideElementWithId('newManufacturerPopup-table');
  
  frames['newManufacturerPopup-frame'].location.href='newManufacturer.hg';
}

/***********************************************************************************************************/
/*                                             CATEGORIES                                                  */
/***********************************************************************************************************/


function insertNewCategory(categoryId, parentId, label)
{
    var categorySelectBox = document.getElementById('categoryDropDownSelectBox');
    
    //If this is the quick form this element will exist, otherwise this is the 
    //advanced form
    if (categorySelectBox)
    {
      //Since the select box has a different label format, we need to fix our label.  If
      //the parent is the root, then we just need to insert it.
      var newLabel = label;
      var options = categorySelectBox.options;
      if (parentId != 1)
      {
          if (options)
          {
            for (var i = 0; i < options.length; i++)
            {
                if (options[i].value == parentId)
                {
                    newLabel = options[i].innerHTML + ' >> ' + label;
                    break;
                }
            }
          }
      }
      
      var newOption = document.createElement('OPTION');
      newOption.value = categoryId;
      newOption.innerHTML = newLabel;
      
      
      //We start the index at one to skip the default "No Category" entry
      var didInsert = false;
      for (var i = 1; i < options.length; i++)
      {
        if (newLabel < options[i].innerHTML)
        {
            categorySelectBox.insertBefore(newOption, options[i]);
            didInsert = true;
            break;
        }
      }
      
      if (!didInsert)
      {
        categorySelectBox.appendChild(newOption);
      }
      
      newOption.selected = true;
    } else {
        insertNewCategoryInAdvancedEditor(categoryId, parentId, label);
    }
    
    hideElementWithId('newCategoryPopup-table');
    //frames['newCategoryPopup-frame'].history.go(-1);
	frames['newCategoryPopup-frame'].location.href='categoryPopup.hg';
}

function insertNewCategoryInAdvancedEditor(categoryId, parentId, label)
{
  var categoryElement = buildCategorySpan(categoryId, label); 
  if(parentId == 1)
  {
    var categoryContent = document.getElementById("category_content");
    if(categoryContent)
    {
      categoryContent.appendChild(categoryElement);
    }
  }
  else
  {
    var parentCategory = document.getElementById('product_category_tree_'+parentId);
    if(parentCategory)
    {
      parentCategory.appendChild(categoryElement);
    }
  }
}

function buildCategorySpan(categoryId, label)
{
  var indentSpan = document.createElement("SPAN");
  indentSpan.className = "category-tree-menu";
  indentSpan.style.display = "block";
  indentSpan.style.marginLeft = "25px";
  indentSpan.id="product_category_tree_"+categoryId;
  
  indentSpan.innerHTML = "&#160;&#160;"+
    "<span style='cursor: pointer' class=\"product-in-category\" onClick=\"clickTextToToggle('product_category_"+categoryId+"'); toggleCategoryToProduct('"+categoryId+"', this);\" onMouseOver=\"if(!document.getElementById('product_category_"+categoryId+"').checked){this.className = 'product-tab-hover'};\" onMouseOut=\"if(!document.getElementById('product_category_"+categoryId+"').checked){this.className = 'product-not-in-category'};\">"+
      "<input id=\"product_category_"+categoryId+"\" type=\"checkbox\" name=\"product.categories("+categoryId+").categoryId\" value=\""+categoryId+"\" onClick=\"clickTextToToggle('product_category_"+categoryId+"'); toggleCategoryToProduct('"+categoryId+"', this);\" checked=\"checked\"/>"+
      "<span id=\"category_label_"+categoryId+"\">"+label+"</span>"+
    "</span>";
  
  return indentSpan;
}


/***********************************************************************************************************/
/*                                         WIZARD INTEGRATION                                              */
/***********************************************************************************************************/

function checkForValidProduct() {
  if ( ( strTrim(editProductForm['product.chars.partNumber'].value ).length > 0) || 
        ( strTrim(editProductForm['product.chars.label'].value ).length > 0) ) {
        
    return true;
    
  }
  
  return false;
}

function clickWizardButton( direction ) {
   if ( checkForValidProduct() ) { 
      if ( editProductForm.onsubmit() ) { 
         editProductForm.wizardAction.value = 'wizard' + direction; 
         editProductForm.submit();
      }
      return false;
   } else {
      return true;
   }
}

/***********************************************************************************************************/
/*                                         Images 			                                               */
/***********************************************************************************************************/


function displayFlashPreview()
{
	var zoomImage = document.getElementById('zoomProductInput').value;
	var zoomPreviewImage = document.getElementById('zoomPreviewImageId').value;
	
	window.open('flashViewer.sc?zoomImage=displayImage.hg?binaryDataId=' + zoomImage + '&zoomPreviewImage=displayImage.hg?binaryDataId=' + zoomPreviewImage, 'ZoomImage', 'width=485, height=380');
}// begin reportManager.js

// Constants
var MONTH = 'month';
var WEEK = 'week';

var reportTypes = {
	'grossTotalSales' : '',
	'netTotalSales'  : '',
	'salesByMonth' : MONTH,
	'salesByDay' : WEEK,
	'salesPerProduct' : WEEK,
	'salesBySourceCode' : WEEK,
	'salesByState' : '',
	'ordersPerDay' : WEEK,
	'totalShipping' : '',
	'totalTaxes' : '',
	'storefrontSearch' : MONTH
}
var WEEK_MILLIS = 0;
var MONTH_MILLIS = 0;

var now = new Date();

var lastWeek = new Date();
lastWeek.setTime(now.getTime() - WEEK_MILLIS);

var lastMonth = new Date();
if(lastMonth.getDate() == 1){
	var month = lastMonth.getMonth();
	if(month == 0){
		lastMonth.setYear(lastMonth.getYear() - 1 );
		lastMonth.setMonth(11);
	}else{
		lastMonth.setMonth(month - 1);
	}
}else{
	lastMonth.setDate(1);
}
var modYear = false;
if(now.getYear() < 2000){
	modYear = true;
}

function createDateString(date){
	var month = date.getMonth() + 1;
	var monthday = date.getDate();
	var year = date.getYear();
	if(modYear) {
		year = year + 1900;
	}
	var dateString = month + '/' + monthday + '/' + year;
	 return dateString;
}

var todayString = createDateString(now);
var weekString = createDateString(lastWeek);
var monthString = createDateString(lastMonth);

var previousPick = 'grossTotalSales';
function userModified(){
	var startDate = document.getElementById('startDate');
	var endDate = document.getElementById('endDate');

	if(reportTypes[previousPick] == WEEK ){
		return !(startDate.value == weekString && endDate.value == todayString );
	}else	if(reportTypes[previousPick] == MONTH ){
		return !(startDate.value == monthString && endDate.value == todayString);
	}else {
		return !(startDate.value == '' && endDate.value == '' );
	}
}

function setDefaultDateRange(reportType){
	if(previousPick != reportType && !userModified()){
		var startDate = document.getElementById('startDate');
		var endDate = document.getElementById('endDate');

		if(reportTypes[reportType] == WEEK){
			startDate.value = weekString;
			endDate.value = todayString;
		}else if(reportTypes[reportType] == MONTH){
			startDate.value = monthString;
			endDate.value = todayString;
		}else {
			startDate.value = '';
			endDate.value = '';
		}
	}
	previousPick = reportType;
}

// end reportManager.js/************************************************/
/*                  ROLES                     */
/************************************************/

// cancel
function cancelRole( ) {
   var tBody = document.getElementById( 'roleGroups' );
     
   if ( isShown( 'optionValueEditorCell') && !confirm( 'Are you sure you want to discard the changes you have made to the ' +
                                                       document.getElementById('label').value + ' role?' ) ) 
      return;

   tlDeselectRow( tBody );
   
   var valueTBody = document.getElementById( 'customRoleValues' );
   
   // clear the rows
   tlClear( valueTBody, optionIdFilter );
   showElementWithId( 'noRolesRow' );
   
   // clear the value
   document.getElementById('label').value = '';   
   
   // clear the option hidden id
   document.getElementById( 'roleId' ).value = '';

   // hide the editor
   hideElementWithId( 'roleValueEditorCell' );   
   showElementWithId( 'addRoleButton' );
   hideElementWithId( 'addRoleButtonSpacer' );   
}

// groups
function editRole( index ) {
   var tBody = document.getElementById( 'roleGroups' );
   
   var cellId = 'roleGroupLabelCell' + index;
   
   if ( isShown( 'roleValueEditorCell') && !confirm( 'Are you sure you want to discard the changes you have made to the ' +
                                                       document.getElementById('label').value + ' role?' ) ) 
      return;
   

   var valueTBody = document.getElementById( 'customRoleValues' );
   
   // clear the rows
   tlClear( valueTBody, roleIdFilter );
   showElementWithId( 'noRolesRow' );   

   if ( tlClickRow( tBody, cellId, 'selection-highlight' ) ) {
      // just selected
      
      // copy the value
      document.getElementById('roleName').value = 
           strTrim( document.getElementById(cellId).getElementsByTagName('A')[0].innerHTML );
      
      
      // copy the rows     
      var valueListTBody = 
           document.getElementById( 'all_roleValuesList' + index);
      
      
      var rowCount = 
           copyRoleValuesTable( index, valueListTBody );
      
      updateRoleButtons( valueTBody );      
      if ( rowCount > 0 ) {
         tlRestoreAlternatingRowStyle( valueTBody, roleIdFilter );
         hideElementWithId( 'noRolesRow' );         
      }
      
      // set the option hidden id
      document.getElementById( 'roleId' ).value = index;
      
      // display the editor
      showElementWithId( 'roleValueEditorCell' );
      hideElementWithId( 'addRoleButton' );   
      showElementWithId( 'addRoleButtonSpacer' );
   
   
   } else {
      // just deselected
      
      // clear the value
      document.getElementById('label').value = '';
      
      
      // clear the option hidden id
      document.getElementById( 'roleId' ).value = '';
      
      // hide the editor
      hideElementWithId( 'roleValueEditorCell' );   
      showElementWithId( 'addRoleButton' );
      hideElementWithId( 'addRoleButtonSpacer' );
   
   }
}

function copyRole( index ) {
   var tBody = document.getElementById( 'roleGroups' );
   
   var cellId = 'roleGroupLabelCell' + index;
   
   if ( isShown( 'roleValueEditorCell') && !confirm( 'Are you sure you want to discard the changes you have made to the ' +
                                                       document.getElementById('label').value + ' role?' ) ) 
      return;
   
   
   var valueTBody = document.getElementById( 'customRoleValues' );
   
   // clear the rows
   tlClear( valueTBody, roleIdFilter );
   showElementWithId( 'noRolesRow' );   

   // copy the value
   document.getElementById('label').value = 'Copy of ' + 
        strTrim( document.getElementById(cellId).getElementsByTagName('A')[0].innerHTML );

   // copy the rows     
   var valueListTBody = 
        document.getElementById( 'all_roleValuesList' + index );

   var rowCount = 
        copyRoleValuesTable( index, valueListTBody );


   updateRoleButtons( valueTBody );      
   if ( rowCount > 0 ) {
      tlRestoreAlternatingRowStyle( valueTBody, roleIdFilter );
      hideElementWithId( 'noRolesRow' );         
   }

   // set the option hidden id
   document.getElementById( 'roleId' ).value = -1;

   // display the editor
   showElementWithId( 'roleValueEditorCell' );
   hideElementWithId( 'addRoleButtonRow' );   
}

function addRole( ) {
   var tBody = document.getElementById( 'roleGroups' );
       
   var valueTBody = document.getElementById( 'customRoleValues' );
   
   // clear the rows
   tlClear( valueTBody, roleIdFilter );
   showElementWithId( 'noRolesRow' );   
   updateRoleButtons( valueTBody );      

	var valueListTBody = 
    document.getElementById( 'default_roleValuesList');
      
      var rowCount = 
           copyRoleValuesTable( -1 , valueListTBody );

      updateRoleButtons( valueTBody );
      
      tlRestoreAlternatingRowStyle( valueTBody, roleIdFilter );
      
   // set the option hidden id
   document.getElementById( 'roleId' ).value = -1;

   // display the editor
   showElementWithId( 'roleValueEditorCell' );
   hideElementWithId( 'addRoleButtonRow' );   
}

function copyRoleValuesTable( index, sourceTBody ) {
  var rowCount = 0;
  var matcher = new RegExp( "^role_" + index + "_value_(\\d+)$" );

  var valueTBody = document.getElementById( 'customRoleValues' );

  var trs = sourceTBody.getElementsByTagName('TR');
  var i;

  for ( i = 0; i < trs.length; i++ ) {
     var elem = trs[i].getElementsByTagName('TD')[0];

     if ( elem == null || elem.id == null || elem.id == '' ) {
        // ignore this row
     } else if ( matcher.test( elem.id ) ) {

        var valueId = RegExp.$1;

        rowCount++;

        tlAddRow( valueTBody, roleIdFilter, tlLastNumberParser, customRoleGenerator, 
                  strTrim( elem.getElementsByTagName('SPAN')[0].innerHTML ), valueId );


     } else {
        break;
     }

     elem = elem.nextSibling;      
  }
  
  return rowCount;
}


// values
function roleIdFilter( idString ) {
   if ( !idString || idString == '' || idString == 'addRoleRow' || idString == 'noRolesRow' )
      return true;
}

function clickRole( index ) {
  var tBody = document.getElementById('customRoleValues');
  tlClickRow(tBody, 'roleCell' + index, 'selection-highlight');
  
  updateRoleButtons( tBody );
}

function moveUpRole() {
  var tBody = document.getElementById('customRoleValues');

   if ( tBody.selectedRow ) {
     var td = document.getElementById( tBody.selectedRow );
     var tr = td.parentNode;
     
     var parent = tr.parentNode;
     
     if ( tlGetPreviousSibling( tr, roleIdFilter ) ) {
        var sib = tlGetPreviousSibling( tr, roleIdFilter );
     
        parent.removeChild( tr );
        
        parent.insertBefore( tr, sib );
        
        swapSortOrderValues( tr, sib );
        
        updateRoleButtons( tBody );
        tlRestoreAlternatingRowStyle( tBody, roleIdFilter );
        
     }
   }
}

function moveDownRole() {
  var tBody = document.getElementById('customRoleValues');

   if ( tBody.selectedRow ) {
     var td = document.getElementById( tBody.selectedRow );
     var tr = td.parentNode;
     
     var parent = tr.parentNode;
     
     if ( tlGetNextSibling( tr, roleIdFilter ) ) {
        var sib = tlGetNextSibling( tr, roleIdFilter );
        
        parent.removeChild( sib );
        
        parent.insertBefore( sib, tr );
        
        swapSortOrderValues( tr, sib );
        
        updateRoleButtons( tBody );
        tlRestoreAlternatingRowStyle( tBody, roleIdFilter );
     }
   }
}

/*function swapSortOrderValues( tr1, tr2 ) {
   var index1 = tlLastNumberParser( tr1.id );
   var index2 = tlLastNumberParser( tr2.id );
   
   var temp = document.getElementById( 'optionValueSortOrder' + index1 ).value;
   document.getElementById( 'optionValueSortOrder' + index1 ).value = 
      document.getElementById( 'optionValueSortOrder' + index2 ).value;
   document.getElementById( 'optionValueSortOrder' + index2 ).value = temp;
}*/

function updateRoleButtons( tBody ) {

  if ( tBody.selectedRow ) {
     //document.getElementById( "deleteRoleButton" ).src = "images/opval_delete.gif";
     
     var td = document.getElementById( tBody.selectedRow );
     
     var tr = td.parentNode;

/*
     if ( tlGetPreviousSibling( tr, roleIdFilter ) ) {
        document.getElementById( "moveUpRoleButton" ).src = "images/ibtn_moveup.gif";
     } else {
        document.getElementById( "moveUpRollButton" ).src = "images/ibtn_moveup_dis.gif";
     }

     if ( tlGetNextSibling( tr, rollIdFilter ) ) {
        document.getElementById( "moveDownRollButton" ).src = "images/ibtn_movedown.gif";  
     } else {
        document.getElementById( "moveDownRollButton" ).src = "images/ibtn_movedown_dis.gif";  
     }     
 */
 
  } else {
  //   document.getElementById( "deleteRoleButton" ).src = "images/opval_delete_dis.gif";
  //   document.getElementById( "moveUpRoleButton" ).src = "images/ibtn_moveup_dis.gif";
  //   document.getElementById( "moveDownRoleButton" ).src = "images/ibtn_movedown_dis.gif";  
  }

}

function addCustomRole() { 
  var id, label;

  if ( arguments.length > 0 ) {
     label = arguments[0];
     
     if ( arguments.length > 1 ) {
        id = arguments[0];
     } else {
        id = -1;
     }       
  } else {
     id = -1;
     label = document.getElementById('addRoleLabel').value;  
     
     if ( label == null || label == '' ) {
        alert( 'Please specify a value for this option.' );
        document.getElementById('addRoleLabel').focus();
        document.getElementById('addRoleLabel').select();
        return false;
     } else {
        document.getElementById('addRoleLabel').value = '';
     }
  }

  var tBody = document.getElementById('customRoleValues');
  
  var index = 
    tlAddRow( tBody, roleIdFilter, tlLastNumberParser, customRoleGenerator, label, id );
  tlRestoreAlternatingRowStyle( tBody, roleIdFilter );
  
  clickOption( index );
  
  updateRollButtons( tBody );
  
  hideElement( document.getElementById('noRoleRow') );
}

function customRoleGenerator( index, params, checked ) {
   var label = params[0];
   
   var id = -1;
   
   if ( params.length > 1 ) {
       id = params[1];          
   }
   
   
   var trTag = document.createElement("tr");    
   trTag.setAttribute('id', 'roleRow' + index);
   
   var tdTag = document.createElement("td");
   tdTag.setAttribute('id', 'roleCell' + index);
   tdTag.align = 'left';
   tdTag.valign = 'top';
   tdTag.width = '100%';
   tdTag.onclick = function() { clickRole( index ) };
   
   
   var matcher = new RegExp("CHECKED|checked");
   
   if( matcher.test(label) )
   {
      var removeHTML = new Array();
   		removeHTML = label.split('>');
   		
   		var test = new Array();
   		
   		test = removeHTML[1].split('value=');
   		test = test[1].split(' ');
   
   		label = removeHTML[2];
   		
   		
   		/*FireFox splits the strings differently than IE
   		  This will correctly reformat the string for FireFox */
   		if(test[0].charAt(0) == '"')
   		{
   			test[0] = test[0].substr(1, test[0].length -2);
   		}
   
   		
   		tdTag.innerHTML =  '<table width="100%" cellspacing="0" cellpadding="0"><tr> <td width="25"> <input name="privilegeLabel(' + index + ')" id="label" type="checkbox" tabindex="1" checked="true" value="' + test[0] +'" /> </td>' + 
   					  '<td> <a href="#" onClick="return false;">' + label + '</a>' +
                      '<input type="hidden" name="roleLabel(' + index + ')" value="' + label + '"/>' +
                      '<input type="hidden" name="roleValueId(' + index + ')" value="' + id + '"/>' +
                      '<input type="hidden" id="roleValueSortOrder' + index +'" name="rollSort(' + index +')" value="' + index + '" size="2"/> </td> </tr> </table>';
   }
   else
   {
   		var removeHTML = new Array();
   		removeHTML = label.split('>');
   
      	var test = new Array();
   		
   		test = removeHTML[1].split('value=');
   		test = test[1].split(' ');
   		
   		label = removeHTML[2];
   		
   		if(test[0].charAt(0) == '"')
   		{
   			test[0] = test[0].substr(1, test[0].length -2);
   		}
   		
   		tdTag.innerHTML =  '<table width="100%" cellspacing="0" cellpadding="0"><tr> <td width="25"> <input name="privilegeLabel(' + index + ')" id="label" type="checkbox" tabindex="1" value="' + test[0] +'" /> </td>' + 
   					  '<td> <a href="#" onClick="return false;">' + label + '</a>' +
                      '<input type="hidden" name="roleLabel(' + index + ')" value="' + label + '"/>' +
                      '<input type="hidden" name="roleValueId(' + index + ')" value="' + id + '"/>' +
                      '<input type="hidden" id="roleValueSortOrder' + index +'" name="rollSort(' + index +')" value="' + index + '" size="2"/> </td> </tr> </table>';
   }
                       
   trTag.appendChild( tdTag );
   
   return trTag;   
}

function deleteCustomRole()
{
  var tBody = document.getElementById('customRollValues');

  var index;
  var rollId;
  if ( arguments.length > 0 ) {
     rollId = arguments[o];
     index = tlLastNumberParser( rollId );
  } else {
     if ( tBody.selectedRow ) {
        index = tlLastNumberParser( tBody.selectedRow );
        rollId = 'rollRow' + index;
        
     } else {
        return false;
     }  
  }
  
  var toSelect = null;
  if ( tBody.selectedRow == ('rollCell' + index) ) {
     var td = tlDeselectRow( tBody );
     var tr = td.parentNode;
     
     if ( tlGetNextSibling( tr, rollIdFilter ) ) {
        toSelect = 'rollCell' + tlLastNumberParser( tlGetNextSibling( tr, rollIdFilter ).id );
     } else if ( tlGetPreviousSibling( tr, rollIdFilter ) ) {
        toSelect = 'rollCell' + tlLastNumberParser( tlGetPreviousSibling( tr, rollIdFilter ).id );
     }
  }  

  tlDeleteRow( tBody, rollId );
 
  tlRestoreAlternatingRowStyle( tBody, rollIdFilter );
  
  if ( toSelect != null ) {
     tlSelectRow(tBody, toSelect, 'selection-highlight');
  }
  
  updateOptionButtons( tBody );  
  
  if ( tlIsEmpty( tBody, rollIdFilter ) ) {
     showElement( document.getElementById('noRolesRow') );
  }
}

function validateRoleForm()
{
	var name = document.getElementById('roleName');
	
	if(name.value.length == 0)
	{
		alert("The role name is empty, please assign it a value.");
		return false;
	}
	
	/*var matcher = new RegExp();
	var listofroles = document.getElementById('roleList');
   	matcher.compile('/^' + name.value + '$/');
   
   if(matcher.test(listofroles.innerHTML) )
   {
   	alert("Role name is already in use");
   	return false;
   }*/
   
	return true;
}

function insertNewRole(roleId, roleName)
{
  var newOption = document.createElement("OPTION");
  newOption.setAttribute('value', roleName);
  newOption.innerHTML = roleName;
  
  var selectBox = document.getElementById('rolesList');
  if (selectBox)
  {
    selectBox.appendChild(newOption);
  }
  
  newOption.selected = true;
  
  hideElementWithId('newRolePopup-table');
  
  //frames['newRolePopup-frame'].history.go(-1);
	frames['newRolePopup-frame'].location.href='newRole.hg';
}
function customWeightFilter( idStr ) {
  return idStr == 'weightTableHeader' || idStr == 'addWeightRow';
}

function customWeightParser( idStr ) {
  return parseInt( idStr.substring( 15, idStr.length ) );
}

function setMinWeightBasedOffMaxWeight(maxWeightIndex)
{
  var maxWeightElement = document.getElementById('maxWeights_'+maxWeightIndex);
  var minWeightElement = document.getElementById("minWeights_"+(maxWeightIndex+1));
  if(maxWeightElement && minWeightElement)
  {
    minWeightElement.value = maxWeightElement.value;
  }
}

function customWeightRowGenerator( index ) {
  var trTag = document.createElement("tr");
  var lastMaxValueElement = document.getElementById('maxWeights_'+(index-1));
  var lastMaxValue = lastMaxValueElement ? lastMaxValueElement.value : '0';
  
  trTag.setAttribute('id', 'customWeightRow' + index);
  
  var tdLineNumber = document.createElement("td");
  tdLineNumber.setAttribute('align', 'center');
  tdLineNumber.setAttribute('id', index);
  tdLineNumber.style.borderWidth = '1px';
  tdLineNumber.style.borderStyle = 'none solid solid none';
  tdLineNumber.style.borderColor = '#003366';
  	tdLineNumber.innerHTML = index;
  	

  var tdTagMinWeight = document.createElement("td");
  tdTagMinWeight.setAttribute('align', 'center');
  tdTagMinWeight.style.borderWidth = '1px';
  tdTagMinWeight.style.borderStyle = 'none solid solid none';
  tdTagMinWeight.style.borderColor = '#003366';
  tdTagMinWeight.innerHTML = '<input class="formfield" style="text-align: right;" type="text" '+
    'value="'+lastMaxValue+'" name="customShippingBean.minWeights(' + index + ')"' +
    ' id="minWeights_' + index + '" size="5" />' +
    '<input type="hidden" name="customShippingBean.lineId(' + index + ')" value="' + index + '"/>';


  var tdTagMaxWeight = document.createElement("td");
  tdTagMaxWeight.setAttribute('align', 'center');
  tdTagMaxWeight.style.borderWidth = '1px';
  tdTagMaxWeight.style.borderStyle = 'none solid solid none';
  tdTagMaxWeight.style.borderColor = '#003366';
  tdTagMaxWeight.innerHTML = '<input class="formfield" style="text-align: right;" id="maxWeights_'+index+'" type="text" '+
    'value="" name="customShippingBean.maxWeights(' + index + ')" onChange="setMinWeightBasedOffMaxWeight('+index+')"' +
                         ' id="maxWeights_' + index + '" size="5" />';

  var tdTagFee = document.createElement("td");
  tdTagFee.setAttribute('align', 'center');
  tdTagFee.style.borderWidth = '1px';
  tdTagFee.style.borderStyle = 'none solid solid none';
  tdTagFee.style.borderColor = '#003366';
  tdTagFee.innerHTML = '$<input class="formfield" style="text-align: right;" type="text" '+
    'value="" name="customShippingBean.fees(' + index + ')"' +
                         ' id="fees_' + index + '" size="7" onBlur="this.value = validatePrice(this.value)"/>';

  var tdTagDeleteButton = document.createElement("td");
  tdTagDeleteButton.setAttribute('align', 'center');
  tdTagDeleteButton.style.borderWidth = '1px';
  tdTagDeleteButton.style.borderStyle = 'none none solid none';
  tdTagDeleteButton.style.borderColor = '#003366';
  tdTagDeleteButton.setAttribute('id', 'deleteLink_' + index);
  tdTagDeleteButton.innerHTML = '<a href="" onClick="deleteCustomWeight(\'customWeightRow' + index + '\'); return false;" onMouseOut="swapImageRestore()" onMouseOver="swapImage(\'deleteWeightButton_' + index + '\',\'\',\'images/icon_delete_over.gif\',1)">' +
                                '<img id="deleteWeightButton_' + index + '" src="images/icon_delete.gif" alt="Delete" title="Delete" border="0"/></a>';

  trTag.appendChild(tdLineNumber);
  trTag.appendChild(tdTagMinWeight);
  trTag.appendChild(tdTagMaxWeight);
  trTag.appendChild(tdTagFee);
  trTag.appendChild(tdTagDeleteButton);
  
  return trTag;
}

function addCustomWeight()
{
    var tBody = document.getElementById('customWeightTbody');
    if (tBody)
    {
       tlAddRow( tBody, customWeightFilter, customWeightParser, customWeightRowGenerator );
    }
}

function deleteCustomWeight(weightId)
{
  var tBody = document.getElementById('customWeightTbody');

  if (tBody)
  {
    tlDeleteRow( tBody, weightId );
  }
}

function checkCustomWeights() {
  var tBody = document.getElementById('customWeightTbody');
  if (tBody)
  {
    var ruleCount = ( tBody.getElementsByTagName("TR").length - 2 ); // header row and new sale price row
    
    var rangeLow = new Array(0);
    var rangeHigh = new Array(0);
    
    var i;
    var j;
    
    var trNodeList = tBody.getElementsByTagName("TR");
      
    var trArray = new Array(0);
    
    for (i = 0; i < trNodeList.length; i++) {
       if (! customWeightFilter( trNodeList[i].id )) {         
          trArray.push( customWeightParser( trNodeList[i].id ) );
       }
    }
             
    trArray.sort( shippingSort );    
    var index = 0;


    var gapFound = true;
    for (i = 0; i < trArray.length; i++)
    {
     
       var intId = trArray[i];
       
       // check valid range
       var minWeight;
       var maxWeight;
       minWeight = parseFloat( document.getElementById('minWeights_' + intId ).value );
       maxWeight = parseFloat( document.getElementById('maxWeights_' + intId ).value );         
       
       if ( minWeight >= maxWeight ) {
          alert( 'Your maximum must be larger than your minimum in rule ' + (i+1) );
          document.getElementById('maxWeights_' + intId ).focus();
          document.getElementById('maxWeights_' + intId ).select();         
          return false;
       }

       // check intersections
       for ( j = 0; j < rangeLow.length; j++ ) {
          var minWeightCompare = rangeLow[j];
          var maxWeightCompare = rangeHigh[j];

          if ( ((minWeight < minWeightCompare) && (maxWeight > minWeightCompare)) ||
               ((minWeight < maxWeightCompare) && (maxWeight > maxWeightCompare)) ) {

            alert( 'Rules ' + (j+1) + ' and ' + (i+1) + ' have overlapping ranges.' );
            return false;
          }
       }

       rangeLow.push( minWeight );
       rangeHigh.push( maxWeight );         
    }

    rangeLow.sort(compareNum);
    rangeHigh.sort(compareNum);
    var previousHigh = rangeLow[0];
    for(i=0; i<rangeLow.length; i++) {
      var low = rangeLow[i];
      var high = rangeHigh[i];

      if (low > previousHigh) {
        alert('You did not assign a shipping fee for the values between ' + previousHigh  + ' ' +
              ' and ' + low);
        return false;
      }

      previousHigh = high;
    }  
  }

  return true;
}

function compareNum(a, b) {
  return a-b;
}

function shippingSort(intA, intB) {         
   return parseInt(intA - intB);
}


function validateCustomShipping() {
  var handlingFee = document.getElementById("handlingFee");
  if(!isSignedFloat(handlingFee.value))
  {
    warnInvalid(handlingFee, 'Please specify a valid handling fee.');
    return false;  
  }
  else if(parseFloat(handlingFee.value) < 0)
  {
    warnInvalid(handlingFee, 'Handling Fee must be a positive value.');
    return false;  
  }

  return checkCustomWeights(); 
}

function toggleShippingType(toType)
{
	var minHeader = document.getElementById('minAmountColumn');
	var maxHeader = document.getElementById('maxAmountColumn');
	var weightBox1 = document.getElementById('weightBasedType1');
	var weightBox2 = document.getElementById('weightBasedType2');
	
	if(toType == 'dollar')
	{
		minHeader.innerHTML = "Min. Amount ($):";
		maxHeader.innerHTML = "Max. Amount ($):";
		weightBox1.disabled = true;
		weightBox2.disabled = true;
	}
	else
	{
		minHeader.innerHTML = "Min. Weight (lbs):";
		maxHeader.innerHTML = "Max. Weight (lbs):";
		weightBox1.disabled = false;
		weightBox2.disabled = false;
	}
}

// A unique index that should only be incremented and is used only to uniquely identify the object in the controller.
var uniqueShippingBoxIdx = 0;

function togglePackagingRows()
{
  var packMethod = getRadioButtonValue(document.getElementsByName("thirdPartyShippingBean.attributes(packMethod)"));
  
  if (packMethod == "separate")
  {
  	hideElementWithId("applyHandlingFee");
  	hideElementWithId("maxPackageWeight");
  	hideElementWithId("shippingBoxTable");
  }
  else
  {
  	showElementWithId("applyHandlingFee");
  	showElementWithId("maxPackageWeight");
  	showElementWithId("shippingBoxTable");
  }
}

function addShippingBox(id)
{
  var bottom = document.getElementById("addBtnRow");

  uniqueShippingBoxIdx++;
  
  var newDiv = document.createElement("div");
  newDiv.id = "shipBox_" + uniqueShippingBoxIdx;
  newDiv.className = "row";

  var baseName = "thirdPartyShippingBean.shippingBoxMap(" + uniqueShippingBoxIdx + ").";
  var hiddenId;
  if (id)
  {
    hiddenId = createShippingBoxHiddenInput(baseName + "id", id);
  }
  else
  {
    hiddenId = createShippingBoxHiddenInput(baseName + "id", "-1");
  }
  newDiv.appendChild(hiddenId);
  
  newDiv.appendChild(createShippingBoxNumberLabel(getNextShippingBoxNumber()));  
  newDiv.appendChild(createShippingBoxTextboxCol(baseName + "length"));
  newDiv.appendChild(createShippingBoxTextboxCol(baseName + "width"));
  newDiv.appendChild(createShippingBoxTextboxCol(baseName + "height"));
  newDiv.appendChild(createShippingBoxCheckboxCol(baseName + "active"));
  newDiv.appendChild(createShippingBoxDeleteBtn(newDiv));

  document.getElementById("shippingBoxTable").insertBefore(newDiv, bottom);
}

function createShippingBoxHiddenInput(name, value)
{
  var hInput = document.createElement("input");
  hInput.setAttribute("type", "hidden");
  hInput.setAttribute("name", name);
  hInput.setAttribute("value", value);
  return hInput;
}

function createShippingBoxTextboxCol(name)
{
  var col = document.createElement("span");
  col.className = "input";

  var txt = document.createElement("input");
  txt.className = "textfield";
  txt.setAttribute("type", "text");
  txt.setAttribute("size", "5");
  txt.setAttribute("name", name);

  col.appendChild(txt);
  return col;
}

function createShippingBoxCheckboxCol(name)
{
  var col = document.createElement("span");
  col.className = "input";

  var chk = document.createElement("input");
  chk.className = "checkfield";
  chk.setAttribute("type", "checkbox");
  chk.setAttribute("name", name);
  chk.setAttribute("value", "true");
  chk.setAttribute("checked", true);
  chk.setAttribute("defaultChecked", true);

  col.appendChild(chk);
  return col;
}

function createShippingBoxDeleteBtn(divToDelete)
{
  var col = document.createElement("span");
  col.className = "input";

  var img = document.createElement("img");
  img.setAttribute("title", "Delete");
  img.setAttribute("alt", "Delete"); 
  img.setAttribute("src", "images/icon_delete.gif");
  img.onclick = function() {
    deleteShippingBoxRow(divToDelete.id);
 	}
  img.setAttribute("border", "0");
  
  col.appendChild(img);
  return col;
}

function createShippingBoxNumberLabel(num)
{
  var boxLabel = document.createElement("span");
  boxLabel.className = "label";
  var text = document.createTextNode(num);
  boxLabel.appendChild(text);
  return boxLabel;
}

function deleteShippingBoxRow(divId)
{
  var div = document.getElementById(divId);
  document.getElementById("shippingBoxTable").removeChild(div);
  recalcShippingBoxNumbers();
}

// Returns the next number for the Box label (ie, the next row number in the shipping box table).
function getNextShippingBoxNumber()
{
  var table = document.getElementById("shippingBoxTable");
  var divs = table.getElementsByTagName("div");
  var numBoxes = 0;
  for (var i = 0; i < divs.length; i++)
  {
    var divId = divs[i].id;
    if (divId.indexOf("shipBox_") != -1)
    {
      numBoxes++;
    }
  }
  return numBoxes+1;
}

// Used when deleting boxes, this function makes sure the box number labels are sequential, starting with 1.
function recalcShippingBoxNumbers()
{
  var table = document.getElementById("shippingBoxTable");
  var divs = table.getElementsByTagName("div");
  var boxNum = 1;
  for (var i = 0; i < divs.length; i++)
  {
    var divId = divs[i].id;
    if (divId.indexOf("shipBox_") != -1)
    {
      var oldLabel = divs[i].getElementsByTagName("span")[0]; // should only be one
      var newLabel = createShippingBoxNumberLabel(boxNum);
      divs[i].replaceChild(newLabel, oldLabel);
      boxNum++;
    }
  }
}
function insertSiteVariable(textAreaId, selectBox)
{
  var selectedOption = selectBox.options[selectBox.selectedIndex];
  var text = selectedOption.value;
  var textArea = document.getElementById(textAreaId);
  if (textArea)
  {
    insertAtCursor(textArea, text);
  }
}
function checkProgress(appHost)
{
  var statusMsg = document.getElementById('statusText');
  var percentMsg = document.getElementById('percentComplete');
  if ( (statusMsg.innerHTML.toLowerCase().indexOf("error") == -1) &&
       (percentMsg.innerHTML != '100%') )
  {
    publishStatusHandler(appHost + 'publishStatus.hg');
    setTimeout('checkProgress(\'' + appHost + '\');', 1000);
  }
  // restart the timer, as all of the xmlhttprequests count as actions,
  // and restart the session counter on the server.
  Timer.refresh();
}

function publishStatusHandler(uri)
{
   var xmlDoc =  XmlDocument.create();
   xmlDoc.loadXML(getStatus(uri));
   var statusElement = xmlDoc.getElementsByTagName("status")[0];
   var status = statusElement.getAttribute("value");
   var percentElement = xmlDoc.getElementsByTagName("percentComplete")[0];
   var percent = percentElement.getAttribute("value");
   //setStatusBar(percent, status, el);
   updateStatusBar(percent, status);
}

function getStatus(uri)
{

  var xmlHttp = XmlHttp.create();

  // The following two lines are to force the browse not to return
  // a cached copy of the requested xml
  var timestamp = new Date();
  var uniqueURI = uri+(uri.indexOf("?") > 0 ? "&" : "?")+"timestamp="+timestamp.getTime();

  xmlHttp.open("GET", uniqueURI, false);
  xmlHttp.send(null);
  return xmlHttp.responseText;
}



function updateStatusBar(percentage, statusText)
{
    var tableWidth = 300;
    var cellTable = document.getElementById('cellTable');
    if (cellTable)
    {
        tableWidth = cellTable.width;
    }

    var percentComplete = Math.ceil( (parseFloat(percentage) / parseFloat(100)) * tableWidth );
    var percentLeft = tableWidth - percentComplete;
    if (percentLeft <= 0)
    {
        percentLeft = 1;
    }

    if (percentComplete <= 0)
    {
        percentComplete = 1;
    }

    var cell1 = document.getElementById('cell1');
    var cell2 = document.getElementById('cell2');

    if (cell1 && cell2)
    {
        if (isAgentAndVersion('IE', 0))
        {
            if (cell1.width == 0)
            {
                cell1.style.backgroundColor = '#003366';
            }
        } else {
            if (parseInt(cell1.width) == 0)
            {
                cell1.style.backgroundColor = '#003366';
            }
        }

        cell1.width = percentComplete;
        cell2.width = percentLeft;

        if (isAgentAndVersion('IE', 0))
        {
            if (cell2.width == 1)
            {
                cell2.style.backgroundColor = '#003366';
            }
        } else {
            if (parseInt(cell2.width) == 1)
            {
                cell2.style.backgroundColor = '#003366';
            }
        }

    }

    var percentMsg = document.getElementById('percentComplete');
    if (percentMsg)
    {
        percentMsg.innerHTML = percentage + '%';
    }

    var statusMsg = document.getElementById('statusText');
    if (statusMsg && (statusText != 'same'))
    {
        statusMsg.innerHTML = "Status: " + statusText;
    }

    if (percentage == '100')
    {
      if(document.getElementById('dnsPropogated').innerHTML == 'false')
      {
        window.location = "initialDeployment.hg";
      }
      else
      {
        showElementWithId('storefrontURL');
      }
    }
}


function sortTable(id, col)
{
  // This code is necessary for browsers that don't reflect the DOM
  // constants (like IE).
  if (document.ELEMENT_NODE == null)
  {
    document.ELEMENT_NODE = 1;
    document.TEXT_NODE = 3;
  }

  // Get the table section to sort.
  var tblEl = document.getElementById(id);

  // Set up an array of reverse sort flags, if not done already.
  if (tblEl.reverseSort == null)
  {
    tblEl.reverseSort = new Array();
  }

  // If this column was the last one sorted, reverse its sort direction.
  if (col == tblEl.lastColumn)
  {
    tblEl.reverseSort[col] = !tblEl.reverseSort[col];
  }

  // Remember this column as the last one sorted.
  tblEl.lastColumn = col;

  // Get the table section to sort.
  var tblEl = document.getElementById("siteTableData");

  // Set the table display style to "none" - necessary for Netscape 6 browsers.
  var oldDsply = tblEl.style.display;
  tblEl.style.display = "none";
  // Sort the rows based on the content of the specified column
  // using a selection sort.
  
  quickSort(tblEl.rows, 0, tblEl.rows.length - 1, col, tblEl.reverseSort[col]);
  cleanUp(tblEl); 

   //makePretty(tblEl, col);

  // Restore the table's display style.
  tblEl.style.display = oldDsply;

  return false;
}

function makePretty(tblEl, col)
{

  var i, j;
  var rowEl, cellEl;

  // Set style classes on each row to alternate their appearance.
  for (i = 0; i < tblEl.rows.length; i++)
  {
    rowEl = tblEl.rows[i];
    rowEl.className = rowEl.className.replace(rowTest, "");
    if (i % 2 != 0)
    {
      rowEl.className += " " + rowClsNm;
    }
    rowEl.className = normalizeString(rowEl.className);
    // Set style classes on each column (other than the name column) to
    // highlight the one that was sorted.
    for (j = 2; j < tblEl.rows[i].cells.length; j++)
    {
      cellEl = rowEl.cells[j];
      cellEl.className = cellEl.className.replace(colTest, "");
      if (j == col)
      {
        cellEl.className += " " + colClsNm;
      }
      cellEl.className = normalizeString(cellEl.className);
    }
  }

  var el = tblEl.parentNode.tHead;
  rowEl = el.rows[el.rows.length - 1];

  // Set style classes for each column as above.
  for (i = 2; i < rowEl.cells.length; i++)
  {
    cellEl = rowEl.cells[i];
    cellEl.className = cellEl.className.replace(colTest, "");
    // Highlight the header of the sorted column.
    if (i == col)
    {
      cellEl.className += " " + colClsNm;
    }
    cellEl.className = normalizeString(cellEl.className);
  }
}//start /utils/Array.js

Array.prototype.clear = function()
{
	this.length = 0;
}

Array.prototype.contains = function(element) 
{
	for (var i=0; i<this.length; i++) 
	{
		if (this[i] == element) 
		{
			return true;
		}
	}
	return false;
}

Array.prototype.removeElement = function(element) 
{
	for (var i=0; i<this.length; i++) 
	{
		if (this[i] == element) 
		{
			this.splice(i, 1);
		}
	}
}

Array.prototype.replaceElement = function(element, newElement) 
{
	for (var i=0; i<this.length; i++) 
	{
		if (this[i] == element) 
		{
			this.splice(i, 1, newElement);
		}
	}
}

Array.prototype.removeIndex = function(index) 
{
	for (var i=0; i<this.length; i++) 
	{
		if (i == index) 
		{
			this.splice(i, 1);
		}
	}
}
//end Array.js
//start /utils/Timer.js

Timer = {};

Timer.start = function(sessionExp)
{
	Timer.count = 0;
	Timer.sessionExp = sessionExp;
	sessionExp = ((sessionExp/60)-1);
	if(Timer._counter){
		clearInterval(Timer._counter);
	}
	Timer._counter = setInterval('Timer.counter('+ sessionExp +')', 60000);
}

Timer.counter = function(sessionExp)
{
	Timer.count++;
	if(Timer.count == sessionExp)
	{
		clearInterval(Timer._counter);
		Timer.countDown = 60;
		Timer._countDown = setInterval('Timer.displayMessage('+ sessionExp +')', 1000);
	}
	//console.log("Timer.count: "+Timer.count);
}

Timer.displayMessage = function(sessionExp)
{
	Timer.countDown--;
	if(Timer.countDown <= -1)
	{
		clearInterval(Timer._countDown);
		document.location = document.location;
	}
	else
	{
		var message = 'You will be logged out in <b>'+ Timer.countDown +'</b> seconds.'
						+ '&#160;&#160;<a href="javascript:xmlLoader(\'refreshSession.jsp\' , Timer.refresh);">Click here to remain logged in.</a>';

		if(Timer.countDown == 59)
		{
			Dialog.openWarning(message);
			if (Utils.ge('contentDiv') != null) Utils.ge('contentDiv').scrollTop = 0;
			if (Utils.ge('contentDiv_jsp') != null) Utils.ge('contentDiv_jsp').scrollTop = 0;
		}
		else
		{
			document.getElementById('warningDialogMessage').innerHTML = message;
		}
	}
}

Timer.refresh = function()
{
	Timer.start(Timer.sessionExp, Timer.displayElement);
	clearInterval(Timer._countDown);
	Dialog.closeWarning();
}

//end Timer.js//start utils/Utils.js

Utils = {};

Utils.ge = function(id)
{
	return document.getElementById(id);
}

Utils.toggle = function(id)
{
	Utils.ge(id).style.display = ( Utils.ge(id).style.display == 'none' ) ? '' : 'none';
}

Utils.toggleContent = function(id, content, content2)
{
	Utils.ge(id).innerHTML = ( Utils.ge(id).innerHTML == content ) ? content2 : content;
}

Utils.debug = function(val)
{
	Utils.ge('debug').innerHTML += val +"<br/>";
}

Utils.getTarget = function(evt)
{
	return t = (evt.target) ? evt.target : evt.srcElement;
}

Utils.addIframe = function(id, el)
{
	if(document.getElementById(id) == null)
	{
		var _iframe = document.createElement("iframe");
		_iframe.src = 'about:blank';
		_iframe.scrolling = 'no';
		_iframe.frameborder = '0';
		_iframe.id = id;
		_iframe.name = id;
		_iframe.style.position = 'absolute';
		if(el)
		{
			document.getElementById(el).appendChild(_iframe);
		}
		else
		{
			document.body.appendChild(_iframe);
		}
	}
	return document.getElementById(id);
}

/*Utils.addIframe = function(id, el)
{
	if(Utils.ge(id) == null)
	{
		var _iframe = Utils.createElement("iframe", {src: 'about:blank', scrolling: 'no', frameborder: '0', id: id, name: id});
		_iframe.style.position = 'absolute';
		_iframe.style.zIndex = '1';
		_iframe.style.border = '#fff 0px none';
		if(el)
		{
			Utils.appendChild(Utils.ge(el), _iframe);
		}
		else
		{
			Utils.appendChild(document.body, _iframe);
		}
	}
	return Utils.ge(id);
}*/

Utils.textWidth = function(text)
{
	var textElement = Utils.createElement("div", {id: 'textElement', innerHTML: text});
	textElement.style.position = 'absolute';
	textElement.style.top = '0';
	textElement.style.left = '0';
	Utils.appendChild(document.body, textElement);
	var w = Utils.ge('textElement').offsetWidth;
	Utils.removeElement('textElement');
	return w;
}

Utils.createElement = function(e, obj)
{
	var a = document.createElement(e);
	for(prop in obj)
	{
		a[prop] = obj[prop];
	}
	return a;
}

Utils.removeElement = function(id)
{
	if(Utils.ge(id).parentNode != null)
	{
		Utils.ge(id).parentNode.removeChild(Utils.ge(id));
	}
}

Utils.appendChild = function()
{
	if(this.appendChild.arguments.length > 1)
	{
		var a = this.appendChild.arguments[0];
		for(i=1; i<this.appendChild.arguments.length; i++)
		{
			if(arguments[i])
			{
				a.appendChild(this.appendChild.arguments[i]);
			}
		}
		return a;
	}
	else
	{
		return null;
	}
}

Utils.getXY = function(el)
{
	var x = el.offsetLeft;
	var y = el.offsetTop;
	if(el.offsetParent != null)
	{
		var pos = Utils.getXY(el.offsetParent);
		x += pos.x;
		y += pos.y;
	}
	return {x: x, y: y}
}

Utils.Tween = function(elementId, finalPosition, direction)
{
	var element = Utils.ge(elementId);
	if(direction == null)
	{
		if(parseInt(element.style.left) > finalPosition)
		{
			direction = 'left';
		}
		else
		{
			direction = 'right';
		}
	}
	
	// Animate both directions
	//printfire("element.style.left: "+parseInt(element.style.left));
	//printfire("finalPosition: "+finalPosition);
	//printfire("direction: "+direction);
	
	if(direction == 'left')
	{
		if(parseInt(element.style.left) > finalPosition)
		{
			element.style.left = parseInt(element.style.left) + (finalPosition/8) +'px';
			setTimeout("Utils.Tween('"+ elementId +"', '"+ finalPosition +"', '"+ direction +"')", 2);
		}
		else
		{
			element.style.left = finalPosition +'px';
		}
	}
	else if(direction == 'right')
	{
		if(parseInt(element.style.left) < finalPosition)
		{
			if(finalPosition == 0)
			{
				element.style.left = parseInt(element.style.left) - (-10) +'px';
			}
			else
			{
				element.style.left = parseInt(element.style.left) - (finalPosition/8) +'px';
			}
			setTimeout("Utils.Tween('"+ elementId +"', '"+ finalPosition +"', '"+ direction +"')", 2);
		}
		else
		{
			element.style.left = finalPosition +'px';
		}
	}
}

Utils.addListener = function(obj, eventName, listener)
{
	if (obj.attachEvent)
	{
		obj.attachEvent("on"+eventName, listener);
	}
	else if(obj.addEventListener)
	{
		obj.addEventListener(eventName, listener, false);
	}
	else
	{
		return false;
	}
	return true;
}


Utils.removeListener = function(obj, eventName, listener)
{
	if(obj.detachEvent)
	{
		obj.detachEvent("on"+eventName, listener);
	}
	else if(obj.removeEventListener)
	{
		obj.removeEventListener(eventName, listener, false);
	}
	else
	{
		return false;
	}
	
	return true;
}

Utils.fade = function(id, opacStart, opacEnd, millisec, callback)
{
	Utils.changeOpac(0, id);
    var speed = Math.round(millisec/100);
    var timer = 0;

    if(opacStart > opacEnd)
	{
        for(var i=opacStart; i>=opacEnd; i--)
		{
            setTimeout("Utils.changeOpac("+ i +", '"+ id +"', "+ opacEnd +", '"+ callback +"')", (timer*speed));
            timer++;
        }
    }
	else if(opacStart < opacEnd)
	{
        for(var i=opacStart; i<=opacEnd; i++)
        {
            setTimeout("Utils.changeOpac("+ i +", '"+ id +"', "+ opacEnd +", '"+ callback +"')", (timer*speed));
            timer++;
        }
    }
}

Utils.changeOpac = function(opacity, id, endPoint, callback)
{
	var _style = Utils.ge(id).style;
    _style.opacity = (opacity / 100);
    _style.MozOpacity = (opacity / 100);
    _style.KhtmlOpacity = (opacity / 100);
    _style.filter = "alpha(opacity=" + opacity + ")";
	
	if(opacity == endPoint && callback != null)
	{
		eval(callback);
	}
}

//end Utils.js
//start /utils/document.js

document.getElementsByClassName = function(oElm, strTagName, strClassName)
{
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++)
	{
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className))
		{
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements);
}

document.getQueryVariable = function(key)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for(var i=0; i<vars.length; i++)
	{
		var pair = vars[i].split("=");
		if(pair[0] == key)
		{
			return pair[1];
		}
	}
	return null;
}

document.onmousemove = function(evt)
{
	if(!evt) { var evt = window.event; }
	document.mouseX = (evt.screenX == null) ? evt.clientX : evt.screenX;
	document.mouseY = (evt.screenY == null) ? evt.clientY : evt.screenY;
}

//end document.js
// FormChek.js
//
// SUMMARY
//
// This is a set of JavaScript functions for validating input on
// an HTML form.  Functions are provided to validate:
//
//      - U.S. and international phone/fax numbers
//      - U.S. ZIP codes (5 or 9 digit postal codes)
//      - U.S. Postal Codes (2 letter abbreviations for names of states)
//      - U.S. Social Security Numbers (abbreviated as SSNs)
//      - email addresses
//  - dates (entry of year, month, and day and validity of combined date)
//  - credit card numbers
//
// Supporting utility functions validate that:
//
//      - characters are Letter, Digit, or LetterOrDigit
//      - strings are a Signed, Positive, Negative, Nonpositive, or
//        Nonnegative integer
//      - strings are a Float or a SignedFloat
//      - strings are Alphabetic, Alphanumeric, or Whitespace
//      - strings contain an integer within a specified range
//
// Functions are also provided to interactively check the
// above kinds of data and prompt the user if they have
// been entered incorrectly.
//
// Other utility functions are provided to:
//
//  - remove from a string characters which are/are not
//    in a "bag" of selected characters
//  - reformat a string, adding delimiter characters
//  - strip whitespace/leading whitespace from a string
//      - reformat U.S. phone numbers, ZIP codes, and Social
//        Security numbers
//
//
// Many of the below functions take an optional parameter eok (for "emptyOK")
// which determines whether the empty string will return true or false.
// Default behavior is controlled by global variable defaultEmptyOK.
//
// BASIC DATA VALIDATION FUNCTIONS:
//
// isWhitespace (s)                    Check whether string s is empty or whitespace.
// isLetter (c)                        Check whether character c is an English letter
// isDigit (c)                         Check whether character c is a digit
// isLetterOrDigit (c)                 Check whether character c is a letter or digit.
// isInteger (s [,eok])                True if all characters in string s are numbers.
// isSignedInteger (s [,eok])          True if all characters in string s are numbers; leading + or - allowed.
// isPositiveInteger (s [,eok])        True if string s is an integer > 0.
// isNonnegativeInteger (s [,eok])     True if string s is an integer >= 0.
// isNegativeInteger (s [,eok])        True if s is an integer < 0.
// isNonpositiveInteger (s [,eok])     True if s is an integer <= 0.
// isFloat (s [,eok])                  True if string s is an unsigned floating point (real) number. (Integers also OK.)
// isSignedFloat (s [,eok])            True if string s is a floating point number; leading + or - allowed. (Integers also OK.)
// isAlphabetic (s [,eok])             True if string s is English letters
// isAlphanumeric (s [,eok])           True if string s is English letters and numbers only.
//
// isSSN (s [,eok])                    True if string s is a valid U.S. Social Security Number.
// isUSPhoneNumber (s [,eok])          True if string s is a valid U.S. Phone Number.
// isInternationalPhoneNumber (s [,eok]) True if string s is a valid international phone number.
// isZIPCode (s [,eok])                True if string s is a valid U.S. ZIP code.
// isStateCode (s [,eok])              True if string s is a valid U.S. Postal Code
// isEmail (s [,eok])                  True if string s is a valid email address.
// isYear (s [,eok])                   True if string s is a valid Year number.
// isIntegerInRange (s, a, b [,eok])   True if string s is an integer between a and b, inclusive.
// isMonth (s [,eok])                  True if string s is a valid month between 1 and 12.
// isDay (s [,eok])                    True if string s is a valid day between 1 and 31.
// daysInFebruary (year)               Returns number of days in February of that year.
// isDate (year, month, day)           True if string arguments form a valid date.

// added by Robby Walker @ Go Daddy (RW@GD)
// isStrongPassword( s )               True if string s is a strong password containing 8 chars, at least 1 alpha, 1 number, and 1 special

// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
// stripCharsNotInBag (s, bag)         Removes all characters NOT in string bag from string s.
// stripWhitespace (s)                 Removes all whitespace characters from s.
// stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.
// reformat (TARGETSTRING, STRING,     Function for inserting formatting characters or
//   INTEGER, STRING, INTEGER ... )       delimiters into TARGETSTRING.
// reformatZIPCode (ZIPString)         If 9 digits, inserts separator hyphen.
// reformatSSN (SSN)                   Reformats as 123-45-6789.
// reformatUSPhone (USPhone)           Reformats as (123) 456-789.
// removeLeadingZeroes(val)					   Removes initial (leading) zeroes from val (so browser doesn't think it's an octal number).


// FUNCTIONS TO PROMPT USER:
//
// prompt (s)                          Display prompt string s in status bar.
// promptEntry (s)                     Display data entry prompt string s in status bar.
// warnEmpty (theField, s)             Notify user that required field theField is empty.
// warnInvalid (theField, s)           Notify user that contents of field theField are invalid.


// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok])    Check that theField.value is not empty or all whitespace.
// checkStateCode (theField)           Check that theField.value is a valid U.S. state code.
// checkZIPCode (theField [,eok])      Check that theField.value is a valid ZIP code.
// checkUSPhone (theField [,eok])      Check that theField.value is a valid US Phone.
// checkInternationalPhone (theField [,eok])  Check that theField.value is a valid International Phone.
// checkEmail (theField [,eok])        Check that theField.value is a valid Email.
// checkSSN (theField [,eok])          Check that theField.value is a valid SSN.
// checkYear (theField [,eok])         Check that theField.value is a valid Year.
// checkMonth (theField [,eok])        Check that theField.value is a valid Month.
// checkDay (theField [,eok])          Check that theField.value is a valid Day.
// checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
//                                     Check that field values form a valid date.
// getRadioButtonValue (radio)         Get checked value from radio button.
// checkCreditCard (radio, theField)   Validate credit card info.


// CREDIT CARD DATA VALIDATION FUNCTIONS
//
// isCreditCard (st)              True if credit card number passes the Luhn Mod-10 test.
// isVisa (cc)                    True if string cc is a valid VISA number.
// isMasterCard (cc)              True if string cc is a valid MasterCard number.
// isAmericanExpress (cc)         True if string cc is a valid American Express number.
// isDinersClub (cc)              True if string cc is a valid Diner's Club number.
// isCarteBlanche (cc)            True if string cc is a valid Carte Blanche number.
// isDiscover (cc)                True if string cc is a valid Discover card number.
// isEnRoute (cc)                 True if string cc is a valid enRoute card number.
// isJCB (cc)                     True if string cc is a valid JCB card number.
// isAnyCard (cc)                 True if string cc is a valid card number for any of the accepted types.
// isCardMatch (Type, Number)     True if Number is valid for credic card of type Type.
//
// Other stub functions are retained for backward compatibility with LivePayment code.
// See comments below for details.
//
// Performance hint: when you deploy this file on your website, strip out the
// comment lines from the source code as well as any of the functions which
// you don't need.  This will give you a smaller .js file and achieve faster
// downloads.
//
// 18 Feb 97 created Eric Krock
//
// (c) 1997 Netscape Communications Corporation



// VARIABLE DECLARATIONS

var digits = "0123456789";

var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"

var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

// RW@GD
var specialCharacters = '!@#$%^&*()[]{}<>?/\\~.,';

// whitespace characters
var whitespace = " \t\n\r";


// decimal point character differs by language and culture
var decimalPointDelimiter = "."


// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";


// characters which are allowed in US phone numbers
var validUSPhoneChars = digits + phoneNumberDelimiters;


// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";


// non-digit characters which are allowed in
// Social Security Numbers
var SSNDelimiters = "- ";



// characters which are allowed in Social Security Numbers
var validSSNChars = digits + SSNDelimiters;



// U.S. Social Security Numbers have 9 digits.
// They are formatted as 123-45-6789.
var digitsInSocialSecurityNumber = 9;



// U.S. phone numbers have 10 digits.
// They are formatted as 123 456 7890 or (123) 456-7890.
var digitsInUSPhoneNumber = 10;



// non-digit characters which are allowed in ZIP Codes
var ZIPCodeDelimiters = "-";



// our preferred delimiter for reformatting ZIP Codes
var ZIPCodeDelimeter = "-"


// characters which are allowed in Social Security Numbers
var validZIPCodeChars = digits + ZIPCodeDelimiters



// U.S. ZIP codes have 5 or 9 digits.
// They are formatted as 12345 or 12345-6789.
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 10


// non-digit characters which are allowed in credit card numbers
var creditCardDelimiters = " "


// CONSTANT STRING DECLARATIONS
// (grouped for ease of translation and localization)

// m is an abbreviation for "missing"

var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."

// s is an abbreviation for "string"

var sUSLastName = "Last Name"
var sUSFirstName = "First Name"
var sWorldLastName = "Family Name"
var sWorldFirstName = "Given Name"
var sTitle = "Title"
var sCompanyName = "Company Name"
var sUSAddress = "Street Address"
var sWorldAddress = "Address"
var sCity = "City"
var sStateCode = "State Code"
var sWorldState = "State, Province, or Prefecture"
var sCountry = "Country"
var sZIPCode = "ZIP Code"
var sWorldPostalCode = "Postal Code"
var sPhone = "Phone Number"
var sFax = "Fax Number"
var sDateOfBirth = "Date of Birth"
var sExpirationDate = "Expiration Date"
var sEmail = "Email"
var sSSN = "Social Security Number"
var sCreditCardNumber = "Credit Card Number"
var sOtherInfo = "Other Information"




// i is an abbreviation for "invalid"

var iStateCode = "This field must be a valid two character U.S. state abbreviation (like CA for California). Please reenter it now."
var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please reenter it now."
var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now."
var iWorldPhone = "This field must be a valid international phone number. Please reenter it now."
var iSSN = "This field must be a 9 digit U.S. social security number (like 123 45 6789). Please reenter it now."
var iEmail = "This field must be a valid email address (like foo@bar.com). Please reenter it now."
var iWebURL = "This field must be a valid web url (like www.yourdomain.com). Please reenter it now."
var iCreditCardPrefix = "This is not a valid "
var iCreditCardSuffix = " credit card number. (Click the link on this form to see a list of sample numbers.) Please reenter it now."
var iDay = "This field must be a day number between 1 and 31.  Please reenter it now."
var iMonth = "This field must be a month number between 1 and 12.  Please reenter it now."
var iYear = "This field must be a 2 or 4 digit year number.  Please reenter it now."
var iDatePrefix = "The Day, Month, and Year for "
var iDateSuffix = " do not form a valid date.  Please reenter them now."



// p is an abbreviation for "prompt"

var pEntryPrompt = "Please enter a "
var pStateCode = "2 character code (like CA)."
var pZIPCode = "5 or 9 digit U.S. ZIP Code (like 94043)."
var pUSPhone = "10 digit U.S. phone number (like 415 555 1212)."
var pWorldPhone = "international phone number."
var pSSN = "9 digit U.S. social security number (like 123 45 6789)."
var pEmail = "valid email address (like foo@bar.com)."
var pCreditCard = "valid credit card number."
var pDay = "day number between 1 and 31."
var pMonth = "month number between 1 and 12."
var pYear = "2 or 4 digit year number."


// Global variable defaultEmptyOK defines default return value
// for many functions when they are passed the empty string.
// By default, they will return defaultEmptyOK.
//
// defaultEmptyOK is false, which means that by default,
// these functions will do "strict" validation.  Function
// isInteger, for example, will only return true if it is
// passed a string containing an integer; if it is passed
// the empty string, it will return false.
//
// You can change this default behavior globally (for all
// functions which use defaultEmptyOK) by changing the value
// of defaultEmptyOK.
//
// Most of these functions have an optional argument emptyOK
// which allows you to override the default behavior for
// the duration of a function call.
//
// This functionality is useful because it is possible to
// say "if the user puts anything in this field, it must
// be an integer (or a phone number, or a string, etc.),
// but it's OK to leave the field empty too."
// This is the case for fields which are optional but which
// must have a certain kind of content if filled in.

var defaultEmptyOK = false




// Attempting to make this library run on Navigator 2.0,
// so I'm supplying this array creation routine as per
// JavaScript 1.0 documentation.  If you're using
// Navigator 3.0 or later, you don't need to do this;
// you can use the Array constructor instead.

function makeArray(n) {
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++) {
      this[i] = 0
   }
   return this
}



var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;




// Valid U.S. Postal Codes for states, territories, armed forces, etc.
// See http://www.usps.gov/ncsc/lookups/abbr_state.txt.

var USStateCodeDelimiter = "|";
var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP";




// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (stripWhitespace(s).length == 0))
}



// Returns true if string s is empty or
// whitespace characters only.

function isWhitespace (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}



// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}




// WORKAROUND FUNCTION FOR NAVIGATOR 2.0.2 COMPATIBILITY.
//
// The below function *should* be unnecessary.  In general,
// avoid using it.  Use the standard method indexOf instead.
//
// However, because of an apparent bug in indexOf on
// Navigator 2.0.2, the below loop does not work as the
// body of stripInitialWhitespace:
//
// while ((i < s.length) && (whitespace.indexOf(s.charAt(i)) != -1))
//   i++;
//
// ... so we provide this workaround function charInString
// instead.
//
// charInString (CHARACTER c, STRING s)
//
// Returns true if single character c (actually a string)
// is contained within string s.

function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}



// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;

    return s.substring (i, s.length);
}

// Removes initial (leading) zeroes from s.
// This prevents a problem where the js parseInt() function
// assumes that the numeric argument is octal if it begins
// with a zero.
function removeLeadingZeroes(val)
{
   while (val.charAt(0) == '0')
      val = val.substring(1, val.length);

   return val;
}




// Returns true if character c is an English letter
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}



// Returns true if character c is a digit
// (0 .. 9).

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}



// Returns true if character c is a letter or digit.

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}


// Returns true if character c is a special character (RW@GD)

function isSpecialCharacter (c)
{   return ( specialCharacters.indexOf (c) != -1 );
}



// isInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true),
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)

{   var i;

    if (isEmpty(s))
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}







// isSignedInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters are numbers;
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)

{   if (isEmpty(s))
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}




// isPositiveInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is an integer > 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a positive, not negative, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) );
}






// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}






// isNegativeInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is an integer < 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a negative, not positive, number

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) < 0) ) );
}






// isNonpositiveInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is an integer <= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonpositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonpositiveInteger.arguments.length > 1)
        secondArg = isNonpositiveInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number <= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) <= 0) ) );
}





// isFloat (STRING s [, BOOLEAN emptyOK])
//
// True if string s is an unsigned floating point (real) number.
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isInteger, then call isFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isFloat (s)

{   var i;
    var seenDecimalPoint = false;

    if (isEmpty(s))
    {
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);
    }

    if (s == decimalPointDelimiter) return false;

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}







// isSignedFloat (STRING s [, BOOLEAN emptyOK])
//
// True if string s is a signed or unsigned floating point
// (real) number. First character is allowed to be + or -.
//
// Also returns true for unsigned integers. If you wish
// to distinguish between integers and floating point numbers,
// first call isSignedInteger, then call isSignedFloat.
//
// Does not accept exponential notation.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isSignedFloat (s)

{   if (isEmpty(s))
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}


function isPositiveFloat(s)
{
  return isSignedFloat(s) && s.charAt(0) != "-";
}


// isAlphabetic (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is English letters
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphabetic (s)

{   var i;

    if (isEmpty(s))
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphabetic character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}




// isAlphanumeric (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is English letters
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphanumeric (s)

{   var i;

    if (isEmpty(s))
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-alphanumeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    // All characters are numbers or letters.
    return true;
}


// isStrongPassword ( STRING s )      RW@GD
//
// Returns true if string is 8 chars or more including
// at least 1 alpha, 1 num, and 1 special character

// Defect 25144: Updated to have a min of 7 and remove the special character requirement

function isStrongPassword (s) {
   if ( s.length < 7 ) return false;

   var i;

   var ac = 0;
   var nc = 0;

   for (i = 0; i < s.length; i++)
   {
      // Check that current character is number or letter.
      var c = s.charAt(i);

      if ( isLetter (c) ) ac++;
      else if ( isDigit (c) ) nc++;

   }

   if ( ( ac > 0 ) && ( nc > 0 )) return true;
   else return false;

}



// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123) 456-7890" make this function call:
//   reformat("1234567890", "(", 3, ") ", 3, "-", 4)
//
// * To reformat a 9-digit U.S. Social Security number from
//   "123456789" to "123-45-6789" make this function call:
//   reformat("123456789", "", 3, "-", 2, "-", 4)
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call function stripCharsNotInBag to remove the unwanted
// characters, THEN call function reformat to delimit as desired.
//
// EXAMPLE:
//
// reformat (stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}




// isSSN (STRING s [, BOOLEAN emptyOK])
//
// isSSN returns true if string s is a valid U.S. Social
// Security Number.  Must be 9 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isSSN (s)
{   if (isEmpty(s))
       if (isSSN.arguments.length == 1) return defaultEmptyOK;
       else return (isSSN.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInSocialSecurityNumber)
}




// isUSPhoneNumber (STRING s [, BOOLEAN emptyOK])
//
// isUSPhoneNumber returns true if string s is a valid U.S. Phone
// Number.  Must be 10 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isUSPhoneNumber (s)
{   if (isEmpty(s))
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}




// isInternationalPhoneNumber (STRING s [, BOOLEAN emptyOK])
//
// isInternationalPhoneNumber returns true if string s is a valid
// international phone number.  Must be digits only; any length OK.
// May be prefixed by + character.
//
// NOTE: A phone number of all zeros would not be accepted.
// I don't think that is a valid phone number anyway.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.  You may leave in
// leading + character if you wish.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isInternationalPhoneNumber (s)
{   if (isEmpty(s))
       if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isInternationalPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}




// isZIPCode (STRING s [, BOOLEAN emptyOK])
//
// isZIPCode returns true if string s is a valid
// U.S. ZIP code.  Must be 5 or 10 chars only.
//
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isZIPCode(zip)
{
	var zipRegExp = /^((?:\d{5}[\s]*)|(?:\d{5}((?:-\d{4}[\s]*)?)$)|(?:[A-Z]\d[A-Z][\s]*\d[A-Z]\d[\s]*)$)/;
	return zipRegExp.test(zip);
}


// isStateCode (STRING s [, BOOLEAN emptyOK])
//
// Return true if s is a valid U.S. Postal Code
// (abbreviation for state).
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isStateCode(s)
{
	if (isEmpty(s))
	{
       	if (isStateCode.arguments.length == 1)
		{
       		return defaultEmptyOK;
		}
       	else
		{
       		return (isStateCode.arguments[1] == true);
       	}
    }
	var regionCodeRegEx = /^([aA][abelkprszABELKPRSZ]|[bB][cC]|[cC][aotAOT]|[dD][ecEC]|[fF][lmLM]|[gG][auAU]|[hH][iI]|[iI][adlnADLN]|[kK][sySY]|[lL][aA]|[mM][abdehinopstABDEHINOPST]|[nN][bcdehjlmstuvyBCDEHJLMSTUVY]|[oO][hknrHKNR]|[pP][aerwAERW]|[qQ][cC]|[rR][iI]|[sS][cdkCDK]|[tT][nxNX]|[uU][tT]|[vV][aitAIT]|[wW][aivyAIVY]|[yY][tT])$/;
    return regionCodeRegEx.test(s);
}




// isEmail (STRING s [, BOOLEAN emptyOK])
//
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{
    // The following regexp is taken from the webmail team
    var emailRE=/^[-\+\*&a-zA-Z0-9\.!#\$%\'\=\?\^_`\{\}\|~\/]+\@[-_a-zA-Z0-9]+(\.[-_a-zA-Z0-9]+)+$/;
	  return emailRE.test(s);
}





// isYear (STRING s [, BOOLEAN emptyOK])
//
// isYear returns true if string s is a valid
// Year number.  Must be 2 or 4 digits only.
//
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   if (isEmpty(s))
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
//
// isIntegerInRange returns true if string s is an integer
// within the range of integer arguments a and b, inclusive.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s))
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    //remove any leading zeros to fix bug were 01 - 07 are valid but 08 and 09 are not.
    var trimmedS = s;
    while(trimmedS.indexOf("0") == 0 && trimmedS.length > 1)
    {
      trimmedS = trimmedS.substring(1,trimmedS.length)
    }

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (trimmedS);
    return ((num >= a) && (num <= b));
}



// isMonth (STRING s [, BOOLEAN emptyOK])
//
// isMonth returns true if string s is a valid
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMonth (s)
{   if (isEmpty(s))
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}



// isDay (STRING s [, BOOLEAN emptyOK])
//
// isDay returns true if string s is a valid
// day number between 1 and 31.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isDay (s)
{   if (isEmpty(s))
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);
    return isIntegerInRange (s, 1, 31);
}



// daysInFebruary (INTEGER year)
//
// Given integer argument year,
// returns number of days in February of that year.

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}



// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day
// form a valid date.
//

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false;

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}




/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */


// Display prompt string s in status bar.

function prompt (s)
{   window.status = s
}



// Display data entry prompt string s in status bar.

function promptEntry (s)
{   window.status = pEntryPrompt + s
}




// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, s)
{   theField.focus();
    alert(s);
    return false;
}



// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid (theField, s)
{   theField.focus();
    if (theField.type != 'select-one' && theField.type != 'select-multiple')
    {
		theField.select();
	}
    alert(s);
    return false;
}




/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

// checkString (TEXTFIELD theField, STRING s, [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is not all whitespace.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkString (theField, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value))
       return false;
    else return true;
}



// checkStateCode (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid U.S. state code.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkStateCode (theField, emptyOK)
{   if (checkStateCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  theField.value = theField.value.toUpperCase();
       if (!isStateCode(theField.value, false))
          return warnInvalid (theField, iStateCode);
       else return true;
    }
}



// takes ZIPString, a string of 5 or 9 digits;
// if 9 digits, inserts separator hyphen

function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}




// checkZIPCode (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid ZIP code.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkZIPCode (theField, emptyOK)
{   if (checkZIPCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    { var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
      if (!isZIPCode(normalizedZIP, false))
         return warnInvalid (theField, iZIPCode);
      else
      {  // if you don't want to insert a hyphen, comment next line out
         theField.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    }
}



// takes USPhone, a string of 10 digits
// and reformats as (123) 456-789

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}



// checkUSPhone (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid US Phone.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkUSPhone (theField, emptyOK)
{   if (checkUSPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false))
          return warnInvalid (theField, iUSPhone);
       else
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          return true;
       }
    }
}



// checkInternationalPhone (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid International Phone.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkInternationalPhone (theField, emptyOK)
{   if (checkInternationalPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  if (!isInternationalPhoneNumber(theField.value, false))
          return warnInvalid (theField, iWorldPhone);
       else return true;
    }
}



// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false))
       return warnInvalid (theField, iEmail);
    else return true;
}


// checkWebURL (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Web URLl.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkWebURL (theField, emptyOK)
{   if (checkWebURL.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isWebURL(theField.value))
       return warnInvalid (theField, iWebURL);
    else return true;
}


function isWebURL (strng) {
  if (strng == "") {
    return false;
  }

  var webURLFilter1=/^.+\.[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4}$/;
  var webURLFilter2=/^.+\.[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4}\.[a-zA-Z]{2,3}$/;

  if (strng.match(webURLFilter1) || strng.match(webURLFilter2))
  {
//    alert('webURLFilter1 or webURLFilter2 is matched!');

    //test url for illegal characters
    var illegalChars= /[\(\)\<\>\,\;\:\"\[\]]/
    if (!strng.match(illegalChars)) {

//      alert('Not contain illegal characters');

      return true;
    }
//    else
//    {
//      alert('Contain illegal characters');
//    }
  }
//  else
//  {
//    alert('webURLFilter1 or webURLFilter2 is not matched!');
//  }

  return false;
}


// takes SSN, a string of 9 digits
// and reformats as 123-45-6789

function reformatSSN (SSN)
{   return (reformat (SSN, "", 3, "-", 2, "-", 4))
}


// Check that string theField.value is a valid SSN.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkSSN (theField, emptyOK)
{   if (checkSSN.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedSSN = stripCharsInBag(theField.value, SSNDelimiters)
       if (!isSSN(normalizedSSN, false))
          return warnInvalid (theField, iSSN);
       else
       {  // if you don't want to reformats as 123-456-7890, comment next line out
          theField.value = reformatSSN(normalizedSSN)
          return true;
       }
    }
}




// Check that string theField.value is a valid Year.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkYear (theField, emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false))
       return warnInvalid (theField, iYear);
    else return true;
}


// Check that string theField.value is a valid Month.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false))
       return warnInvalid (theField, iMonth);
    else return true;
}


// Check that string theField.value is a valid Day.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkDay (theField, emptyOK)
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false))
       return warnInvalid (theField, iDay);
    else return true;
}



// checkDate (yearField, monthField, dayField, STRING labelString [, OKtoOmitDay==false])
//
// Check that yearField.value, monthField.value, and dayField.value
// form a valid date.
//
// If they don't, labelString (the name of the date, like "Birth Date")
// is displayed to tell the user which date field is invalid.
//
// If it is OK for the day field to be empty, set optional argument
// OKtoOmitDay to true.  It defaults to false.

function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value))
       return warnInvalid (dayField, iDay);
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}



// Get checked value from radio button.

function getRadioButtonValue (radio)
{
    var radioValue = null;
    for (var i = 0; i < radio.length; i++)
    {
      if (radio[i].checked) { radioValue = radio[i].value}
    }
    return radioValue;
}




// Validate credit card info.

function checkCreditCard (radio, theField)
{   var cardType = getRadioButtonValue (radio)
    var normalizedCCN = stripCharsInBag(theField.value, creditCardDelimiters)
    if (!isCardMatch(cardType, normalizedCCN))
       return warnInvalid (theField, iCreditCardPrefix + cardType + iCreditCardSuffix);
    else
    {  theField.value = normalizedCCN
       return true
    }
}



/*  ================================================================
    Credit card verification functions
    Originally included as Starter Application 1.0.0 in LivePayment.
    20 Feb 1997 modified by egk:
           changed naming convention to initial lowercase
                  (isMasterCard instead of IsMasterCard, etc.)
           changed isCC to isCreditCard
           retained functions named with older conventions from
                  LivePayment as stub functions for backward
                  compatibility only
           added "AMERICANEXPRESS" as equivalent of "AMEX"
                  for naming consistency
    ================================================================ */


/*  ================================================================
    FUNCTION:  isCreditCard(st)

    INPUT:     st - a string representing a credit card number

    RETURNS:  true, if the credit card number passes the Luhn Mod-10
        test.
        false, otherwise
    ================================================================ */

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()



/*  ================================================================
    FUNCTION:  isVisa()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid VISA number.

        false, otherwise

    Sample number: 4111 1111 1111 1111 (16 digits)
    ================================================================ */

function isVisa(cc)
{
  if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0,1) == 4))
    return isCreditCard(cc);
  return false;
}  // END FUNCTION isVisa()




/*  ================================================================
    FUNCTION:  isMasterCard()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid MasterCard
        number.

        false, otherwise

    Sample number: 5500 0000 0000 0004 (16 digits)
    ================================================================ */

function isMasterCard(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isMasterCard()





/*  ================================================================
    FUNCTION:  isAmericanExpress()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid American
        Express number.

        false, otherwise

    Sample number: 340000000000009 (15 digits)
    ================================================================ */

function isAmericanExpress(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isAmericanExpress()




/*  ================================================================
    FUNCTION:  isDinersClub()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Diner's
        Club number.

        false, otherwise

    Sample number: 30000000000004 (14 digits)
    ================================================================ */

function isDinersClub(cc)
{
  firstdig = cc.substring(0,1);
  seconddig = cc.substring(1,2);
  if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
    return isCreditCard(cc);
  return false;
}



/*  ================================================================
    FUNCTION:  isCarteBlanche()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Carte
        Blanche number.

        false, otherwise
    ================================================================ */

function isCarteBlanche(cc)
{
  return isDinersClub(cc);
}




/*  ================================================================
    FUNCTION:  isDiscover()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid Discover
        card number.

        false, otherwise

    Sample number: 6011000000000004 (16 digits)
    ================================================================ */

function isDiscover(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) && (first4digs == "6011"))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isDiscover()





/*  ================================================================
    FUNCTION:  isEnRoute()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid enRoute
        card number.

        false, otherwise

    Sample number: 201400000000009 (15 digits)
    ================================================================ */

function isEnRoute(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 15) &&
      ((first4digs == "2014") ||
       (first4digs == "2149")))
    return isCreditCard(cc);
  return false;
}



/*  ================================================================
    FUNCTION:  isJCB()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is a valid JCB
        card number.

        false, otherwise
    ================================================================ */

function isJCB(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) &&
      ((first4digs == "3088") ||
       (first4digs == "3096") ||
       (first4digs == "3112") ||
       (first4digs == "3158") ||
       (first4digs == "3337") ||
       (first4digs == "3528")))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isJCB()



/*  ================================================================
    FUNCTION:  isAnyCard()

    INPUT:     cc - a string representing a credit card number

    RETURNS:  true, if the credit card number is any valid credit
        card number for any of the accepted card types.

        false, otherwise
    ================================================================ */

function isAnyCard(cc)
{
  if (!isCreditCard(cc))
    return false;
  if (!isMasterCard(cc) && !isVisa(cc) && !isAmericanExpress(cc) && !isDinersClub(cc) &&
      !isDiscover(cc) && !isEnRoute(cc) && !isJCB(cc)) {
    return false;
  }
  return true;

} // END FUNCTION isAnyCard()



/*  ================================================================
    FUNCTION:  isCardMatch()

    INPUT:    cardType - a string representing the credit card type
        cardNumber - a string representing a credit card number

    RETURNS:  true, if the credit card number is valid for the particular
        credit card type given in "cardType".

        false, otherwise
    ================================================================ */

function isCardMatch (cardType, cardNumber)
{

  cardType = cardType.toUpperCase();
  var doesMatch = true;

  if ((cardType == "VISA") && (!isVisa(cardNumber)))
    doesMatch = false;
  if ((cardType == "MASTERCARD") && (!isMasterCard(cardNumber)))
    doesMatch = false;
  if ( ( (cardType == "AMERICANEXPRESS") || (cardType == "AMEX") )
                && (!isAmericanExpress(cardNumber))) doesMatch = false;
  if ((cardType == "DISCOVER") && (!isDiscover(cardNumber)))
    doesMatch = false;
  if ((cardType == "JCB") && (!isJCB(cardNumber)))
    doesMatch = false;
  if ((cardType == "DINERS" || cardType == "DINERCLUB") && (!isDinersClub(cardNumber)))
    doesMatch = false;
  if ((cardType == "CARTEBLANCHE") && (!isCarteBlanche(cardNumber)))
    doesMatch = false;
  if ((cardType == "ENROUTE") && (!isEnRoute(cardNumber)))
    doesMatch = false;
  return doesMatch;

}  // END FUNCTION CardMatch()




/*  ================================================================
    The below stub functions are retained for backward compatibility
    with the original LivePayment code so that it should be possible
    in principle to swap in this new module as a replacement for the
    older module without breaking existing code.  (There are no
    guarantees, of course, but it should work.)

    When writing new code, do not use these stub functions; use the
    functions defined above.
    ================================================================ */

function IsCC (st) {
    return isCreditCard(st);
}

function IsVisa (cc)  {
  return isVisa(cc);
}

function IsVISA (cc)  {
  return isVisa(cc);
}

function IsMasterCard (cc)  {
  return isMasterCard(cc);
}

function IsMastercard (cc)  {
  return isMasterCard(cc);
}

function IsMC (cc)  {
  return isMasterCard(cc);
}

function IsAmericanExpress (cc)  {
  return isAmericanExpress(cc);
}

function IsAmEx (cc)  {
  return isAmericanExpress(cc);
}

function IsDinersClub (cc)  {
  return isDinersClub(cc);
}

function IsDC (cc)  {
  return isDinersClub(cc);
}

function IsDiners (cc)  {
  return isDinersClub(cc);
}

function IsCarteBlanche (cc)  {
  return isCarteBlanche(cc);
}

function IsCB (cc)  {
  return isCarteBlanche(cc);
}

function IsDiscover (cc)  {
  return isDiscover(cc);
}

function IsEnRoute (cc)  {
  return isEnRoute(cc);
}

function IsenRoute (cc)  {
  return isEnRoute(cc);
}

function IsJCB (cc)  {
  return isJCB(cc);
}

function IsAnyCard(cc)  {
  return isAnyCard(cc);
}

function IsCardMatch (cardType, cardNumber)  {
  return isCardMatch (cardType, cardNumber);
}

function validatePrice(price)
{
  var numericPrice = "";
  var foundDecimal = false;
  var numFractionalDigits = 0;
  var digit = false;

  if(price != null)
  {
    for(var i = 0; i < price.length; i++)
    {
      if(price.charAt(i) == '.' && !foundDecimal)
      {
          numericPrice += price.charAt(i);
          foundDecimal = true;
      }
      digit = isDigit(price.charAt(i));
      if (foundDecimal && digit) {
      	numFractionalDigits++;
      }

      if(digit && (numFractionalDigits < 3))
      {
        numericPrice += price.charAt(i);
      }
    }
  }
  return numericPrice;
}

function validateDate(dateString)
{
	var date = new Date(dateString);
	var dateRegExp = new RegExp("^(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/\\d\\d\\d\\d$");
	if (isNaN(date) || !dateRegExp.test(dateString))
	{
	  return false;
	}

	// Check to see if the date is validate such as check leap year
  var num = dateString.split("/");
  return isDateOK(new Number(num[2]), new Number(num[0]), new Number(num[1]));

	return true;
}

// Validate the date
// This method is copied from http://www.merlyn.demon.co.uk/js-date4.htm#DVal
var MonthDate = [, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isDateOK(Y, M, D) {
    var L = MonthDate[M];
    return D > 0 &&
           !!L &&
           (D <= L || D == 29 && Y % 4 == 0 && (Y % 100 != 0 || Y % 400 == 0));
}

// elemenetId: Element that contains HTML text
// name: (Optional)The name that will be used to display in the error message. 
function validateHtmlCode(elementId, name)
{
  var data = '';
  var errorDiv = 'validateHtmlResult';
  if (validateHtmlCode.arguments.length == 2)
  {
   	if (name.label)
	  	data = 'name=' + encodeURIComponent(name.label) + '&';	  	
	if (name.errorDiv)
		errorDiv = name.errorDiv;
  }

  var htmlCode = document.getElementById(elementId).value;
  xmlLoaderPost("validateHtml.hg", data + 'htmlCode=' + encodeURIComponent(htmlCode), validateHtmlCodeHandler, errorDiv);
}

function validateHtmlCodeHandler(xmlHttp, errorDiv)
{
  var xmlDoc =  XmlDocument.create();
  xmlDoc.loadXML(xmlHttp.responseText);

  var error = xmlDoc.getElementsByTagName("isError")[0].firstChild.data;
  var message = xmlDoc.getElementsByTagName("message");
  var errorSection = document.getElementById(errorDiv);
  document.getElementById('errors').innerHTML = "";

  if (error == 'true')
  {	
	// there is an error, display the error message
	errorSection.style.lineHeight = "normal";
	errorSection.style.paddingBottom = "10px";
	errorSection.innerHTML = xmlElementToString(message[0].firstChild);
  }
  else
  {
	errorSection.innerHTML = "";
    errorSection.style.lineHeight = "0px";
	alert(message[0].firstChild.data);
  }
}

function verifyMerchantEmail(emailType, address, label, multiple)
{
	var addr = document.getElementById(address).value;
	var a = addr.split(',');
	if (!multiple && a.length > 1)
	{
		alert("'" + label + "' does not allow multiple email addresses.\nPlease enter a valid e-mail address.");	
		return false;
	}

  for(var i = 0; i < a.length; i++)
  {
		if (!isEmail(a[i]))
		{
//			alert("'" + a[i] + "' is an invalid email address. Please enter a valid e-mail address.");			
			alert("'" + label + "' contains an invalid email address.");
			return false;
		}
  }

	var date = new Date();	
	var uri = "merchantEmail.hg?verifyEmail=true&emailToVerify=" + emailType + "&verifyAddress=" + addr + "&nocache=" + date.getHours() + date.getMinutes() + date.getSeconds();
  	var xmlHttp = XmlHttp.create();
  	xmlHttp.open("GET", uri, false);
  	xmlHttp.send(null);
  	alert("A sample message has been sent to " + addr); 
}
// start Dialog.js

Dialog = {};

Dialog.initialize = function()
{
	Dialog.currentErrors = new Array();
	Dialog.currentWarnings = new Array();
	Dialog.currentErrorFields = new Array();
	Dialog.currentWarningFields = new Array();
}
Dialog.initialize();


/********************************************************
 * Error Dialog
 ********************************************************/
 
/**
* @param	issue		the error string that should display in the dialog
* @param	action		either a js function as a string
* @param	actionLabel	label to use as hyperlink to fix the issue
* @param	field		form field to focus
*/
Dialog.openError = function(issue, action, actionLabel, field)
{
	Dialog.isOpen = true;
	if(!Dialog.currentErrors.contains(issue))
	{
		Dialog.currentErrors.push(issue);
		Utils.ge('errorDialog').style.display = '';
		Utils.fade('errorDialog', 0, 100, 500, 'Dialog.onFadeInError()');
		
		var errorIndex = (Dialog.currentErrors.length-1);
		var errorId = 'error_'+ errorIndex;
		if(action != undefined)
		{
			if(!actionLabel) actionLabel = 'Edit';
			if(field)
			{
				Dialog.currentErrorFields.push(field);
				field.onblur = function(evt) { Dialog.removeError(evt, errorId); };
				field.style.borderColor = '#c90707';
			}
			
			Utils.ge('errorDialogMessage').innerHTML += '<div id="'+ errorId +'" class="error">'+ issue +'&#160;&#160;<a href="javascript:'+ action +'Dialog.focusErrorFields('+errorIndex+');">'+ actionLabel +'</a></div>';
		}
		else
		{
			Utils.ge('errorDialogMessage').innerHTML += '<div id="'+ errorId +'">'+ issue +'</div>';
		}
		
		Page.forceCloseDropIn();
		Utils.ge('content').scrollTop = 0;
	}
}

Dialog.focusErrorFields = function(index)
{
	Dialog.currentErrorFields[index].focus();
	Dialog.currentErrorFields[index].select();
}

Dialog.removeError = function(evt, errorId)
{
	if(Dialog.isOpen)
	{
		var evt = Dialog.getEvent(evt);
		var t = Dialog.getTarget(evt);
		
		if(Utils.ge(t.id).value != '')
		{
			Utils.ge(errorId).style.display = 'none';
			Utils.ge(t.id).style.borderColor = '';
			//Utils.ge(t.id).onblur = null;
		}
		else
		{
			Utils.ge(errorId).style.display = '';
			Utils.ge(t.id).style.borderColor = '#c90707';
		}
		
		var isError = false;
		for(var i=0; i<Dialog.currentErrorFields.length; i++)
		{
			if(Dialog.currentErrorFields[i].value == '')
			{
				isError = true;
				break;
			}
		}
		if(!isError)
		{
			Dialog.closeError();
			// if warnings, show warnings
		}
	}
}

Dialog.getEvent = function(evt)
{
	if(!evt)
	{
		var evt = window.event;
	}
	return evt;
}

Dialog.getTarget = function(evt)
{
	return t = (evt.target) ? evt.target : evt.srcElement;
}

Dialog.closeError = function()
{
	Dialog.onFadeOutError();
	Dialog.currentErrors.clear();
	Dialog.currentErrorFields.clear();
	Dialog.isOpen = false;
	//Utils.fade('dialog', 100, 0, 500, 'Dialog.onFadeOutError()');
}

Dialog.onFadeInError = function()
{
	//Utils.ge('dialog').style.display = '';
}

Dialog.onFadeOutError = function()
{
	Utils.ge('errorDialog').style.display = 'none';
	Utils.ge('errorDialogMessage').innerHTML = '';
}





/********************************************************
 * Warning Dialog
 ********************************************************/
 
/**
* @param	issue		the error string that should display in the dialog
* @param	action		either a js function as a string
* @param	actionLabel	label to use as hyperlink to fix the issue
* @param	field		form field to focus
*/
Dialog.openWarning = function(issue, action, actionLabel, field)
{
	Dialog.isOpen = true;
	if(!Dialog.currentWarnings.contains(issue))
	{
		Dialog.currentWarnings.push(issue);
		Utils.ge('warningDialog').style.display = '';
		Utils.fade('warningDialog', 0, 100, 500, 'Dialog.onFadeInWarning()');
		
		var warningIndex = (Dialog.currentWarnings.length-1);
		var warningId = 'warning_'+ warningIndex;
		if(action != undefined)
		{
			if(!actionLabel) actionLabel = 'Edit';
			if(field)
			{
				Dialog.currentWarningFields.push(field);
				field.onblur = function(evt) { Dialog.removeWarning(evt, warningId); };
				field.style.borderColor = '#ffbf00';
			}
			
			Utils.ge('warningDialogMessage').innerHTML += '<div id="'+ warningId +'">'+ issue +'&#160;&#160;<a href="javascript:'+ action +'Dialog.focusWarningFields('+warningIndex+');">'+ actionLabel +'</a></div>';
		}
		else
		{
			Utils.ge('warningDialogMessage').innerHTML += '<div id="'+ warningId +'">'+ issue +'</div>';
		}
		
		// The Page object does not have this method in this version of the skin
		//Page.forceCloseDropIn();
		// The content div does not exist in this version of the skin
		//Utils.ge('content').scrollTop = 0;
	}
}

Dialog.focusWarningFields = function(index)
{
	Dialog.currentWarningFields[index].focus();
	Dialog.currentWarningFields[index].select();
}

Dialog.removeWarning = function(evt, warningId)
{
	if(Dialog.isOpen)
	{
		var evt = Dialog.getEvent(evt);
		var t = Dialog.getTarget(evt);
		
		if(Utils.ge(t.id).value != '')
		{
			Utils.ge(warningId).style.display = 'none';
			Utils.ge(t.id).style.borderColor = '';
			//Utils.ge(t.id).onblur = null;
		}
		else
		{
			Utils.ge(warningId).style.display = '';
			Utils.ge(t.id).style.borderColor = '#ffbf00';
		}
		
		var isWarning = false;
		for(var i=0; i<Dialog.currentWarningFields.length; i++)
		{
			if(Dialog.currentWarningFields[i].value == '')
			{
				isWarning = true;
				break;
			}
		}
		if(!isWarning)
		{
			Dialog.closeWarning();
		}
	}
}

Dialog.closeWarning = function()
{
	Dialog.onFadeOutWarning();
	Dialog.currentWarnings.clear();
	Dialog.isOpen = false;
	Dialog.currentWarningFields.clear();
	//Utils.fade('warningDialog', 100, 0, 500, 'Dialog.onFadeOutWarning()');
}

Dialog.onFadeInWarning = function()
{
	//Utils.ge('dialog').style.display = '';
	//Dialog.writeCurrentIssuesToDialog();
}

Dialog.onFadeOutWarning = function()
{
	Utils.ge('warningDialog').style.display = 'none';
	Utils.ge('warningDialogMessage').innerHTML = '';
}

//end Dialog.js
// start /view/Form.js

function Form()
{
	this.fields = arguments;
	for(var i=0; i<this.fields.length; i++)
	{
		alert("arguments: "+this.fields[i]);
	}
}

Form.prototype.validate = function()
{
	alert(this.fields);
}

// end Form.js

// start /view/Page.js

Page = {};

Page.resize = function()
{
    // WINDOW dimensions as baseline
    var windowHeight = (isIE()) ? document.body.offsetHeight-2 : window.innerHeight;
    
    if(windowHeight >= 600)
    {
      windowHeight -= 20;
    }
    else
    {
      windowHeight -= 30;
    }
    var windowWidth = (isIE()) ? document.body.offsetWidth - 8 : window.innerWidth - 5;
    var MIN_WIDTH=984;

    var TARGET_WIDTH = windowWidth>MIN_WIDTH?windowWidth:MIN_WIDTH;
    
    // ---------------------------------
    // SETUP some things that need sized
    var page = Utils.ge('page');
    var titleContainer = Utils.ge("title-container");
    var contentContainer = Utils.ge('contentContainer');
    var contentDiv = Utils.ge('contentDiv');
    var contentDiv_jsp = Utils.ge('contentDiv_jsp');
    var navLeft = Utils.ge('navLeft');
    
    // ---------------------------------
    // PAGE outline sizing
    // window height and width, or MIN_WIDTH
    if (page != null) {
        page.style.height = (windowHeight) + "px"; // subtract 2px b/c we add borders on #page
        page.style.width = TARGET_WIDTH + "px";
    }
    
    // ---------------------------------
    // HEADER sizing
    if (Utils.ge('header') != null) {
        Utils.ge('header').style.width = page.style.width;
    }
    
    // ---------------------------------
    // CONTENT height
    // first, account for the title area
    var contentHeight = page.offsetHeight-2; // offsetHeight is an int, but includes the border
    
    // then, account for header
    if (Utils.ge('header') != null)
        contentHeight = ((contentHeight - Utils.ge('header').offsetHeight)>0 
        ? contentHeight - Utils.ge('header').offsetHeight 
        : contentHeight);
    
    // ---------------------------------
    // CONTENT CONTAINER sizing
    if (contentContainer != null) {
        contentContainer.style.height = contentHeight + "px";
        contentContainer.style.width = (page.offsetWidth-2) + "px"; // offsetHeight is an int, but includes the border
    }
    
    // ---------------------------------
    // CONTENT DIV sizing
    var innerContentHeight = (contentHeight - titleContainer.offsetHeight);
    if (contentDiv != null) {
        contentDiv.style.height = innerContentHeight + "px";
        contentDiv.style.width = navLeft ? (contentContainer.offsetWidth - 216) +"px" : "100%";
    }
        
    if (navLeft!=null)
        navLeft.style.height = innerContentHeight + "px";
    
    if (contentDiv_jsp!=null) 
    {
		contentDiv_jsp.style.height = innerContentHeight + "px";
      if (navLeft != null)
        contentDiv_jsp.style.width = navLeft ? (contentContainer.offsetWidth - 216) +"px" : "100%";
      else
        contentDiv_jsp.style.width = TARGET_WIDTH + "px"
    }
    
    if (Utils.ge('navContainer') != null)
        Utils.ge('navContainer').style.width = (TARGET_WIDTH - 216) +"px";
}

var currHeight;
var currWidth;
Page.resizeHandler = function()
{
    if(currHeight != document.documentElement.clientHeight ||
       currWidth != document.documentElement.clientWidth)
    {
        Page.resize();
    }
    currHeight = document.documentElement.clientHeight;
    currWidth = document.documentElement.clientWidth;
}

//end Page.js
/**
 * Helper function to get the active X xml parser to use
 * for the xml http object.
 * @return the prefix for the XmlHttp active x object to use.
 */
function getXmlHttpPrefix()
{
  if (getXmlHttpPrefix.prefix)
  {
    return getXmlHttpPrefix.prefix;
  }

  var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
  var activeXObj;
  for (var i = 0; i < prefixes.length; i++)
  {
    try
    {
      // try to create the objects
      activeXObj = new ActiveXObject(prefixes[i] + ".XmlHttp");
      return getXmlHttpPrefix.prefix = prefixes[i];
    }
    catch (ex)
    {
    }
  }

  throw new Error("Could not find an installed XML parser");
}

/**
 * The XML Http helper object.
 * This xml object allows you to post an xml data
 * to a server without leaving the current page.
 */
function XmlHttp()
{
}


/**
 * A create function for the XMLHttp object.
 */
XmlHttp.create = function ()
  {
    try
    {
      if (window.XMLHttpRequest)
      {
        var req = new XMLHttpRequest();

        // some versions of Moz do not support the readyState property
        // and the onreadystate event so we patch it!
        if (req.readyState == null)
        {
          req.readyState = 1;
          req.addEventListener("load", function ()
            {
              req.readyState = 4;
              if (typeof req.onreadystatechange == "function")
              {
                req.onreadystatechange();
              }
            },
            false);
        }

        return req;
      }
      if (window.ActiveXObject)
      {
        return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
      }
    }
    catch (ex)
    {
    }
    // fell through
    throw new Error("Your browser does not support XmlHttp objects");
  }

function getDomDocumentPrefix() 
{
  if (getDomDocumentPrefix.prefix)
  {
    return getDomDocumentPrefix.prefix;
  }
  
  var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
  var activeXObj;
  for (var i = 0; i < prefixes.length; i++) 
  {
    try 
    {
      // try to create the objects
      activeXObj = new ActiveXObject(prefixes[i] + ".DomDocument");
      return getDomDocumentPrefix.prefix = prefixes[i];
    }
    catch (ex) 
    {
    };
  }
  
  throw new Error("Could not find an installed XML parser");
}

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () {
  try {
    // DOM2
    if (document.implementation && document.implementation.createDocument) {
      var doc = document.implementation.createDocument("", "", null);
      
      // some versions of Moz do not support the readyState property
      // and the onreadystate event so we patch it!
      if (doc.readyState == null) 
      {
        doc.readyState = 1;
        doc.addEventListener("load", function () 
        {
          doc.readyState = 4;
          if (typeof doc.onreadystatechange == "function")
            doc.onreadystatechange();
        }, false);
      }
      
      return doc;
    }
    if (window.ActiveXObject)
      return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
  }
  catch (ex) 
  {
  }
  throw new Error("Your browser does not support XmlDocument objects");
};



// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser && window.XMLSerializer &&
  window.Node && Node.prototype && Node.prototype.__defineGetter__)
{

  // XMLDocument did not extend the Document interface in some versions
  // of Mozilla. Extend both!
  //XMLDocument.prototype.loadXML =
  Document.prototype.loadXML = function (s)
    {

      // parse the string to a new doc
      var doc2 = (new DOMParser()).parseFromString(s, "text/xml");

      // remove all initial children
      while (this.hasChildNodes())
      {
        this.removeChild(this.lastChild);
      }
      // insert and import nodes
      for (var i = 0; i < doc2.childNodes.length; i++)
      {
        this.appendChild(this.importNode(doc2.childNodes[i], true));
      }
    }


  /**
   * xml getter
   *
   * This serializes the DOM tree to an XML String
   *
   * Usage: var sXml = oNode.xml
   *
   */
  Document.prototype.__defineGetter__("xml", function ()
  {
    return (new XMLSerializer()).serializeToString(this);
  });
}

/**
 * This function loads the XML document from the specified URL and, when
 * it is fully loaded, passes that document and the URL to the specified
 * handler function. This function works with any XML document.
 */
function xmlLoader(uri, handler) 
{
  var contentElementId = arguments[2];
  var contentElement = document.getElementById(contentElementId);

  var progressText = "Loading...";
  var xmlHttp = XmlHttp.create();

  // The following two lines are to force the browse not to return
  // a cached copy of the requested xml
  var timestamp = new Date();
  var uniqueURI = uri+(uri.indexOf("?") > 0 ? "&" : "?")+"timestamp="+timestamp.getTime();

  xmlHttp.open("GET", uniqueURI, true);
  {
    xmlHttp.onreadystatechange = function () 
    {
      if (xmlHttp.readyState == 4)
      {
        if ( contentElement )
          handler(xmlHttp, contentElementId);
        else
          handler(xmlHttp);
      }
    }
    
    if (contentElement)
      contentElement.innerHTML = progressText;
  }
  xmlHttp.send(null);
}

function xmlLoaderPost(url, data, handler, extraData)
{
  var hed = (xmlLoaderPost.arguments.length == 4)? true: false;
  var xmlHttp = XmlHttp.create();

  // The following two lines are to force the browse not to return
  // a cached copy of the requested xml
  var timestamp = new Date();
  var uniqueURL = url+(url.indexOf("?") > 0 ? "&" : "?")+"timestamp="+timestamp.getTime();

  xmlHttp.open("POST", uniqueURL, true);
  {
    xmlHttp.onreadystatechange = function () 
    {
      if (xmlHttp.readyState == 4)
      {
      	if (hed)
      	  handler(xmlHttp, extraData);
      	else
      	  handler(xmlHttp);
      }
    }

	xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	xmlHttp.setRequestHeader('Content-length', data.length );    
	xmlHttp.setRequestHeader('Connection', 'close');	
  }
  xmlHttp.send(data);
}

function alertHandler(xmlHttp, contentElementId)
{
  alert("attempting to replace"+ contentElementId+" with \n"+
    xmlHttp.responseText);
}

/**
 * Handler to replace the content of a specified element with
 * the content retrieved from a uri.  This handler should be passed into
 * loadXML 
 * @param xmlHttp the xml document to use as the content of the 
 *        specified element Id.
 * @param elementId the id of the element whose inner html should be replaced.
 */
function replaceElementContentHandler(xmlHttp, contentElementId)
{
  try
  {
    document.getElementById(contentElementId).innerHTML = xmlHttp.responseText;
  }
  catch (exc)
  {
    alert("An error occurred <br/>" +
      "Message: " + exc.message + "<br/>" +
      "File: " + exc.fileName + "<br/>" +
      "Line: " + exc.lineNumber + "<br/>" +
      "Name: " + exc.name);
  }
}

/**
 * Function to get a string representation of an attribute. 
 * Uses classes from xmlutil.css for formatting.
 * @param attribute the attribute node to get the string repesentation of.
 * @return the string representation of the specified attribute node.
 */
function xmlAttributeToString(attribute) 
{
  return " <span class='attribname'>" + attribute.nodeName + 
    "</span><span class='attribvalue'>=\"" + attribute.nodeValue + 
    "\"</span>";
}

/**
 * Function to get the string representation of an object.
 * @obj the object to get the string representation for.
 * @return the string representation of the object passed in.
 */
function inspect(obj) 
{
  var objToString = "";
  for (var k in obj)
  {
    objToString += "obj." + k + " = " + obj[k] + "\n";
  }
  return objToString;
}

/**
 * Function to get the a displayable version of the
 * specified xml node.
 * This function produces elements with classes defined
 * in xmlutil.css.
 * @param the node to get the displayable version of.
 * @indent the number of spaces to indent the children.
 */
function xmlNodeToString(node, indent) 
{
  if (node == null)
  {
    return "";
  }
  
  var str = "";
  
  switch (node.nodeType) 
  {
    case 1: // Element
      str += "<div class='element'>&lt;<span class='elementname'>" + 
        node.nodeName + "</span>";
      
      var attrs = node.attributes;
      for (var i = 0; i < attrs.length; i++)
      {
        str += xmlAttributeToString(attrs[i]);
      }
      
      if (!node.hasChildNodes())
      {
        return str + "/&gt;</div>";
      }
      
      str += "&gt;<br />";
      
      var cs = node.childNodes;
      for (var i = 0; i < cs.length; i++)
      {
        str += xmlNodeToString(cs[i], indent + 3);
      }
      
      str += "&lt;/<span class='elementname'>" + node.nodeName + 
        "</span>&gt;</div>";
      break;
  
    case 9: // Document
      var cs = node.childNodes;
      for (var i = 0; i < cs.length; i++)
      {
        str += xmlNodeToString(cs[i], indent);
      }
      break;
  
    case 3: // Text
      if (!/^\s*$/.test(node.nodeValue))
      {
        str += "<span class='text'>" + node.nodeValue + "</span><br />";
      }
      break;
  
    case 7: // ProcessInstruction
      str += "&lt;?" + node.nodeName;
    
      var attrs = node.attributes;
      for (var i = 0; i < attrs.length; i++)
      {
        str += xmlNodeToString(attrs[i]);
      }
      
      str+= "?&gt;<br />"
      break;
  
    case 4: // CDATA
      str = "<div class='cdata'>&lt;![CDATA[<span class='cdata-content'>" + 
        node.nodeValue + "</span>]" + "]></div>";
      break;
      
    case 8: // Comment
      str = "<div class='comment'>&lt;!--<span class='comment-content'>" + 
        node.nodeValue + "</span>--></div>";
      break;
    
    case 10:
        str = "<div class='doctype'>&lt;!DOCTYPE " + node.name;
        if (node.publicId) 
        {
          str += " PUBLIC \"" + node.publicId + "\"";
          if (node.systemId) 
          {
            str += " \"" + node.systemId + "\"";
          }
        }
        else if (node.systemId) 
        {
          str += " SYSTEM \"" + node.systemId + "\"";
        }
        str += "&gt;</div>";        
        break;
    
    default:
      inspect(node);
  }
  
  return str;
}

/**
 * Function to get the a displayable version of the
 * specified xml element.
 * This function produces elements with classes defined
 * in xmlutil.css.
 * @param the node to get the displayable version of.
 * @indent the number of spaces to indent the children.
 */
function xmlElementToString(node, indent) 
{
  if (node == null)
  {
    return "";
  }
  
  var str = "";
  
  switch (node.nodeType) 
  {
    case 1: // Element
      str += "<" + node.nodeName;
      
      var attrs = node.attributes;
      for (var i = 0; i < attrs.length; i++)
      {
        str += " " + attrs[i].nodeName + "=\"" + attrs[i].nodeValue + "\"";
      }
      
      if (!node.hasChildNodes())
      {
        return str + "/>";
      }
      
      str += ">";
      
      var cs = node.childNodes;
      for (var i = 0; i < cs.length; i++)
      {
        str += xmlElementToString(cs[i], indent + 3);
      }
      
      str += "</" + node.nodeName + ">";
      break;
  
    case 9: // Document
      var cs = node.childNodes;
      for (var i = 0; i < cs.length; i++)
      {
        str += xmlElementToString(cs[i], indent);
      }
      break;
  
    case 3: // Text
      if (!/^\s*$/.test(node.nodeValue))
      {
        str += node.nodeValue;
      }
      break;

    case 8: // Comment
      str += "<!-- " + node.nodeValue + "-->";
      break;

    default:
      inspect(node);
  }
  
  return str;
}


/**
 * function to html encode an xml string.
 * @param xml the xml string that should be encoded to make viewable
 *        on an html page.
 */
function encodeXMLforHTML(xml)
{
  return xml.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;").replace(/\t/g, "&nbsp;&nbsp;&nbsp;").replace(/\n/g, "<br />");
}

function getCountryRegions(countryCode, url, regionData, selectedRegionCode)
{
  if (countryCode)
  {
  	data = 'country=' + escape(countryCode);
  	if (selectedRegionCode)
  	{
  		data = data + '&selected='+ selectedRegionCode;
  	}
  	
	$.ajax({
		url: url,
		data: data,
		dataType: 'json',
		error: function(response, status, error) {
					window.alert("Unable to get country region. If this continues, contact support.");				
		},
		success: function(json) {
		  var html = json.regionsHTML;
		  
          for(var i=0; i < regionData.length; i++)
          {
		    var result = html.replace('%ID%', regionData[i].id);
		    result = result.replace('%NAME%', regionData[i].name);
		    if (regionData[i].onchange)
		    {
			    result = result.replace('%ONCHANGE%', regionData[i].onchange);
			}
			else
			{
			    result = result.replace('%ONCHANGE%', '');			
			}

		    if (regionData[i].styleClass)
		    {
			    result = result.replace('%STYLECLASS%', regionData[i].styleClass);
			}
			else
			{
			    result = result.replace('%STYLECLASS%', '');			
			}
						
			if (regionData[i].disabled)
			{
				result = result.replace("%DISABLED%", "disabled=\"disabled\"");
			}
			else
			{
				result = result.replace("%DISABLED%", "");
			}
			
	  	    document.getElementById(regionData[i].divId).innerHTML = result;
          }	  
		}
	});
  }
}