var replacelist = {};
function setPrice(price)
{
  $('pn_price').innerHTML = price;
}

function registerReplaceID(id, type)
{
  replacelist[id] = {};
  replacelist[id]['default'] = '';
  replacelist[id]['type']    = type;
}

function replacePlaceholder()
{
  for(i in replacelist)
  {
    if('html' == replacelist[i]['type'])
    {
      if(replacelist[i]['default'].length == 0)
      {
        replacelist[i]['default'] = $(i).innerHTML;
      }
    }
    else
    {
      if(replacelist[i]['default'].length == 0)
      {
        replacelist[i]['default'] = $(i).value;
      }
    }
    replacestr = replacelist[i]['default'];
    var prepend = '';
    var append   = '';
    switch(replacelist[i]['type'])
  {
    case 'html':
        prepend  = '<span class="pn_replace">';
    append   = '</span>';
    break;
  }
  for(f in field)
  {
    test = replacestr.split('[' + f + ']');
    for(p = 0, pp = test.length; p < pp; p++)
    {
      replacestr = replacestr.replace('[' + f + ']', prepend + $F(f) +  append);
    }
  }
    if('html' == replacelist[i]['type'])
  {
    $(i).innerHTML = replacestr;
  }
  else
  {
      $(i).value = replacestr;
  }
  }
}
function setFieldStyle(id)
{
  if(field[id]['default'] != $F(id))
  {
    $(id).className = 'pn_field_pers';
  }
  else
  {
    $(id).className = 'pn_field';
  }
}
function setDeliveryTime(deliverytime)
{
  $('delivery').innerHTML = deliverytime;
}
function setDeliveryBox()
{
  var checktype = Array('edition', 'liebhaber', 'exquisit', 'juwel', 'seide', 'nabuka');
  var found     = false;
  //check which type is selected
  for(type in checktype)
  {
    if(checktype.hasOwnProperty(type) && null != $(checktype[type]))
    {
      if($(checktype[type]).checked)
      {
        if(document.getElementById(checktype[type] + '_delivery'))
        {
          Element.show(checktype[type] + '_delivery');
          Element.show(checktype[type] + '_delivery2');
          found = true;
        }
      }
      else
      {
        if(document.getElementById(checktype[type] + '_delivery'))
        {
          Element.hide(checktype[type] + '_delivery');
          Element.hide(checktype[type] + '_delivery2');
        }
      }
    }
  }
  if(!found)
  {
    if(document.getElementById('edition_delivery'))
    {
      Element.show('edition_delivery');
      Element.show('edition_delivery2');
      found = true;
    }
  }
}
function setDeliveryBoxText()
{
  var checktype     = Array('edition', 'liebhaber', 'exquisit', 'juwel', 'seide', 'nabuka');
  var typetext          = new Object();
  typetext['edition']   = '- Taschenbuch \'Edition\'';
  typetext['liebhaber'] = '- Hardcover \'Liebhaber\'';
  typetext['exquisit']  = '- Leinen \'Exquisit\'';
  typetext['juwel']     = '- Leder \'Juwel\'';
  typetext['juwel']     = '- Seide';
  typetext['juwel']     = '- Nabuka';
  var prependtext     = 'Folgende Einbände sind noch garantiert lieferbar: ';
  var appendtext       = '';
  var additionaltext   = '';
  for(type in checktype)
  {
    if(checktype.hasOwnProperty(type))
  {
    if(document.getElementById(checktype[type] + '_delivery_ok'))
    {
      if($(checktype[type] + '_delivery_ok').value == 1)
      { //type delivery guaranteed
        additionaltext += '<br>' + typetext[checktype[type]];
      }
    }
    }
  }
  for(type in checktype)
  {
    if(checktype.hasOwnProperty(type))
  {
    if(document.getElementById(checktype[type] + '_delivery_ok'))
    {
      if($(checktype[type] + '_delivery_ok').value == 0)
      { //type delivery not guaranteed, add addiontonal text
        var finaltext = '<br><span class="pn_delivery_ok">' +  prependtext + additionaltext + appendtext + '</span>'
        if(additionaltext.length > 0)
        {
          $(checktype[type] + '_delivery_text').innerHTML  += finaltext;
          $(checktype[type] + '_delivery2_text').innerHTML += finaltext;
        }
      }
    }
    }
  }
}
function hasPersonChanged()
{
  var haschanged = false;
  for(f in field)
  {
    if(field[f]['default'] != $F(f))
    {
      haschanged = true;
    }
  }
  return haschanged;
}
function hasPersonBadChars()
{
  for(f in field)
  {
    if(hasNotAllowedChars($F(f)))
    {
      $(f).value = removeNotAllowedChars($F(f));
      $(f).focus();
      Element.show('box_1');
      setState('person', false);
      return true;
    }
  }
  return false;
}
function hasPersonEmptyFields()
{
  var hasemptyfield = false;
  for(f in field)
  {
    tmp = trim($F(f));
    if(tmp.length == 0)
  {
    hasemptyfield = true;
    $(f).focus();
  }
  }
  return hasemptyfield;
}
function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}
function changeHandler(obj,max,updateid,maxline,updateidline)
{
 MAX = max;
 lines = obj.value.split('\n');
 if(lines.length > maxline)
 {
   obj.value = '';
   var counter = 0;
   for(l in lines)
   {
     if(lines.hasOwnProperty(l))
   {
     if(counter < maxline)
     {
       if(0 != counter)
     {
          obj.value += '\n';
     }
       counter++;
       obj.value += lines[l];
     }
   }
   }
   lines = obj.value.split('\n');
   alert('Es sind maximal ' + maxline + ' Zeilen erlaubt');
 }
 if(obj.value.length>MAX)
 {
   obj.value = obj.value.slice(0,MAX);
   alert('Es sind maximal ' + max + ' Zeichen erlaubt');
 }
 document.getElementById(updateid).innerHTML = MAX-obj.value.length;
 document.getElementById(updateidline).innerHTML = maxline-lines.length;
}

function setInfo()
{
  var infotags = Array('edition_info', 'liebhaber_info', 'exquisit_info', 'juwel_info', 'seide_info', 'nabuka_info');
  for(i=0, ii = infotags.length; i<ii; i++)
  {
    var tag = infotags[i].replace('_info','');
    if(document.getElementById(tag))
    {
      if($(tag).checked == true)
      {
        Element.show(infotags[i]);
        $('final_delivery_date').value = $F(tag + '_distributor_date');
      }
      else
      {
        Element.hide(infotags[i]);
      }
    }
  }
}

function checkPerson(bDisplayMessage)
{
  if(hasPersonEmptyFields())
  {
    setState('person', false);
    return false;
  }
  else if(hasPersonChanged())
  {
    if(hasPersonBadChars())
    {
      if(bDisplayMessage)
      {
        alert('Nicht erlaubte Zeichen wurden entfernt.');
      }
      return false;
    }
    else
    {
      setState('person', true);
      return true;
    }
  }
  setState('person', false);
  return false;
}
function checkWidmung(bDisplayMessage)
{
  if($F('shop.cart[0][widmung]').length == 0)
  {
    setState('widmung', false);
  }
  else
  {
    if(hasNotAllowedChars($F('shop.cart[0][widmung]')))
    {
      if(bDisplayMessage)
      {
        alert('Nicht erlaubte Zeichen wurden entfernt.');
        Element.show('box_2');
        $('shop.cart[0][widmung]').focus();
      }
      $('shop.cart[0][widmung]').value = removeNotAllowedChars($F('shop.cart[0][widmung]'));
      setState('widmung', false);
      return false;
    }
    else
    {
      setState('widmung', true);
      return true;
    }
  }
}
function checkType()
{
  var checktype     = Array('edition', 'liebhaber', 'exquisit', 'juwel','seide','nabuka');
  var delivery      = Array('0', '2', '2', '4', '4', '4');
  var checkvariant  = Array('_variant_standard', '_variant_schrift', '_variant_bild');
  var colors        = Array('juwel_blau', 'juwel_rot', 'juwel_schwarz');
  var colorsseide   = Array('seide_rot', 'seide_purpur', 'seide_braun');
  var colorsnabuka  = Array('nabuka_rot', 'nabuka_braun', 'nabuka_rosa', 'nabuka_hellorange', 'nabuka_hellblau', 'nabuka_dunkelblau', 'nabuka_dunkelgruen', 'nabuka_hellbraun', 'nabuka_weiss');
  var choosen       = false;
  var choosentype   = '';
  var counter       = 0;
  setDeliveryBox();
  //check which type is selected
  for(type in checktype)
  {
    if(checktype.hasOwnProperty(type) && null != $(checktype[type]))
    {
      if($(checktype[type]).checked)
      {
        choosentype  = checktype[type];
        setDeliveryTime(parseInt(delivery[counter]) + parseInt(deliverydefault));
      }
      counter++;
    }
  }
  if(choosentype.length)
  { //a type is selected
    colorchoosen = false;
    if('juwel' == choosentype)
    {
      for(color in colors)
      {
        if(colors.hasOwnProperty(color))
        {
          if($(colors[color]).checked)
          {
            colorchoosen = true;
          }
        }
      }
    }
    else if('seide' == choosentype)
    {
      for(color in colorsseide)
      {
        if(colorsseide.hasOwnProperty(color))
        {
          if($(colorsseide[color]).checked)
          {
            colorchoosen = true;
          }
        }
      }
    }
    else if('nabuka' == choosentype)
    {
      for(color in colorsnabuka)
      {
        if(colorsnabuka.hasOwnProperty(color))
        {
          if($(colorsnabuka[color]).checked)
          {
            colorchoosen = true;
          }
        }
      }
    }
    else
    {
      colorchoosen = true;
    }
    for(variant in checkvariant)
    {
      if(checkvariant.hasOwnProperty(variant))
      {
        tmpvariant = choosentype + checkvariant[variant];
        if(document.getElementById(tmpvariant))
        { //element exists
          if($(tmpvariant).checked == true)
          {
            if(colorchoosen)
            {
              choosen = true;
            }
            else
            {
              choosen = false;
            }
          }
        }
      }
    }
  }
  setState('type', choosen);
  return choosen;
}
function checkFont()
{
  choosen = false;
  for(i=0; i<=4; i++)
  {
    if($('font_' + i).checked)
  {
    choosen = true;
  }
  }
  setState('font', choosen);
  return choosen;
}
function setState(type, value)
{
  switch(type)
  {
    case 'person':
      idok   = 'person_ok';
      idfail   = 'person_fail';
    break;
    case 'widmung':
      idok   = 'widmung_ok';
      idfail   = 'widmung_fail';
    break;
    case 'type':
      idok   = 'type_ok';
      idfail   = 'type_fail';
    break;
    case 'font':
      idok   = 'font_ok';
      idfail   = 'font_fail';
    break;
    case 'document':
      idok   = 'document_ok';
      idfail   = 'document_fail';
    break;
    default:
      return false;
    break;
  }
  if(value)
  {
    if(document.getElementById(idok))
    { //if ok exists, fail exists too
      Element.show(idok);
      Element.hide(idfail);
    }
  }
  else
  {
    if(document.getElementById(idok))
    { //if ok exists, fail exists too
      Element.hide(idok);
      Element.show(idfail);
    }
  }
}
function checkBookData()
{
  if(checkDocument() && checkFont() && checkType() && checkPerson(false) && checkWidmung(false))
  {
    return true;
  }
  else
  {
    Element.hide('box_1');
    Element.hide('box_2');
    Element.hide('box_3');
    Element.hide('box_4');
    if(document.getElementById('box_10'))
    {
       Element.hide('box_10');
    }
    if(!checkType())
    {
      alert('Bitte wählen Sie den Einband/Buchumschlag und Variante aus.');
      Element.show('box_3');
      return false;
    }
    if(!checkFont())
    {
      alert('Bitte wählen Sie eine Schrift aus.');
      Element.show('box_4');
      return false;
    }
    if(!checkDocument())
    {
      alert('Bitte wählen sie die Variante aus.');
      if(document.getElementById('box_10'))
      {
        Element.show('box_10');
      }
      return false;
    }
    if(!checkPerson(false))
    {
      if(hasPersonEmptyFields())
      {
        alert('Die Felder der Personen dürfen nicht leer sein. Bitte füllen Sie alle Felder aus.');
        Element.show('box_1');
        setState('person', false);
        hasPersonEmptyFields();
        return false;
      }
      if(hasPersonBadChars())
      {
        alert('Nicht erlaubte Zeichen wurden entfernt.');
        return false;
      }

      var answer = confirm('Wollen Sie wirklich keine Person personalisieren / ändern?\nMit "OK" bestellen Sie das Buch ohne eine Anpassung der Personen!');
      if(!answer)
      {
        Element.show('box_1');
        setState('person', false);
        return false
      }
      else
      {
        setState('person', true);
      }
    }
    if(!checkWidmung(false))
    {
      if(hasNotAllowedChars($F('shop.cart[0][widmung]')))
      {
        alert('Nicht erlaubte Zeichen wurden entfernt.');
        Element.show('box_2');
        $('shop.cart[0][widmung]').focus();
        $('shop.cart[0][widmung]').value = removeNotAllowedChars($F('shop.cart[0][widmung]'));
        setState('widmung', false);
        return false;
      }
      var answer = confirm('Wollen Sie wirklich keine Widmung angeben?\nMit "OK" bestellen Sie das Buch ohne Widmung!');
      if(!answer)
      {
        setState('widmung', false);
        Element.show('box_2');
        return false
      }
      else
      {
        setState('widmung', true);
      }
    }
  }
  return true;
}
function checkDocument()
{
  if(document.getElementById('box_10'))
  { //variant is displayed
    if(document.getElementById('document_0'))
    { //element exists, variant is present
    var documentchoosed = false;
    for(i=0; i<10; i++)
    {
      if(document.getElementById('document_' + i))
      {
      if($('document_' + i).checked == true)
      { //document has been choosen, stop check
        documentchoosed = true;
        break;
      }
      }
      else
      {
      break;
      }
    }
    setState('document', documentchoosed);
    return documentchoosed;
    }
    else
    {
    return true;
    }
  }
  else
  { //only one variant is present
    return true;
  }
}
function hasNotAllowedChars(sTestString)
{
  if(0 == sTestString.length)
  {
    return false;
  }
  var iAsciiCode = 0;
  for(i=0,ii=sTestString.length;i<ii;i++)
  {
    iAsciiCode = sTestString.charCodeAt(i);
    if(!(32 <= iAsciiCode && iAsciiCode <= 127 || 160 <= iAsciiCode && iAsciiCode <= 256))
    {//Character is not in the range of ascii 32-127 or 160-256
      return true;
    }
  }
  return false;
}
function removeNotAllowedChars(sTestString)
{
  var iAsciiCode = 0;
  var sCleanString = '';
  for(i=0,ii=sTestString.length;i<ii;i++)
  {
    iAsciiCode = sTestString.charCodeAt(i);
    if(32 <= iAsciiCode && iAsciiCode <= 127 || 160 <= iAsciiCode && iAsciiCode <= 256)
    {//Character is in the range of ascii 32-127 or 160-256
      sCleanString += sTestString.charAt(i);
    }
  }
  return sCleanString;
}
