﻿var iKeys = 0;
var productType = 1;
var cartIsValid = true;
var ignorePopup = false;
var focusField = null;
var defGift = '';


function setDropDownValue(ddl, value)
{
  ddl.selectedIndex = -1;
  
  for (var i=0; i < ddl.length; i++)
  {
    if (ddl.options[i].value == value)
      ddl.options[i].selected = true;
  }
}

function selectAll(select) 
{
   var formObj = document.forms[0];
   
   for (var i=0;i < formObj.length;i++) 
   {
      fldObj = formObj.elements[i];
      
      if (fldObj.type == 'checkbox')
      { 
         fldObj.checked = select;
      }
      else if (fldObj.type == 'radio')
      {
        fldObj.checked = select;
      }
   }
}

function selectAllText(obj)
{ 
  if (obj != null)
  {
    obj.focus();
    obj.select();
  }
}

function findElement(id) 
{
   var formObj = document.forms[0];
   for (var i=0;i < formObj.length;i++) 
   {
      fldObj = formObj.elements[i];
      if (fldObj.id.search(id) != -1)
        return fldObj;
   }
   
   return null;
}

function findItem(id) 
{
   for (var i=0;i < document.all.length;i++) 
   {
      fldObj = document.all[i];
      if (fldObj.id.search(id) != -1)
        return fldObj;
   }
   
   return null;
}

function findImage(id) 
{
   for (var i=0;i < document.images.length;i++) 
   {
      fldObj = document.images[i];
      if (fldObj.id.search(id) != -1)
        return fldObj;
   }
   
   return null;
}

// --------------- DATE FUNCTIONS ----------------

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

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 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate2(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}






function FormatDate(DateToFormat,FormatAs){
  if(DateToFormat==""){return"";}
  if(!FormatAs){FormatAs="dd/mm/yyyy";}

  var strReturnDate;
  FormatAs = FormatAs.toLowerCase();
  DateToFormat = DateToFormat.toLowerCase();
  var arrDate
  var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  var strMONTH;
  var Separator;

  while(DateToFormat.indexOf("st")>-1){
    DateToFormat = DateToFormat.replace("st","");
  }

  while(DateToFormat.indexOf("nd")>-1){
    DateToFormat = DateToFormat.replace("nd","");
  }

  while(DateToFormat.indexOf("rd")>-1){
    DateToFormat = DateToFormat.replace("rd","");
  }

  while(DateToFormat.indexOf("th")>-1){
    DateToFormat = DateToFormat.replace("th","");
  }

  if(DateToFormat.indexOf(".")>-1){
    Separator = ".";
  }

  if(DateToFormat.indexOf("-")>-1){
    Separator = "-";
  }


  if(DateToFormat.indexOf("/")>-1){
    Separator = "/";
  }

  if(DateToFormat.indexOf(" ")>-1){
    Separator = " ";
  }

  arrDate = DateToFormat.split(Separator);
  DateToFormat = "";
	  for(var iSD = 0;iSD < arrDate.length;iSD++){
		    if(arrDate[iSD]!=""){
		    DateToFormat += arrDate[iSD] + Separator;
		  }
	  }
  DateToFormat = DateToFormat.substring(0,DateToFormat.length-1);
  arrDate = DateToFormat.split(Separator);

  if(arrDate.length < 3){
    return "";
  }

  var DAY = arrDate[0];
  var MONTH = arrDate[1];
  var YEAR = arrDate[2];




  if(parseFloat(arrDate[1]) > 12){
    DAY = arrDate[1];
    MONTH = arrDate[0];
  }

  if(parseFloat(DAY) && DAY.toString().length==4){
    YEAR = arrDate[0];
    DAY = arrDate[2];
    MONTH = arrDate[1];
  }


  for(var iSD = 0;iSD < arrMonths.length;iSD++)
  {
    var ShortMonth = arrMonths[iSD].substring(0,3).toLowerCase();
    var MonthPosition = DateToFormat.indexOf(ShortMonth);
	    if(MonthPosition > -1)
	    {
	      MONTH = iSD + 1;
		      if(MonthPosition == 0)
		      {
		        DAY = arrDate[1];
		        YEAR = arrDate[2];
		      }
	    break;
	    }
  }

  var strTemp = YEAR.toString();
  if(strTemp.length==2)
  {
	  if(parseFloat(YEAR)>40)
	  {
	    YEAR = "19" + YEAR;
	  }
	  else
	  {
	    YEAR = "20" + YEAR;
	  }

  }


	  if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
	  {
	  MONTH = "0" + MONTH;
	  }
	  if(parseInt(DAY)< 10 && DAY.toString().length < 2)
	  {
	    DAY = "0" + DAY;
	  }
    switch (FormatAs)
    {
      case "dd/mm/yyyy":
        return DAY + "/" + MONTH + "/" + YEAR;
      case "mm/dd/yyyy":
        return MONTH + "/" + DAY + "/" + YEAR;
      case "dd/mmm/yyyy":
        return DAY + " " + arrMonths[MONTH -1].substring(0,3) + " " + YEAR;
      case "mmm/dd/yyyy":
        return arrMonths[MONTH -1].substring(0,3) + " " + DAY + " " + YEAR;
      case "dd/mmmm/yyyy":
        return DAY + " " + arrMonths[MONTH -1] + " " + YEAR;	
      case "mmmm/dd/yyyy":
        return arrMonths[MONTH -1] + " " + DAY + " " + YEAR;
	  }

  return DAY + "/" + strMONTH + "/" + YEAR;;

}

function isDate(DateToCheck){
  if(DateToCheck==""){return true;}
  
  var m_strDate = FormatDate(DateToCheck);
  
  if(m_strDate==""){
    return false;
  }
  
  var m_arrDate = m_strDate.split("/");
  var m_DAY = m_arrDate[0];
  var m_MONTH = m_arrDate[1];
  var m_YEAR = m_arrDate[2];
  if(m_YEAR.length > 4){return false;}
  
  m_strDate = m_MONTH + "/" + m_DAY + "/" + m_YEAR;
  var testDate=new Date(m_strDate);
  
  if(testDate.getMonth()+1==m_MONTH){
    return true;
  } 
  else
  {
    return false;
  }
}//end function







// ------------------- END OF DATE FUNCTIONS -----------------------------------

function isPrice(price, canBeNegative)
 {
	  var i;
	  var s = price;
	  
	  if (s == "")
	  {
	    return false;
	  }
	  
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if ((((c < "0") || (c > "9")) && (c != ".") && (c != "-")))
        {
          return false;
        }
    }
    
    if (canBeNegative == false)
    {
      if (parseFloat(price) < 0)
      {
        return false;
      }
    }
    
    // All characters are numbers.
    return true;
}

function isDecimal(price)
 {
	  var i;
	  var s = price;
	  
	  if (s == "")
	  {
	    return false;
	  }
	  
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if ((((c < "0") || (c > "9")) && (c != ".")))
        {
          return false;
        }
    }
    
    // All characters are numbers.
    return true;
}

function val_IsDate(sender, args)
 {
   args.IsValid = isDate(args.Value);
 }
 
 
 function val_IsInteger(sender, args)
 {
   args.IsValid = isInteger(args.Value);
   
   if (parseInt(args.Value) < 0)
        args.IsValid = false;
}

function val_IsDiscount(sender, args)
 {
	  var i;
	  var s = args.Value;
	  
	  if (s == "")
	  {
	    args.IsValid = false;
	    return;
	  }
	  
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if ((((c < "0") || (c > "9")) && (c != ".")))
        {
          args.IsValid = false;
          return;
        }
    }
    
    // also check for not greater than 100 or less than 0.
    if (args.IsValid)
    {
        if (parseFloat(args.Value) > 100 || parseFloat(args.Value) < 0)
        {
          args.IsValid = false;
          return;
        }
    }
    
    // All characters are numbers.
    args.IsValid = true;
}

function val_IsPositivePrice(sender, args)
{
    args.IsValid = isPrice(args.Value, false);
}

function val_IsPrice(sender, args)
{
    args.IsValid = isPrice(args.Value, true);
}

function val_IsDecimal(sender, args)
{
    args.IsValid = isDecimal(args.Value);
}


function val_Strand(sender, args)
{
  var strand = findElement('StrandCheckBox')
  var valid = true;
  
  if (strand != null)
  {
    if (strand.checked)
    {
      if (args.Value != "")
      {
        valid = isInteger(args.Value);
        
        if (valid)
          if (parseInt(args.Value) <= 0)
            valid = false;
      }
      else
        valid = false;
    }
  }
  
  args.IsValid = valid;
}

function val_Engraving(sender, args)
{
  var strand = findElement('EngravingCheckBox')
  var valid = true;
  
  if (strand != null)
  {
    if (strand.checked)
    {
      if (args.Value != "")
      {
        valid = isInteger(args.Value);
        
        if (valid)
          if (parseInt(args.Value) <= 0)
            valid = false;
      }
      else
        valid = false;
    }
  }
  
  args.IsValid = valid;
}

var poppedWindow = null;

function popWindow(url, name, width, height)
{
  var left = (screen.availWidth - width) / 2;
  var top = (screen.availHeight - height) / 2;
  poppedWindow = window.open(url, name, 'width=' + width + ',height=' + height + 
                        'left=' + left + ',top=' + top + ', status=yes,scrollbars=yes,resizable=yes');
  poppedWindow.focus();
}

function popImageWindow(url, name, width, height)
{
  var left = (screen.availWidth - width) / 2;
  var top = (screen.availHeight - height) / 2;
  poppedWindow = window.open(url, name, 'width=' + width + ',height=' + height + 
                        'left=' + left + ',top=' + top);
  poppedWindow.focus();
}

function writeToWindow(win, txt)
{
  win.document.write(txt);
}





// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function checkInternationalPhone(strPhone)
{
  s=stripCharsInBag(strPhone,validWorldPhoneChars);
  return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function val_Phone(sender, args)
{
  args.IsValid = checkInternationalPhone(args.Value)
}








// ############### PRODUCT VALIDATION #########################
var cartErrMsg = '';

function cartValid(sender, args)
{
  var valid = true;
  var bTag = false;
  
  qty = findElement('WithQuantityTextBox');
  
  if (qty != null)
    bTag = true;
    
  valid = validateCustomPrice();
  
  if (valid == true)
    valid = validateQuantity();
  
  if (bTag)
  {
    if (valid == true)
      valid = validateEngraving();
  }
      
  if (valid == true)
    valid = validateStrand();
  
  if (valid == true)
    valid = validateGift();
    
  if (valid == true)
    valid = validateTypewriter();
    
  if (valid == true)
    valid = validateGiftCert();
  
  if (valid == true)
    valid = validateSnowman();
  
  if (valid == false)
  {
    if (cartErrMsg != "")
      alert(cartErrMsg)
    
    valid = false;
  }
  // if bracelet with tag and they ordered with tag
  else if ((productType == 1 && findElement('Engraving1')) || productType == 6)
  {
    if (ignorePopup == false)
    {
        valid = confirm('Stop!  Have you measured your wrist and added 1 inch?  Lauren\'s Hope Bracelets do not fit ' +
								'like the average bracelet.  Remember, the tag does not bend so you need to add an inch to ' +
								'your wrist measurement.  Returns for sizing will need to include the $6 return shipping and ' +
								'handling fee.  If you need to change your size please press cancel on this message') ;
    }
    else
      valid = true;
  }
  // if interchangeable strand or order bracelet with tag but with not tag.
  else if (productType == 7 || (productType == 1 && findElement('Engraving1') == null))
  {
    if (ignorePopup == false)
    {
        valid = confirm('Stop! Even though you are ordering an interchangeable strand only, you still need to measure ' +
                'your wrist and add 1 inch.  ALL of our bracelets include the ID tag in the measurement-even if you ' +
                'are ordering JUST the strand.  Returns for sizing will need to include the $6 return shipping and ' +
                'handling fee.  If you need to change your size please press cancel on this message');
    }
    else
      valid = true;
  }
  // Mothers Bracelet
  else if (productType == 8)
  {
    if (ignorePopup == false)
    {
        valid = confirm('Stop!  Have you measured your wrist and added 1/2 inch?  Please be sure to take a ' +
                'snug wrist measurement and add 1/2 inch.  Returns for sizing will need to include the $6 ' +
                'shipping and handling fee.  If you need to change your size please press cancel on this message.');
    }
    else
      valid = true;

  }
  // Chunky
  else if (productType == 9)
  {
    if (ignorePopup == false)
    {
        valid = confirm('STOP!  You are ordering a chunky bracelet!  You will need to measure your wrist and add 1 1/2 ' +
                'inches to your snug wrist measurement.  Lauren\'s Hope Bracelets do not fit like the average bracelet.  ' +
                'Remember, the tag does NOT bend so you will need to add 1 1/2 inches to your measurement.  Returns for ' +
                'sizing will need to include the $6 return shipping and handling fee.  If you need to change your size ' +
                'please press cancel on this message.');
    }
    else
      valid = true;

  }
  
  return valid;
}

function validateCustomPrice()
{
  var obj = findElement('ProductPriceTextBox');
  
  if (obj == null)
    return true;
  else
    return isPrice(findElement('ProductPriceTextBox').value)
}

function validateQuantity()
{
  var qtyTB = null;
  var qty = 0;
  
  qtyTB = findElement('WithQuantityTextBox');
  
  if (qtyTB == null)
    qtyTB = findElement('WithoutQuantityTextBox');
  
  qty = qtyTB.value;
    
  if (qty == '')
  {
    cartErrMsg = 'You must enter a quantity';
    return false;
  }
  else if (isInteger(qty) == false)
  {
    cartErrMsg = 'You must enter a valid quantity';
    return false;
  }
  else
    cartErrMsg = '';
  
  return true;
}

function validateEngraving()
{
  var valid = true;
  
  // first see if we have any engravings
  
  if (findElement('Engraving1') != null)
  {
    var engravingNo = 0;
    
    // find how many strands
    var formObj = document.forms[0];
    for (var i=0;i < formObj.length;i++) 
    {
      fldObj = formObj.elements[i];
      if (fldObj.id.search('Engraving') != -1)
        engravingNo += 1;
    }
    
    // first make sure at least one is filled outfor (var i=strandNo; i > 0; i--)
    // or that the blank tag is selected
    var blankObj = findElement('BlankTagCheckBox')
        
    var filled = false;
    for (var i=engravingNo; i > 0; i--)
    {
      var txt = findElement('Engraving' + i).value;
      
      if (txt != '')
      {
        filled = true;
        break;
      }
    }
    
    if (filled == false && blankObj.checked == false)
    {
      cartErrMsg = 'You\'ve selected an item with Customized Lettering. \n However you have ' +
                          'not filled out all the lettering fields.'
      return false;
    }
    
    // we will do two loops.  We will make sure that they did not enter info
    // on a higher strand and not a lower strand
    for (var i=engravingNo; i > 0; i--)
    {
      var txt = findElement('Engraving' + i).value;
      
      if (txt != '')
      {
        for (var j=i-1; j > 0; j--)
        {
          var txt2 = findElement('Engraving' + j).value;
          
          if (txt2 == '')
          {
            cartErrMsg = 'Engraving lines must be filled out in the order they appear.'
            valid = false;
            return valid;
          }
        }
      }
    }
  }
  
  return valid;
}

function removeEngravingText()
{
  var obj = null;
  var blankTagObj = findElement('BlankTagCheckBox')
  
  if (blankTagObj.checked == true)
  {
    for (var i=1; i <= 5; i++)
    {
      obj = findElement('Engraving' + i);
      
      if (obj != null)
        obj.value = '';
    }
  }
}

function validateStrand()
{
  var valid = true;
  
  // first see if we have any strands
  
  if (findElement('Strand1') != null)
  {
    var strandNo = 0;
    
    // find how many strands
    var formObj = document.forms[0];
    for (var i=0;i < formObj.length;i++) 
    {
      fldObj = formObj.elements[i];
      if (fldObj.id.search('Strand') != -1)
        strandNo += 1;
    }
    
    // first make sure at least one is filled outfor (var i=strandNo; i > 0; i--)
    var filled = false;
    for (var i=strandNo; i > 0; i--)
    {
      var txt = findElement('Strand' + i).value;
      
      if (txt != '')
      {
        filled = true;
        break;
      }
    }
    
    if (filled == false)
    {
      cartErrMsg = 'You\'ve selected an item with Customized Lettering. \n However you have ' +
                          'not filled out all the lettering fields.'
      return false;
    }
    
    // we will do two loops.  We will make sure that they did not enter info
    // on a higher strand and not a lower strand
    for (var i=strandNo; i > 0; i--)
    {
      var txt = findElement('Strand' + i).value;
      
      if (txt != '')
      {
        for (var j=i-1; j > 0; j--)
        {
          var txt2 = findElement('Strand' + j).value;
          
          if (txt2 == '')
          {
            cartErrMsg = 'You\'ve selected an item with Customized Lettering. \n However you have ' +
                          'not filled out all the lettering fields in the correct order.'
            valid = false;
            return valid;
          }
        }
      }
    }
  }
  
  return valid;
}

function validateGift()
{
  var valid = true;
  
  if (findElement('GiftWrapDropDownList') != null)
  {
    var giftDDL = findElement('GiftCardDropDownList');
    var giftMsg = findElement('GiftMessageTextBox');
    
    if (giftDDL.value != '' && (giftMsg.value == defGift))
    {
      cartErrMsg = 'You have selected a Gift Card but have not\nentered a message to put on the card.' + 
                    '\n\nIf you do not want a Gift Card, please \nreturn the Gift Card field to - ' +
                    'select - and \ndelete all text from the Message field.';
      valid = false;
    }
    else if (giftDDL.value == '' && giftMsg.length > 0)
    {
      cartErrMsg = 'Please select the type of Gift Card \nyou want sent with your order.' +
                    '\n\nIf you do not want a Gift Card, please \ndelete all text from the message field.';
      valid = false;
    }
    else if (giftDDL.value != '' && giftMsg.length == 0)
    {
      cartErrMsg = 'You have selected a Gift Card but have not\nentered a message to put on the card.' + 
                    '\n\nIf you do not want a Gift Card, please \nreturn the Gift Card field to - ' +
                    'select - and \ndelete all text from the Message field.';
      valid = false;
    }
    else if (CountWords(giftMsg, false, false) > 15)
    {
      cartErrMsg = 'You can only have a gift card message with 15 words or less.';
      valid = false;
    }
  }
  
  return valid;
}

function validateTypewriter()
{
  var sCol, oKeyImg, iPos, iPos2;
  var ret = '';
  
  if (findImage('keyImg1') != null)
  {
	  for (var i = 1; i <= iKeys; i++)
	  {
		  oKeyImg = findImage('keyImg' + i);
  		
		  if (oKeyImg != null)
		  {
		    sCol = oKeyImg.src;
    		
		    iPos = InStr(0, sCol, '/')
    		
		    while (iPos != -1)
		    {
			    iPos2 = iPos;				
			    iPos = InStr(iPos + 1, sCol, '/');
		    }
    	  
		    sKey = Mid(sCol, iPos2 + 1, sCol.length - iPos2 - 1);
		    sKey = Left(sKey, sKey.length - 4);
		    if (sKey == 'spacer1x1')
		      sKey = ''
    		
		    if (ret != '')
		      ret = ret + '&'
    		
		    ret = ret + 'key' + i + '=' + sKey;
		  }
	  }
  	
	  findElement('TypewriterHiddenField').value = ret;
  }
  
  return true;
}

function validateGiftCert()
{  
  var valid = true;
  if (findElement('GiftCertPriceTextBox') != null)
  {
    valid = isPrice(findElement('GiftCertPriceTextBox').value)
    
    if (valid == false)
    {
      alert('You must enter a valid amount for the Gift Certificate');
    }
  }
  return valid;
}

function validateSnowman()
{  
  var valid = true;
  
  if (noSnowmen == 0 && findElement('SnowmanPlaceHolder') != null)
  {
    valid = false;
      alert('You must enter a value for at least one of the snowmen');
  }
  return valid;
}
// ############### END OF PRODUCT VALIDATION ##################





function addOption(selectbox,text,value )
{
  var optn = document.createElement("OPTION");
  optn.text = text;
  optn.value = value;
  selectbox.options.add(optn);
}


function addPropertyValue()
{
  var tb = findElement('PropertyValueTextBox');
  var ddl = findElement('PropertyValuesDropDownList');
  
  if (tb == null || ddl == null)
    return false;
  
  if (tb.value == "")
    return false;
    
  
  addOption(ddl, tb.value, tb.value);
  tb.value = '';
  tb.focus();
  return false;
}

function removePropertyValue()
{
  var ddl = findElement('PropertyValuesDropDownList');
  
  if (ddl == null)
    return;
  
  var i; 
  for (i = ddl.length - 1; i>=0; i--)
  { 
    if (ddl.options[i].selected)
    { 
      ddl.remove(i); 
    } 
  } 

    
  return false;
}


function checkPropertyValues()
{
  return true;
  
  var tb = findElement('PropertyNameTextBox');
  var ddl = findElement('PropertyValuesDropDownList');
  
  if (tb == null || ddl == null)
    return false;
    
  if (tb.value == "" && ddl.length > 0)
  {
    alert('You have Property Values assigned but no Property Name')
    return false;
  }
  else if (tb.value != "" && ddl.length == 0)
  {
    alert('You have entered a Property Name but have not assigned any Property Values.')
    return false;
  }
  else
    return true;
}

function changeClasp()
{
  ddl = findElement('ClaspDropDownList')
  img = findImage('ClaspImage')
  
  if (ddl == null || img == null)
    return;
  
  img.src = 'images/' + claspImg[ddl.selectedIndex]
  img.style.visibility = 'visible';
}

function changeSlide()
{
  ddl = findElement('SlideDropDownList')
  img = findImage('SlideImage')
  
  if (ddl == null || img == null)
    return;
  
  if (ddl.selectedIndex == 0)
  {
    img.src = '';
    img.style.visibility = 'hidden';
  }
  else
  {
    img.src = 'images/' + slideImg[ddl.selectedIndex]
    img.style.visibility = 'visible';
  }
}




function GetRandomNumber(number,symbols)
{
  var length=62;
  var character = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ£$%&*+-?<>";
  var password="";
  if(symbols=="yes"){length=length+10}
  for (var i=0; i<=(number-1);i++){
  var rand = Math.floor(Math.random()*length);
  password = password+=character.substring(rand,rand+1)}
  return password
}


function SendXMLHttp(sUrl, sType)
{
  var today = new Date();
  var sToken = GetRandomNumber(20, 'no')
  var iTime = today.getHours() * 3600000 + today.getMinutes() * 60000 + today.getSeconds() * 1000 + today.getMilliseconds()
  var oXML = new ActiveXObject("Msxml2.XMLHTTP");
  
  sUrl = sUrl + '&time=' + sToken + '-' + iTime;
  oXML.Open(sType, sUrl, false);

  if (sType == "POST")
  	oXML.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

 	oXML.send(); //Send the stream
 
  var ret = oXML.responseText;
  return (ret)
}

function addToNewsletter(path)
{
  var email = findElement('NewsletterEmailTextBox')
  
  if (email == null)
    alert('you must enter an email address');
  else if (email.value == '' || email.value == 'enter e-mail address here')
    alert('you must enter an email address');
  else
  {
    var resp = SendXMLHttp(path + '?email=' + email.value, 'GET');
    resp = resp.substring(0,1);
        
    if (resp == '1')
      alert('You have been added to our newsletter.  Thank you.');
    else if (resp == '0')
      alert('There was a problem adding you to our newsletter.  Please try again later');
    else
    {
      selectAllText(email);
      alert('You have entered an invalid email address');
    }
  }
}

function ignoreEnter(myfield, e)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13)
   return false;
  else
   return true;
}

function enterPressed(myfield, e)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13)
   return true;
  else
   return false;
}

function submitEnterButton(myfield,e, button)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13)
     {
     button.click();
     return false;
     }
  else
     return true;
}

function submitEnter(myfield,e)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13)
     {
     myfield.form.submit();
     return false;
     }
  else
     return true;
}


function CountWords (this_field, show_word_count, show_char_count) {
  if (show_word_count == null) {
    show_word_count = true;
  }
  if (show_char_count == null) {
    show_char_count = false;
  }
  
  var char_count = this_field.value.length;
  var fullStr = this_field.value + " ";
  var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
  var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
  var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
  var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
  var splitString = cleanedStr.split(" ");
  var word_count = splitString.length -1;
  
  if (fullStr.length <2) {
    word_count = 0;
  }
  if (word_count == 1) {
    wordOrWords = " word";
  }
  else {
    wordOrWords = " words";
  }
  
  if (char_count == 1) {
    charOrChars = " character";
  } else {
    charOrChars = " characters";
  }
  
  if (show_word_count & show_char_count) {
    alert ("Word Count:\n" + "    " + word_count + wordOrWords + "\n" + "    " + char_count + charOrChars);
  }
  else {
    if (show_word_count) {
      alert ("Word Count:  " + word_count + wordOrWords);
    }
    else {
      if (show_char_count) {
        alert ("Character Count:  " + char_count + charOrChars);
        }
     }
  }
  return word_count;
}


/* snowman */
var noSnowmen = 0;
var snowMen = new Array()
var snowMenDesc = new Array()

snowMenDesc[0] = 'Black hat with black crystal'
snowMenDesc[1] = 'Red hat with red crystal'
snowMenDesc[2] = 'Amethyst hat and crystal'
snowMenDesc[3] = 'Red hat with amethyst crystal'
snowMenDesc[4] = 'Light sapphire hat and crystal'
snowMenDesc[5] = 'Rose hat and crystal'
snowMenDesc[6] = 'Sapphire hat and crystal'
snowMenDesc[7] = 'Tanzanite hat and crystal'

function addSnowman(snowmanNo)
{
  var oSnowman = document.getElementById('snowmanDiv');
  var ddl = null;
  var i = parseInt(noSnowmen) + 1;
  
  ddl = 'Snowman ' + i + ': ' + snowMenDesc[snowmanNo - 1]
  
  var newdiv = document.createElement('div');
  newdiv.setAttribute('id', 'snowmanDiv' + i);
  
  ddl = ddl + '<input type="hidden" name="snowmanOption' + i + '" value="' + snowmanNo + ':' + snowMenDesc[snowmanNo-1] + '"/>'
  
  newdiv.innerHTML = newdiv.innerHTML + ddl
  
  ddl = '&nbsp;<a href="javascript: removeSnowman(' + noSnowmen + ');">remove</a>';
  newdiv.innerHTML = newdiv.innerHTML + ddl + '<br/>';
  
  oSnowman.appendChild(newdiv);
  
  snowMen[noSnowmen] = snowmanNo
  noSnowmen = noSnowmen + 1
  
  findElement('SnowmanHiddenField').value = noSnowmen;
}

function removeSnowman(i)
{
  // if we only have one snowman, we wont do anything
  //if (noSnowmen == 1)
    //return;
  
  // first remove the item from the list
  var oSnowman = document.getElementById('snowmanDiv');
  //var olddiv = document.getElementById('snowmanDiv' + i)
  //oSnowman.removeChild(olddiv);
  
  snowMen[i] = ''
  
  // now clear the div
  oSnowman.innerHTML = '';
  
  // create the new list
  setSnowmenItems()
}

function setSnowmenItems()
{
  
  // copy the array
  var tempArray = new Array()
  var count = 0;
  
  for (var i = 0; i < noSnowmen; i++)
  {
    if (snowMen[i] != '')  
    {
      tempArray[count] = snowMen[i]
      count = count + 1
    }
  }
  
  // reset the array
  noSnowmen = 0;
  snowMen = new Array()
    
  for (var i=0; i < count; i++)
  {
    snowMen[i] = tempArray[i]
    addSnowman(snowMen[i])
  }
}

function validationCheckout(button)
{
  var specialText = '';
  var billingText = '';
  var shippingText = '';
  var re = null;
  var ddl = null;
  
  // check if we need to validate email
  var email = document.getElementById('ctl00$MainContent$EmailTextBox').value;
  
  if (document.all['ctl00_MainContent_EmailRequired'] || email != '')
  {
    if (email == '')
    {
        specialText = specialText + '<li>Email is required</li>';
        document.all['ctl00_MainContent_EmailRequired'].style.visibility = 'visible';
        document.all['ctl00_MainContent_EmailExpressionRequired'].style.visibility = 'hidden';
    }
    else
    {
      if (document.all['ctl00_MainContent_EmailRequired'])
        document.all['ctl00_MainContent_EmailRequired'].style.visibility = 'hidden';
      
      re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      
      if (re.test(email) == false)
      {
        specialText = specialText + '<li>Email is invalid</li>';
        document.all['ctl00_MainContent_EmailExpressionRequired'].style.visibility = 'visible';
      }
      else
        document.all['ctl00_MainContent_EmailExpressionRequired'].style.visibility = 'hidden';
    }
  }
  
  // check business name
  if (document.getElementById('ctl00$MainContent$BusinessNameTextBox').value == '')
  {
    specialText = specialText + '<li>Business Name is required.</li>';
    document.all['ctl00_MainContent_BusinessNameRequiredFieldValidator'].style.visibility = 'visible';
  }
  
  // check sales tax id
  if (document.getElementById('ctl00$MainContent$SalesTaxIDTextBox').value == '')
  {
    specialText = specialText + '<li>Sales Tax ID is required.</li>';
    document.all['ctl00_MainContent_SalesTaxIDRequiredFieldValidator'].style.visibility = 'visible';
  }
  
  // check billing
  /*
  if (document.getElementById('ctl00$MainContent$BillingFirstNameTextBox').value == '')
  {
    billingText = billingText + '<li>Billing First Name is required.</li>';
    document.all['ctl00_MainContent_BillingFirstNameRequiredFieldValidator'].style.visibility = 'visible';
  }
  else
    document.all['ctl00_MainContent_BillingFirstNameRequiredFieldValidator'].style.visibility = 'hidden';
    
  if (document.getElementById('ctl00$MainContent$BillingLastNameTextBox').value == '')
  {
    billingText = billingText + '<li>Billing Last Name is required.</li>';
    document.all['ctl00_MainContent_BillingLastNameRequiredFieldValidator'].style.visibility = 'visible';
  }
  else
    document.all['ctl00_MainContent_BillingLastNameRequiredFieldValidator'].style.visibility = 'hidden';
  */
  
  if (document.getElementById('ctl00$MainContent$BillingAddressLine1TextBox').value == '')
  {
    billingText = billingText + '<li>Billing Address Line 1 is required.</li>';
    document.all['ctl00_MainContent_BillingAddressLine1RequiredFieldValidator'].style.visibility = 'visible';
  }
  else
    document.all['ctl00_MainContent_BillingAddressLine1RequiredFieldValidator'].style.visibility = 'hidden';
    
  
  if (document.getElementById('ctl00$MainContent$BillingCityTextBox').value == '')
  {
    billingText = billingText + '<li>Billing City is required.</li>';
    document.all['ctl00_MainContent_BillingCityRequiredFieldValidator'].style.visibility = 'visible';
  }
  else
    document.all['ctl00_MainContent_BillingCityRequiredFieldValidator'].style.visibility = 'hidden';
    
  
  ddl = document.getElementById('ctl00$MainContent$BillingStateDropDownList')
  if (ddl.options[ddl.selectedIndex].value == '')
  {
    billingText = billingText + '<li>Billing State is required.</li>';
    document.all['ctl00_MainContent_BillingStateRequiredFieldValidator'].style.visibility = 'visible';
  }
  else
    document.all['ctl00_MainContent_BillingStateRequiredFieldValidator'].style.visibility = 'hidden';
    
  
  if (document.getElementById('ctl00$MainContent$BillingZipCodeTextBox').value == '')
  {
    billingText = billingText + '<li>Billing ZipCode is required.</li>';
    document.all['ctl00_MainContent_BillingZipRequiredFieldValidator'].style.visibility = 'visible';
  }
  else
    document.all['ctl00_MainContent_BillingZipRequiredFieldValidator'].style.visibility = 'hidden';
    
  if (document.all['ctl00_MainContent_BillingDayPhoneRequiredFieldValidator'])
  {
    if (document.getElementById('ctl00$MainContent$BillingDayPhoneTextBox').value == '')
    {
      billingText = billingText + '<li>Billing Day Phone is required.</li>';
      document.all['ctl00_MainContent_BillingDayPhoneRequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_BillingDayPhoneRequiredFieldValidator'].style.visibility = 'hidden';
  }
  
  // did they click the continue button?  If so validate the shipping as well
  if (button.id.indexOf('ContinueButton') > -1)
  {
    /*
    if (document.getElementById('ctl00$MainContent$ShippingFirstNameTextBox').value == '')
    {
      shippingText = shippingText + '<li>Shipping First Name is required.</li>';
      document.all['ctl00_MainContent_ShippingFirstNameRequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_ShippingFirstNameRequiredFieldValidator'].style.visibility = 'hidden';
      
    if (document.getElementById('ctl00$MainContent$ShippingLastNameTextBox').value == '')
    {
      shippingText = shippingText + '<li>Shipping Last Name is required.</li>';
      document.all['ctl00_MainContent_ShippingLastNameRequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_ShippingLastNameRequiredFieldValidator'].style.visibility = 'hidden';
    */
    
    if (document.getElementById('ctl00$MainContent$ShippingAddressLine1TextBox').value == '')
    {
      shippingText = shippingText + '<li>Shipping Address Line 1 is required.</li>';
      document.all['ctl00_MainContent_ShippingAddressLine1RequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_ShippingAddressLine1RequiredFieldValidator'].style.visibility = 'hidden';
      
    if (document.getElementById('ctl00$MainContent$ShippingCityTextBox').value == '')
    {
      shippingText = shippingText + '<li>Shipping City is required.</li>';
      document.all['ctl00_MainContent_ShippingCityRequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_ShippingCityRequiredFieldValidator'].style.visibility = 'hidden';
      
    
    ddl = document.getElementById('ctl00$MainContent$ShippingStateDropDownList')
    if (ddl.options[ddl.selectedIndex].value == '')
    {
      shippingText = shippingText + '<li>Shipping State is required.</li>';
      document.all['ctl00_MainContent_ShippingStateRequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_ShippingStateRequiredFieldValidator'].style.visibility = 'hidden';
      
    if (document.getElementById('ctl00$MainContent$ShippingZipCodeTextBox').value == '')
    {
      shippingText = shippingText + '<li>Shipping ZipCode is required.</li>';
      document.all['ctl00_MainContent_ShippingZipCodeRequiredFieldValidator'].style.visibility = 'visible';
    }
    else
      document.all['ctl00_MainContent_ShippingZipCodeRequiredFieldValidator'].style.visibility = 'hidden';
      
    if (document.all['ctl00_MainContent_ShippingDayPhoneRequiredFieldValidator'])
    {
      if (document.getElementById('ctl00$MainContent$ShippingDayPhoneTextBox').value == '')
      {
        shippingText = shippingText + '<li>Shipping Day Phone is required.</li>';
        document.all['ctl00_MainContent_ShippingDayPhoneRequiredFieldValidator'].style.visibility = 'visible';
      }
      else
        document.all['ctl00_MainContent_ShippingDayPhoneRequiredFieldValidator'].style.visibility = 'hidden';
    }
  }
  
  document.all['SpecialOptionsErrorSpan'].innerHTML = specialText;
  document.all['BillingErrorsSpan'].innerHTML = billingText;
  document.all['ShippingErrorsSpan'].innerHTML = shippingText;
  
  if (specialText == '' && billingText == '' && shippingText == '')
    return true
  else
    return false;
}