function ajax_request(url)
{
  this.url = url;
  this.xhr = null;

  try {
    // Mozilla-family, Opera, Safari...
    this.xhr = new XMLHttpRequest();
  }
  catch(e) { // MS will always be a catch ;)    
    try {
      this.xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
      this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }

  this.fetch = function(target_id)
  {
    // Request completed.
    if (this.xhr.readyState == 4) {
      // Return file data
      if (this.xhr.status == 200) {
	// Get data put into innerHTML of given element having given target_id.
	//alert("target_id == "+ target_id);
	document.getElementById(target_id).innerHTML = this.xhr.responseText;
      }
      else {
	alert('Failed to get response :'+ this.xhr.statusText);
      }
    }
  }
  // Assign state handler.
  this.xhr.onreadystatechange=function(){this.fetch};
  // Open socket connection.
  this.xhr.open('GET', this.url, false);
  // Send request.
  this.xhr.send(null);
}

function fix_params(pid){
  var tmp_str = document.getElementById('cart_pchase_params_'+pid).value;
  tmp_str = tmp_str.replace('}','');
  tmp_str = tmp_str.replace('{','');
  document.getElementById('cart_pchase_params_'+pid).value = tmp_str;
}

function do_navigation(obj_selector){
  if(obj_selector.value!='0'){
    document.location.href = 'index.cgi?phase=selection&cid='+obj_selector.value;
  }
  else{
    return false;
  }
  return true;
}


/// Simply compute the amount of VAT from the prices given.
function vat(inc_vat, ex_vat)
{
  var vat = (inc_vat - ex_vat);
  document.write((vat.toFixed(2)).replace('.',','));
}

/// Compute the VAT percent from the prices given.
function vat_percent(inc_vat, ex_vat)
{
  var vp = Math.round(100*(inc_vat - ex_vat)/ex_vat);
  document.write(vp); 
}

// Reimplement using form field names or id's. 
function set_equal(formx)
{
  if (formx[12].checked) {
    formx[13].value = formx[7].value;
    formx[14].value = formx[8].value;
    formx[15].value = formx[9].value;
    formx[16].value = formx[10].value;
  }
  else {
    formx[13].value = "";
    formx[14].value = "";
    formx[15].value = "";
    formx[16].value = "";
  }
}

// Right trim string
function strrtrim(str) 
{
  return str.replace(/\s+$/,'');
}

function xreplace(checkMe,toberep,repwith){
  var temp = checkMe;
  var i = temp.indexOf(toberep);
  while(i > -1){
    temp = temp.replace(toberep, repwith);
    i = temp.indexOf(toberep, i + repwith.length + 1);
  }
  return temp;
}

function truncate(str, len)
{
  str = xreplace(str,'<br>',' ');
  str = xreplace(str,'<br />',' ');
  var str_tr = strrtrim(str);
  var full_len = str_tr.length;
  var r_pad = "";
  if (full_len > len) {
    r_pad = "...";
  }
  document.write(str_tr.substr(0, len) + r_pad);
}

function dot2comma(str)
{
  var rstr = str.replace(/\./, ",");
  document.write(rstr);
}
function avoid_empty(test, content)
{
  if (test != '') {
    document.write('<b>'+content+':</b> <span class="classvalues">'+test+'</span><br />');
  }
}
function avoid_empty_prod4cat(test)
{
  if (test != '') {
    document.write('<div class="mainheader">'+test+'</div>');
  }
}
function avoid_empty_plist(test, content)
{
  if (test != '') {
    document.write('<div class="unit"><br />'+content+':'+test+'</div>');
  }
}
function avoid_empty2(test, content)
{
  if (test != '') {
    document.write(content);
  }
}

function std_price(sale_price)
{
  document.write( ((sale_price / 0.85).toFixed(2)).replace('.',',') );
}

function plural(number, singular, plural)
{
  if (number > 1) {
    document.write(plural);
  }
  else {
    document.write(singular);
  }
}

function check_postalnumber(oObj){
  oObj.style.backgroundColor="#FFFFFF";
  var isnumerical = new Number(oObj.value);
  if(new String(isnumerical)=="NaN"){
    oObj.style.backgroundColor="#FF0000";
    alert('Du kan bare benytte deg av tall i felt merket med rødt');
    oObj.focus();
    return false;
  }
  if(oObj.value.length>5){
    oObj.style.backgroundColor="#FF0000";
    alert('Du har fylt inn for mange siffer i feltet merket med rødt');
    oObj.focus();
    return false;
  }
  if(oObj.value.length<4){
    oObj.style.backgroundColor="#FF0000";
    alert('Du har fylt inn for få siffer i feltet merket med rødt');
    oObj.focus();
    return false;
  }
}

function check_email(oObj){
  var str=oObj.value
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if (filter.test(str))
    return true;
  else{
    oObj.style.backgroundColor="#FF0000";
    alert('Vennligst fyll inn gyldig E-postadresse i feltet merket med rødt');
    oObj.focus();
    return false;
  }
}

function check_new_customer(){
  var firstname = document.getElementById("new_customer_firstname");
  var lastname = document.getElementById("new_customer_lastname");
  var email = document.getElementById("new_customer_email");
  
  firstname.style.backgroundColor="#FFFFFF";
  lastname.style.backgroundColor="#FFFFFF";
  document.getElementById("new_customer_email").style.backgroundColor="#FFFFFF";
  if(firstname.value==''){
    firstname.style.backgroundColor="#FF0000";
    alert("Vennligst fyll inn fornavn i felt merket med rødt");
    firstname.focus();
    return false;
  }
  else{
    firstname.value = first_char_to_upper(firstname.value);
  }
  if(lastname.value==''){
    lastname.style.backgroundColor="#FF0000";
    alert("Vennligst fyll inn etternavn i felt merket med rødt");
    lastname.focus();
    return false;
  }
  else{
    lastname.value = first_char_to_upper(lastname.value);
  }
  if(!check_email(email)){
    return false;
  }
  return true;
}
// function to convert the first character of a string to uppercase
// useful with names an places
function first_char_to_upper(objId){
  var oObj = document.getElementById(objId);
  var nameParts = oObj.value.split(" ");
  var strLength = '';
  var firstchar = '';
  var restOfChars = '';
  var returnString = '';
  var delimiter = '';
  for (var loop=0; loop < nameParts.length; loop++)
  {
    strLength = nameParts[loop].length;
    firstchar = nameParts[loop].substring(0, 1);
    restOfChars = nameParts[loop].substring(1, strLength);
    firstchar = firstchar.toUpperCase();
    if(returnString!=''){
      delimiter = ' ';
    }
    returnString = returnString + ' ' + firstchar + restOfChars;
  }
  strLength = returnString.length;
  if(returnString.substring(0,1)==' '){
    returnString = returnString.substring(1,strLength);
  }
  oObj.value = returnString;
}

//generic check of certain formfields
function check_form(){
var checkNotEmpty = ' customer_firstname,customer_lastname,customer_email,customer_address1,customer_postal_code,customer_post_location';
var checkPostalNumber = 'customer_postal_code';
var checkEmail = ' customer_email ';
var firstCharacterToUpper = ' customer_firstname,customer_lastname,customer_delivery_address1,customer_delivery_post_location,customer_company,customer_address1,customer_post_location,customer_address2';
//start of the generic solution
  for (var form_loop=0; form_loop<document.forms.length; form_loop++) 
  {
    for (var elems=0; elems<document.forms[form_loop].length;elems++)
    {
      if (document.forms[form_loop].elements[elems].name != "")
      {
        var current_object = document.forms[form_loop].elements[elems];
        current_object.style.backgroundColor="";
        //check what fields need to have their first character converted to uppercase and pass them on to the appropriate function
        if(firstCharacterToUpper.indexOf(current_object.id) !='-1' && firstCharacterToUpper.indexOf(current_object.id) !=''){
          if(current_object.value!=''){
            first_char_to_upper(current_object.id);
          }
        }
        //check required fields and make sure they're not empty
        if(checkNotEmpty.indexOf(current_object.id) !='-1' && checkNotEmpty.indexOf(current_object.id) !=''){
          if(current_object.value==''){
            current_object.style.backgroundColor="#FF0000";
            alert("Vennligst fyll inn felt merket med rødt");
            current_object.focus();
            return false;
          }
        }
        //check postal numbers and make sure they contain numbers only and that their length is correct
        if(checkPostalNumber.indexOf(current_object.id) !='-1' && checkNotEmpty.indexOf(current_object.id) !=''){
          var checkedPostalNumber = check_postalnumber(current_object);
          if(checkedPostalNumber==false){
            return false;
          }
        }
        //check email adresses and make sure they are in the correct format
        if(checkEmail.indexOf(current_object.id) !='-1' && checkEmail.indexOf(current_object.id) !=''){
          var checkedEmail = check_email(current_object);
          if(checkedEmail==false){
            return false;
          }
        }
      }
    }
  }
  return true;
}

function stock_and_status(qty,status){
  if(qty<1){
    if(status=='999'){
      document.getElementById('add2cart_submit').style.display='none';
      document.getElementById('add2cart_submit').disabled=true;
      document.getElementById('pchase_quantity').disabled=true;
      return '<p><b>Beklager, tomt på lager.</b></p>';
    }else{
      return '';
    }
  }else{
    return '';
  }
}

function disable_expired(pidd,qty,status){
  if(qty<1){
    if(status=='999' && document.getElementById(pidd)){
      document.getElementById(pidd).disabled=true;
      document.getElementById(pidd+' '+'1').disabled=true;
    }
  }
}

function check_add2cart(){
  var qty = document.getElementById('chk_qty').value;
  var time = document.getElementById('chk_time').value;
  var chkVal = document.getElementById('pchase_quantity').value;
  if(time=='999'){
    if(new Number(chkVal)>new Number(qty)){
      alert("Du kan dessverre bare kjøpe "+qty+" stk. av denne varen");
      document.getElementById('pchase_quantity').value = qty;
      return false;
    }
  }
  return true;
}

function check_bestillingsvare(status){
  if(status=='998'){
    return 'Bestillingsvare<br>';
  }else{
    return '';
  }
}
function return_linked_studio(studio_string){
  var studios=studio_string.split(",")
  var studio_output = '';
  var delimiter = '';
  var linked_studio = '';
  var studio = '';
  for (i=0; i<studios.length; i++){
    if(studio_output!=''){
      delimiter = ', ';
    }
    studio = studios[i].replace(/(^\s+)|\s+$/g,"");
    if(studio!=''){ //search_context=studio&search_str=Peter+Jackson&phase=selection
      linked_studio = "<a class=\"classvalues\" href=\"?search_context=studio&search_str="+studio+"&phase=selection\">"+studio+"</a>";
    }
    studio_output = studio_output + delimiter + linked_studio;
  }
  if(studio_output!=''){
    studio_output = "<b>Studio: </b>" + studio_output + "<br />";
  }
  return studio_output;
}

function return_linked_director(director_string){
  var directors=director_string.split(",")
  var director_output = '';
  var delimiter = '';
  var linked_director = '';
  var director = '';
  for (i=0; i<directors.length; i++){
    if(director_output!=''){
      delimiter = ', ';
    }
    director = directors[i].replace(/(^\s+)|\s+$/g,"");
    if(director!=''){ //search_context=director&search_str=Peter+Jackson&phase=selection
      linked_director = "<a class=\"classvalues\" href=\"?search_context=director&search_str="+director+"&phase=selection\">"+director+"</a>";
    }
    director_output = director_output + delimiter + linked_director;
  }
  if(director_output!=''){
    director_output = "<b>Regi: </b>" + director_output + "<br />";
  }
  return director_output;
}

function return_linked_actor(actor_string){
  var actors=actor_string.split(",")
  var actor_output = '';
  var delimiter = '';
  var linked_actor = '';
  var actor = '';
  for (i=0; i<actors.length; i++){
    if(actor_output!=''){
      delimiter = ' ';
    }
    actor = actors[i].replace(/(^\s+)|\s+$/g,"");
    if(actor!=''){//search_context=director&search_str=Peter+Jackson&phase=selection
      linked_actor = "<a class=\"classvalues\" href=\"?search_context=actor_list&search_str="+actor+"&phase=selection\">"+actor+"</a><br />";
    }
    actor_output = actor_output + delimiter + linked_actor;
  }
  if(actor_output!=''){
    actor_output = "<b>Skuespillere: </b><br />" + actor_output + "<br />";
  }
  return actor_output;
}
function swap_visibility(box, id1, id2)
{ 
  var elm1 = document.getElementById(id1);
  var elm2 = document.getElementById(id2);

  if (box.checked) {
    elm2.value = elm1.value;
    elm1.style.display = "none";
    elm2.style.display = "inline";
  }
  else {
    elm1.value = elm2.value;
    elm1.style.display = "inline";
    elm2.style.display = "none";
  }
}
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  var q_string = '';
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      var f_return =  pair[1];
    }else{
      if(q_string!=''){
        q_string = '?'+pair[0]+'='+pair[1];
      }
      else{
        q_string = q_string+'&amp;'+pair[0]+'='+pair[1];
      }
    }
  } 
  var r_str = query.replace('&alt_cart=y','');
  return f_return+','+r_str;
}
function check_confirm(){
  //  alert(document.getElementById('age_confirm').checked)
  if(document.getElementById('age_confirm').checked){
    return true;
  }
  else{
    alert('Du må krysse av boks for å verifisere at du er over 18, eller har tillatelse fra foresatte til å handle');
    return false;
  }
}
matchHeight=function(){
  var divs,contDivs,maxHeight,divHeight,d;
  // get all <div> elements in the document
  divs=document.getElementsByTagName('div');
  contDivs=[];
  // initialize maximum height value
  maxHeight=0;
  // iterate over all <div> elements in the document
  for(var i=0;i<divs.length;i++){
    // make collection with <div> elements with class attribute 'mainlists'
    if(/\mainlists\b/.test(divs[i].className)){
    d=divs[i];
    contDivs[contDivs.length]=d;
    // determine height for <div> element
      if(d.offsetHeight){
        divHeight=d.offsetHeight;
      }
      else if(d.style.pixelHeight){
        divHeight=d.style.pixelHeight;
      }
      // calculate maximum height
      maxHeight=Math.max(maxHeight,divHeight);
    }
  }
  // assign maximum height value to all of container <div> elements
  for(var i=0;i<contDivs.length;i++){
    contDivs[i].style.height=maxHeight;
  }
}
// execute function when page loads
window.onload=function(){
  if(document.getElementsByTagName){
    matchHeight();
  }
}
