
<!-- these are the House Atreides scripts
// (c) James Hoskin 2005-9, Last updated 21st May 2009

var tostep = "";

function setToStep(step)
{
  tostep = "step"+step;
  return;
};

function wipeCardDetails(mode,isphonedin)
{
  if ((mode == "DebitCard") || (mode == "CreditCard"))
  {
    if (isphonedin == "phonedin")
      document.getElementById("cardNumber").value = "to be phoned in";
    else
      document.getElementById("cardNumber").value = "";
  }

  if (mode == "CreditCard")
  {
    document.getElementById("cvv").value = "";
  }

  return;
};

function UseDeliveryAddress(field)
{
  if (field.checked)
  {
    // these tmp values get set by PHP before this script is called.
    document.getElementById("billingAddress1").value = tmpdeladdress[0];
    document.getElementById("billingAddress2").value = tmpdeladdress[1];
    document.getElementById("billingAddress3").value = tmpdeladdress[2];
    document.getElementById("billingAddress4").value = tmpdeladdress[3];
    document.getElementById("billingPostcode").value = tmpdeladdress[4];
    document.getElementById("billingCountry").value = tmpdeladdress[5];

    document.getElementById("billingAddress1").disabled = true;
    document.getElementById("billingAddress2").disabled = true;
    document.getElementById("billingAddress3").disabled = true;
    document.getElementById("billingAddress4").disabled = true;
    document.getElementById("billingPostcode").disabled = true;
    document.getElementById("billingCountry").disabled = true;
  }
  else
  {
    document.getElementById("billingAddress1").value = tmpbiladdress[0];
    document.getElementById("billingAddress2").value = tmpbiladdress[1];
    document.getElementById("billingAddress3").value = tmpbiladdress[2];
    document.getElementById("billingAddress4").value = tmpbiladdress[3];
    document.getElementById("billingPostcode").value = tmpbiladdress[4];
    document.getElementById("billingCountry").value = tmpbiladdress[5];

    document.getElementById("billingAddress1").disabled = false;
    document.getElementById("billingAddress2").disabled = false;
    document.getElementById("billingAddress3").disabled = false;
    document.getElementById("billingAddress4").disabled = false;
    document.getElementById("billingPostcode").disabled = false;
    document.getElementById("billingCountry").disabled = false;
  }

  validatePresent(document.forms.C3bform.billingCountry, 'info_billcountry'); 
  validatePresent(document.forms.C3bform.billingPostcode,'info_billpc'); 
  validatePresent(document.forms.C3bform.billingAddress4,'info_billadr4'); 
  validatePresent(document.forms.C3bform.billingAddress3,'info_billadr3'); 
  validatePresent(document.forms.C3bform.billingAddress1,'info_billadr1'); 

  return true;
};

function PhoneNumberIn(field)
{
  if (field.checked)
  {
    document.getElementById("cardNumber").value = "to be phoned in";
    document.getElementById("cardNumber").disabled = true;
    validatePresent(document.forms.C3bform.cardNumber,'info_cardnumber')
  }
  else
  {
    document.getElementById("cardNumber").value = "";
    document.getElementById("cardNumber").disabled = false;
    validateNumber(document.forms.C3bform.cardNumber,'info_cardnumber',true,16,'','')
  }

  return true;
};

function gameChanged(Obj,usedby)
{
  var tmpTxt = Obj.options[Obj.selectedIndex].text
  var tmpFieldList = new Array();
  var tmpIgnoreList = new Array();

  if (usedby == "search")
  {
    tmpFieldList[0] = "expansion";
    tmpIgnoreList[0] = 0;
    tmpFieldList[1] = "cardtype";
    tmpIgnoreList[1] = 3;
    tmpFieldList[2] = "faction";
    tmpIgnoreList[2] = 3;
    tmpFieldList[3] = "rarity";
    tmpIgnoreList[3] = 0;
  }
  if (usedby == "buylists")
  {
    tmpFieldList[0] = "expansion";
    tmpIgnoreList[0] = 0;
  }

  for (var x=0; x<tmpFieldList.length; x++)
  {
    var tmpField = document.getElementById(tmpFieldList[x]);

    if (Obj.options[Obj.selectedIndex].value == -1)
    {
      Obj.options[0].selected=true;
      tmpField.options[0].selected=true;
    }
    else
    {
      var tmpIgnore = 1;

      // locate which game the field currently belongs to
      var tmpNewIndex = tmpField.selectedIndex;
      while (tmpField.options[tmpNewIndex].value != -1)
      {
        tmpNewIndex--
      }

      // check if we need to ignore Obj row
      if (tmpIgnoreList[x] == 3)
        tmpIgnore = (tmpField.selectedIndex != 2);

      // only change game if we need to
      if ((tmpIgnore) && (tmpField.options[tmpNewIndex].text != tmpTxt))
      {
        var tmpLen = tmpField.options.length;
        var tmpChangeMade = false;

        for (var countB=0; countB<tmpLen; countB++)
        {
          if (tmpField.options[countB].text == tmpTxt)
          {
            tmpField.options[countB].selected=true;
            tmpChangeMade = true;
            break;
          }
        }
        if (!tmpChangeMade)
        {
          // game doesnt exist, so set to any game
          tmpField.options[0].selected=true;
        }
      }
    }
  }
  if (usedby == "search")
  {
    searchSuggest(document.getElementById('game').value);
  }
  return;
}

function findGame(Obj,usedby,ignoreXrows)
{
  // locate which game Obj belongs to
  var tmpNewIndex = Obj.selectedIndex;
  while (Obj.options[tmpNewIndex].value != -1)
  {
    tmpNewIndex--
  }

  var tmpGameLen = document.getElementById("game").options.length;
  var tmpIgnore = 1;

  // check if we need to ignore Obj row
  if (ignoreXrows == 2)
    tmpIgnore = ((Obj.selectedIndex != 0) && (Obj.selectedIndex != 1));
  if (ignoreXrows == 3)
    tmpIgnore = ((Obj.selectedIndex != 0) && (Obj.selectedIndex != 1) && (Obj.selectedIndex != 2));

  // reposition game if we're not ignoring the row selected
  if (tmpIgnore)
  {
    for (var count=tmpGameLen-1; count>=0; count--)
    {
      if (document.getElementById("game").options[count].text == Obj.options[tmpNewIndex].text)
      {
        document.getElementById("game").options[count].selected=true;
        gameChanged(document.getElementById("game"),usedby);
        break;
      }
    }
  }

  return;
}

function clearSearch(FormType)
{
  if ((FormType == "full") || (FormType == "part"))
  {
    document.getElementById("expansion").options[0].selected=true;
    document.getElementById("title").value="";
    document.getElementById("subtitle").value="";
    document.getElementById("number").value="";
    document.getElementById("cardtype").options[0].selected=true;
    document.getElementById("faction").options[0].selected=true;
    document.getElementById("rarity").options[0].selected=true;
    document.getElementById("condition").options[0].selected=true;
    document.getElementById("artist").value="";
    document.getElementById("printedin").options[0].selected=true;
    document.getElementById("instock0").checked=true;
    document.getElementById("priceoperator").options[3].selected=true;
    document.getElementById("price").value="0.00";
    document.getElementById("sortby").options[1].selected=true;
    document.getElementById("sortorder").options[0].selected=true;
  }
  if (FormType == "full")
  {
    // if the game was previously selected, these two dont appear on the search form
    document.getElementById("game").options[0].selected=true;
    document.getElementById("manufacturer").options[0].selected=true;
  }
}

// ----------------------------------------------------------------
// AJAX search suggestions
// Original Author: Ryan Smith
// Website: http://www.dynamicajax.com/fr/AJAX_Suggest_Tutorial-271_290_312.html
//
// Modifications: James Hoskin 2009
// Comments removed to save space. See full version at above link
// ----------------------------------------------------------------

var passedurl = '';
var iscompatible = true;
var searchReq = getXmlHttpRequestObject();

function getXmlHttpRequestObject()
{
  var obj;

  try
  {
    // Firefox, Opera 8.0+, Safari
    obj=new XMLHttpRequest();
  }
  catch (e)
  {
    try
    {
      // Internet Explorer 6.0+
      obj=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        // Internet Explorer 5.5+
        obj=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        iscompatible = false;
        //alert("Unfortunately, search suggestions are\nincompatible with your browser.");
      }
    }
  }

  return obj;
}

function searchSuggest(gameID)
{
  if ((iscompatible) && (searchReq.readyState == 4 || searchReq.readyState == 0))
  {
    var str = escape(document.getElementById('title').value);
    if ((gameID=="") || (gameID==-1))
    {
      gameID = escape(document.getElementById('game').value);
    }
    searchReq.open("GET", passedurl+'/offer_suggestions.php?title='+str+'&gameID='+gameID, true);
    searchReq.onreadystatechange = handleSearchSuggest; 
    searchReq.send(null);
  }		
}

function handleSearchSuggest()
{
  if ((searchReq.readyState == 4) && (searchReq.status == 200))
  {
    var ss = document.getElementById('search_suggest')
    ss.style.display = 'block';
    ss.innerHTML = '';
    var str = searchReq.responseText.split("\n");
    for(i=0; i < str.length - 1; i++)
    {
      if (str[i] != '')
      {
        if (i==0)
        {
          var suggest = '<img src="'+passedurl+'/images/cross-red.gif" title="close suggestions" ';
          suggest += 'alt="close suggestions button" onclick="javascript:closeSuggestion();" ';
          suggest += 'style="position:absolute;top:2px;right:2px;width:12;height:12;border:none;">';
          suggest += '<div class="suggestlink">'+str[i]+'</div>';
          ss.innerHTML += suggest;
        }
        else
        {
          var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
          suggest += 'onmouseout="javascript:suggestOut(this);" ';
          suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
          suggest += 'class="suggestlink">'+str[i]+'</div>';
          ss.innerHTML += suggest;
        }
      }
    }
    if (ss.innerHTML == '')
    {
      ss.style.display = 'none';
    }
  }
}

function closeSuggestion()
{
  document.getElementById('search_suggest').innerHTML = '';
  document.getElementById('search_suggest').style.display = 'none';
}

function suggestOver(div_value)
{
  div_value.className = 'suggestlink_over';
}

function suggestOut(div_value)
{
  div_value.className = 'suggestlink';
}

function setSearch(suggestion)
{
  suggestion = suggestion.replace(/<(?:.|\s)*?>/g,"");	// remove html tags
  document.getElementById('title').value = suggestion.replace(/\&amp;/g,"&");	// remove ampersand symbol
  closeSuggestion();
}

// ----------------------------------------------------------------
// Javascript form validation routines.
// Original Author: Stephen Poley
// Website: http://www.xs4all.nl/~sbpoley/webmatters/index.html
//
// Modifications: James Hoskin 2006-2007
// Comments removed to save space. See full version at above link
// ----------------------------------------------------------------

var nbsp = 160;
var node_text = 3;
var emptyString = /^\s*$/
var global_validfield;

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
};


function setFocusDelayed()
{
  global_validfield.focus();
}

function setfocus(validfield)
{
  global_validfield = validfield;
  setTimeout('setFocusDelayed()', 100);
}


function msg(field,msgtype,message)
{
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(field);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;
};

var proceed = 2;  

function commonCheck(validfield,infofield,required,notrequiredmsg)
{
  if (!document.getElementById) 
    return true;
  var elem = document.getElementById(infofield);
  if (!elem.firstChild)
    return true;
  if (elem.firstChild.nodeType != node_text)
    return true;

  if (emptyString.test(validfield.value))
  {
    if (required)
    {
      msg (infofield, "errormsg", "Required");  
      setfocus(validfield);
      return false;
    }
    else
    {
      msg (infofield, "warnmsg", notrequiredmsg);
      return true;  
    }
  }
  return proceed;
}

function validatePresent(validfield,infofield)
{
  var stat = commonCheck(validfield,infofield,true,'');
  if (stat != proceed) return stat;

  msg (infofield, "warnmsg", "");  
  return true;
};

function validateEmail(validfield,infofield,required)
{
  var stat = commonCheck(validfield,infofield,required,'');
  if (stat != proceed) return stat;

  var trimmedfield = trim(validfield.value);
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(trimmedfield))
  {
    msg (infofield, "errormsg", "ERROR: invalid e-mail address.");
    setfocus(validfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(trimmedfield)) 
    msg (infofield, "warnmsg", "WARNING: Unusual e-mail address. Please double check.");
  else
    msg (infofield, "warnmsg", "");
  return true;
};

function validateNumber(validfield,infofield,required,expectedlength,validmsg,notrequiredmsg)
{
  var stat = commonCheck(validfield,infofield,required,notrequiredmsg);
  if (stat != proceed) return stat;

  var trimmedfield = trim(validfield.value);
  var cardnumber = /^[0-9 ]*[0-9]$/
  if (!cardnumber.test(trimmedfield))
  {
    msg (infofield, "errormsg", "ERROR: invalid number. Characters permitted are digits and space.");
    setfocus(validfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<trimmedfield.length; j++)
    if (trimmedfield.charAt(j)>='0' && trimmedfield.charAt(j)<='9') numdigits++;

  if (numdigits < expectedlength)
  {
    if (required)
      msg (infofield, "errormsg", "ERROR: expecting "+expectedlength+" digits.");
    else
      msg (infofield, "warnmsg", "WARNING: expecting at least "+expectedlength+" digits - please double check.");
  }
  else
    msg (infofield, "warnmsg", validmsg);

  return true;
};

function validateSelect(validfield,infofield,required)
{
  var stat = commonCheck(validfield,infofield,true,'');
  if (stat != proceed) return stat;

  if ((validfield.value == "-1") && (required))
  {
    msg (infofield, "errormsg", "Required");  
    setfocus(validfield);
    return false;
  }
  else
  {
    msg (infofield, "warnmsg", "");
    return true;  
  }
  return true;
};

function validateCardExpiry(validfield,infofield)
{
  var stat = commonCheck(validfield,infofield,true,'');
  if (stat != proceed) return stat;

  if ((document.forms.C3bform.expiryMonth.value == "-1") && (document.forms.C3bform.expiryYear.value == "-1"))
  {
    msg (infofield, "errormsg", "Required");  
    setfocus(validfield);
    return false;
  }

  if ((document.forms.C3bform.expiryMonth.value == "-1") && (document.forms.C3bform.expiryYear.value != "-1"))
  {
    msg (infofield, "errormsg", "Expiry month required.");  
    setfocus(validfield);
    return false;
  }

  if ((document.forms.C3bform.expiryMonth.value != "-1") && (document.forms.C3bform.expiryYear.value == "-1"))
  {
    msg (infofield, "errormsg", "Expiry year required.");  
    setfocus(validfield);
    return false;
  }

  if ((document.forms.C3bform.expiryMonth.value != "-1") && (document.forms.C3bform.expiryYear.value != "-1"))
  {
    if ((document.forms.C3bform.expiryMonth.value < tmpthismonth) && (document.forms.C3bform.expiryYear.value == tmpthisyear))
    {
      msg (infofield, "errormsg", "ERROR: card already expired!");  
      setfocus(validfield);
      return false;
    }
    else
    {
      msg (infofield, "warnmsg", "");
      return true;  
    }
  }
  return true;
};

function validateCardValid(validfield,infofield)
{
  var stat = commonCheck(validfield,infofield,true,'');
  if (stat != proceed) return stat;

  if ((document.forms.C3bform.validMonth.value == "-1") && (document.forms.C3bform.validYear.value == "-1"))
  {
    msg (infofield, "warnmsg", "if available");
    return true;  
  }

  if ((document.forms.C3bform.validMonth.value == "-1") && (document.forms.C3bform.validYear.value != "-1"))
  {
    msg (infofield, "errormsg", "ERROR: invalid month.");  
    setfocus(validfield);
    return false;
  }

  if ((document.forms.C3bform.validMonth.value != "-1") && (document.forms.C3bform.validYear.value == "-1"))
  {
    msg (infofield, "errormsg", "ERROR: invalid year.");  
    setfocus(validfield);
    return false;
  }

  if ((document.forms.C3bform.validYear.value > tmpthisyear) || ((document.forms.C3bform.validYear.value == tmpthisyear) && (document.forms.C3bform.validMonth.value > tmpthismonth)))
  {
    msg (infofield, "errormsg", "ERROR: card not valid yet!");  
    setfocus(validfield);
    return false;
  }

  msg (infofield, "warnmsg", "");
  return true;  
};

// ---------------------------
// End of form validation code
// ---------------------------

