var changed = false;
var validateError = '';
var completed = 0;

var INPUT_REGEX = new Array();
  INPUT_REGEX['articles_articlecontent_1228_e176'] = [/^.+$/, orderLang['choosehostel']]
  INPUT_REGEX['articles_articlecontent_1227_e189'] = [/^.+$/, orderLang['choosehostel']]
  INPUT_REGEX['articles_articlecontent_1228_e171'] = [/^.+$/, orderLang['startdate']]
  INPUT_REGEX['articles_articlecontent_1227_e193'] = [/^.+$/, orderLang['startdate']]
  INPUT_REGEX['articles_articlecontent_1228_e172'] = [/^.+$/, orderLang['stopdate']]
  INPUT_REGEX['articles_articlecontent_1227_e194'] = [/^.+$/, orderLang['stopdate']]
  INPUT_REGEX['articles_articlecontent_1228_e177'] = [/^[0-9]{1,}$/, orderLang['persons'], 1]
  INPUT_REGEX['articles_articlecontent_1227_e190'] = [/^[0-9]{1,}$/, orderLang['persons'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e178'] = [/^.{2,}$/, orderLang['groupname'], 1]
  INPUT_REGEX['articles_articlecontent_1227_e191'] = [/^.{2,}$/, orderLang['firmname'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e179'] = [/^.+$/, orderLang['groupcat'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e181'] = [/^.+$/, orderLang['agegroup'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e182'] = [/^.+$/, orderLang['contactname'], 1]
  INPUT_REGEX['articles_articlecontent_1227_e199'] = [/^.+$/, orderLang['contactname'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e183'] = [/^\w(\.?[\w-])*@\w(\.?[\w-])*\.[a-z]{2,6}$/i, orderLang['email'], 1]
  INPUT_REGEX['articles_articlecontent_1227_e200'] = [/^\w(\.?[\w-])*@\w(\.?[\w-])*\.[a-z]{2,6}$/i, orderLang['email'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e184'] = [/^[0-9]{8,}$/, orderLang['phone'], 1]
  INPUT_REGEX['articles_articlecontent_1227_e201'] = [/^[0-9]{8,}$/, orderLang['phone'], 1]
  INPUT_REGEX['articles_articlecontent_1228_e185'] = [/^.+$/, orderLang['country'], 1]
  INPUT_REGEX['articles_articlecontent_1227_e202'] = [/^.+$/, orderLang['country'], 1]

function validateBooking(fID, fName, fValue) {
  if( INPUT_REGEX[fName] && !fValue.match(INPUT_REGEX[fName][0]) ) {
    $(fID).addClassName('error');
    validateError += INPUT_REGEX[fName][1] + '\n';
    return false;
  } else if( INPUT_REGEX[fName] && INPUT_REGEX[fName][2] ) {
    $(fID).removeClassName('error');
    return true;
  } else {
    return true;
  }
}

function nextForm(formObj) {
  if( !changed ) { document.location='?template=experimental'; return false; }
  if( changed && confirm('Alt du har endret vil forsvinne.\nVil du fortsette uten \u00E5 lagre?') ) { 
    document.location='?template=experimental';
  } else {
    return false;
  }
}

function saveForm(formObj, next, submit) {
  f = formObj;
  ee = f.getElements();
  rc = eval(readCookie(f.id))
  if( $(f.id + 'e176') ) {
    n = $(f.id + 'e176') }
  else {
    n = $(f.id + 'e189');
  }
  v = n.options[n.options.selectedIndex].value;
  d = ''+ new Date().getTime(); 
  t = d.substr(d.length-8);
  
  /* Updating/Making cookie with form information */
  
  c = '[';
  for( i=0; i<ee.length; i++ ) {
    e = ee[i];
    if( validateBooking(e.id, e.name, e.value) ) {
      if( e.tagName=='SELECT' ) {
        c += "['"+e.name+"','"+e.options[e.options.selectedIndex].value+"']";
        c += ( i==(ee.length) ? '' : ',');
      } else if( e.name && e.type!='submit' && ( ( e.value && e.tagName=='TEXTAREA' ) || ( e.value && e.tagName=='INPUT' && e.type!='checkbox' ) || ( e.type=='checkbox' && e.checked==true ) ) ) {
        ta = e.value.replace(/(\x0a\x0d|\x0d\x0a)/g, '\n');
        ta = ta.replace(/(\n)/g, '<br/>')
        c += "['"+e.name+"','"+ta+"']";
        c += ( i==(ee.length) ? '' : ',');
      }
    }
  }
  if( validateError ) {
    alert(validateError);
    validateError = '';
    return false;
  }
  
  c += ']';

  formId = ( currentFID ? currentFID : t );

  createCookie(formId, c, 1);
  
  /* E N D */
  
  /* Updating cookie with form information */
  
  updatedCookie = '[';

  if( rc ) {
    for( i=0; i<rc.length; i++ ) {
      if( !rc[i] ) continue;
      r = rc[i];
      if( r[0]!=currentFID ) {
        updatedCookie += "['" + r[0] + "', '" + r[1] + "'],";
      }
    }
  }
  if( currentFID ) {
    updatedCookie += "['" + currentFID + "', '" + v + "']";
  } else {
    currentFID = t;
    updatedCookie += "['" + t + "', '" + v + "']";
  }

  updatedCookie += ']';
  
  createCookie(f.id, updatedCookie, 1); 
  
  /* E N D */
  
  printMenu(f);
  changed = false;
  //alert(orderLang['updated']);
  if(submit) return submitForms(formObj);
  if(next) return nextForm(formObj);
  return false;
}

function deleteForms(formObj, verbose) {
  f = formObj.id;
  aa = eval(readCookie(f));
  
  if( !readCookie(f) ) return false;
  if( !verbose && !confirm('Er du sikker p\u00E5 at du vil slette alle '+ aa.length +' foresp\u00F8rsler?') ) return false;

  for( i=0; i<aa.length; i++) {
    eraseCookie(aa[i][0]);
  }
  eraseCookie(f);
  
  printMenu(formObj, true); 
  f.reset();
  alert('Alle '+ aa.length +' foresp\u00F8rsler ble slettet');
}

function submitForms(formObj) {
  f = formObj.id;
  if( !readCookie(f) || changed ) {
    saveForm(formObj, false, true);
  } else {
    allBookings = eval(readCookie(f));
    timestamp = ''+ new Date().getTime();

    //if( !confirm(orderLang['confirminquiries']) ) return false;
    for( i=0; i<allBookings.length; i++) {
      result = '';
      booking = eval(readCookie(allBookings[i][0]));
      for( d=0; d<booking.length; d++) {
        if( !booking[d] ) continue;
        inputs = booking[d];
        fName = inputs[0];
        fValue = ( fName=='articles_articlecontent_1228_e250' || fName=='articles_articlecontent_1227_e251' ? timestamp : inputs[1]);
          
        result += fName + '=' + fValue;
        if( o=a.length ) result += '&';
      }
      
      new Ajax.Request('./', {
        method: 'post',
        parameters: result
      });
    }


    //eraseCookie(f);
    Ajax.Responders.register({
      count: 0,
      onCreate: function() {
        var count = Ajax.activeRequestCount++;
      },

      onComplete: function() {
        var count =  Ajax.activeRequestCount--;
        if( ( count == 0 || count==1 ) && completed == 0 ) {
          //alert('Alle '+ allBookings.length +' foresp\u00F8rsler ble sendt.\nVelkommen igjen.');
          completedBooking(formObj);
          completed = 1;
          deleteForms(formObj, true);
        }
      }
    });
  }
}

function completedBooking(formObj) {
  var div = document.createElement('DIV');
  div.id = 'completedBooking';
  div.innerHTML='<h1>Takk for din bookingforesp\u00F8rsel.</h1><h3>Vi vil gi deg svar innen 2 virkedager. Hvis dere har sp\u00F8rsm\u00E5l vennligst kontakt Norske Vandrerhjem p\u00E5 telefon 23 12 45 10 eller p\u00E5 e-post til <a href="mailto:groups@hihostels.no">groups@hihostels.no</a>.</h3>';
  formObj.innerHTML='';
  formObj.appendChild(div);
  if( completed == 0 ) {
  if(formObj.id == 'articles_articlecontent_1227_') {
    var analyticsUrl = urlroot + '?module=Articles;action=ArticleFolder.publicOpenFolder;ID=5782';
  } else {
    var analyticsUrl = urlroot + '?module=Articles;action=ArticleFolder.publicOpenFolder;ID=5781';
  }
  window.location = analyticsUrl;
  //console.log('test');
  }  
}

function deleteForm(formObj) {
  f = formObj.id;
  aa = eval(readCookie(f));
  
  if( !readCookie(f) ) return false;
  if( !confirm('Er du sikker p\u00E5 at du vil slette denne foresp\u00F8rselen?') ) return false;

  /* Updating cookie with form information */
  
  updatedCookie = '[';
  for( i=0; i<aa.length; i++) {
    a = aa[i];
    if( a[0]==currentFID ) {
      eraseCookie(a[0]);
    } else {
      updatedCookie += "['" + a[0] + "', '" + a[1] + "']";

        updatedCookie += ',';

        lastForm = a[0];

    }
  }
  if( aa.length==1 ) lastForm = false;
  updatedCookie += ']';

  createCookie(f, updatedCookie, 1);
  
  /* E N D */
  
  printMenu(formObj, true);
  if( lastForm ) {
    document.location='?template=experimental;fid=' + lastForm;
  } else {
    formObj.reset();
  }
}

function printMenu(formObj, del) {
  f = formObj;
  if( del ) { $('menuContainer').innerHTML=''; return true; }
  
  aa = eval(readCookie(f.id));
  if( !aa ) return;
  menu = document.createElement('ul');

  for( i=0; i<aa.length; i++) {
    if( !aa[i] ) continue;
    a = aa[i];
    li = document.createElement('li');
    if( currentFID==a[0] ) {
      link = document.createElement('span');
      link.innerHTML=a[1];
    } else {
      link = document.createElement('a');
      link.href='?template=experimental;fid=' + a[0];
      link.innerHTML=a[1];
    }
    
    li.appendChild(link);
    menu.appendChild(li);
  }
  $('menuContainer').innerHTML='';
  $('menuContainer').appendChild(menu);
}

function doInput(formObj, cache) {
  f = formObj;
  aa = eval(readCookie(formObj.id));
  if( !aa ) return;
  for( i=0; i<aa.length; i++) {
    if( aa[i][0]==currentFID || ( !currentFID && cache==true && i==0 ) ) {
      a = eval(readCookie(aa[i][0]));
      for( d=0; d<a.length; d++) {
        if( !a[d] || !a[d][0] ) return;
        fName = a[d][0];
        fValue = a[d][1];
        
        if( fName=='articles_articlecontent_1228_e171' || fName=='articles_articlecontent_1227_e193' ) {
          $('hiddenStart').value=fValue;
        }
        if( fName=='articles_articlecontent_1228_e172' || fName=='articles_articlecontent_1227_e194' ) {
          $('hiddenEnd').value=fValue;
        }
        if( $(fName) ) {
          o = $(fName);
          if( o.tagName=='INPUT' && o.type!='checkbox' ) {
            o.value=fValue;
          }
          if( o.tagName=='SELECT' ) {
            for( p=0; p<o.options.length; p++ ) {
              if( o.options[p].value==fValue ) {
                o.options[p].selected=true;
              }
            }
          }
          if( o.tagName=='INPUT' && o.type=='checkbox' && fValue=='true' ) {
            o.checked=true;
          }
          if( o.tagName=='TEXTAREA' ) {
            o.value=fValue.replace('<br/>', '\n', 'g');
          }
        }
      }
    }
  }
}

function substringBefore(str, del) {
  s = str.split(del);
  return s[0];
}

function substringAfter(str, del) {
  s = str.split(del);
  return s[s.length-1];
}

/*
    COOKIE FUNCTIONS
*/

function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

function readCookie(name) {
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return "";
}
