/*
## View: Common
## Toggles the visibility of a element specified with id
*/
function toggleDisplay(elementId) {
  var element = document.getElementById(elementId);
  element.style.display = (element.style.display != 'none' ? 'none' : '');
}

/*
## View: Framework
## Ajax request of the basket in the framework.
*/
function getSimpleBasket(url, elementId) {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest;
  }
  catch (e) {
    try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {
      try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) { alert("Din nettleser st&#248;tter ikke AJAX\nYour browser does not support AJAX"); }
    }
  }
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status != 200 && xmlHttp.status != 0) alert("No response from AJAX("+xmlHttp.status+")");
      else {
        var responseText = xmlHttp.responseText;
        if (!responseText) return
        document.getElementById(elementId).innerHTML = responseText;
      }
    }
  };
  xmlHttp.open('GET', url);
  xmlHttp.send(null);
}

/*
## View: Shopping basket
## Removes all items from basket
*/
function removeAll(form) {
   removeItems(form, true);
   form.submit();
}

/*
## View: Shopping basket
## Removes checked items from basket
*/
function removeItems(form) {
   removeItems(form, false);
}

/*
## View: Shopping basket
## Common function to remove items from basket,
## used by removeItems() and removeAll()
*/
function removeItems(form, removeall) {
  var size = form.elements.length;
  for (i=0;i<size;i++) {
    var element = form.elements[i];
    if (element.name != '' && element.name.indexOf("deleteItem") > -1 && (element.checked || removeall)) {
      var id = element.name.substring(10);
      var amount = document.getElementById('quantity_' + id);
      amount.value = '0';
    }
  }
  return true;
}

/*
## View: Signin
*/

/*
## View: Register
## Validates the user form...
*/
function validateInput(element, regExp, checkEmail) {
  if (regExp != null && element.value != "") {
    var regExpObj = new RegExp(regExp);
    if (!regExpObj.test(element.value)) {
      showMessage(element, 'Brukernavn/e-post m&#229; inneholde @.');
    } else if (checkEmail == 'true') {
      var userNameCheckResponse = checkUserName(element);
    }
    else {
      hideMessage();
      // remove error class?
    }
  }
}

function validatePassword(element, regExp, checkEmail) {
  if (regExp != null && element.value != "") {
    var regExpObj = new RegExp(regExp);
    if (!regExpObj.test(element.value)) {
      showMessage(element, 'Passordet m&#229; best&#229; av minst 8 tegn og inneholde b&#229;de bokstaver og tall.');
    } 
    else {
      hideMessage();
      // remove error class?
    }
  }
}

/*
## View: Register
## Function for displaying a info bubble
*/
function showMessage(element, text) {
  var tip;
  if(!document.getElementById('messageBubble')) {
    tip = document.createElement('div');
    tip.id = 'messageBubble';
    document.body.appendChild(tip);
  } else {
    tip = document.getElementById('messageBubble');
  }
  tip.innerHTML = '<div class="content">' + text + '</div>';
  
  document.getElementById('messageBubble').style.display = 'block';
  //var positionTop = topPos(element) - ((tip.offsetHeight - element.offsetHeight) / 2);
  var positionTop = topPos(element);
  var positionLeft = leftPos(element) + element.offsetWidth + 8;
  if (positionLeft != 0) {
    tip.style.top = positionTop + 'px';
    tip.style.left = positionLeft + 'px';
  }
}

/*
## View: Register
## Hides message in register view.
*/
function hideMessage() {
  var element = document.getElementById('messageBubble');
  if (element) {
    element.style.display = 'none';
  }
}

/*
## View: Register
## Helper function for #showMessage
## Calculate the left position of an element
*/
function leftPos(target) {
  var left = 0;
  if (target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if (target.x) {
    left += target.x;
  }
  return left;
}

/*
## View: Register
## Helper function for #showMessage
## Calculate the top position of an element
*/
function topPos(target) {
  var top = 0;
  if (target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if (target.y) {
    top += target.y;
  }  
  return top;
}

/*
## View: Register
## Do a ajax request to checks if a username is available
*/
function checkUserName(element) {
  var url = './?module=Users&amp;action=Ajax.isUsernameAvailable&amp;username=' + element.value;
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest;
  }
  catch (e) {
    try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {
      try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) { alert("Din nettleser st&#248;tter ikke AJAX\nYour browser does not support AJAX"); }
    }
  }
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status != 200 && xmlHttp.status != 0) alert("No response from AJAX("+xmlHttp.status+")");
      else {
        var isUserNameAvailable = xmlHttp.responseText;
        if (isUserNameAvailable == 'false') {
          showMessage(element, 'Dette brukernavnet er ikke tilgjengelig, vennligst pr&#248;v p&#229; nytt');
        } else if (isUserNameAvailable == 'true') {
          hideMessage();
        }
      }
    }
  };
  xmlHttp.open('GET', url);
  xmlHttp.send(null);
}

/*
## View: Common
## ajax function, performs a url lookup and calls function specified in parameter
## TODO: Update description
*/
function ajax(url) {
  var response;
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest;
  }
  catch (e) {
    try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {
      try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) { alert("Your browser does not support AJAX"); }
    }
  }
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status != 200 && xmlHttp.status != 0) alert("No response from AJAX("+xmlHttp.status+")");
      else response = xmlHttp.responseText;
    }
  };
  xmlHttp.open('GET', url);
  xmlHttp.send(null);
  return response;
}

/*
## View: Register
## Live update of hidden username field
*/
function updateUserName() {
  var emailText = document.getElementById('email').value;
  var userNameEl = document.getElementById('userName');
  userNameEl.value = emailText;
}

/*
## View: Checkout
## Changes payment method, complete button and displays information
## about choosen payment method
*/
function changePaymentMethod(elementId, invoiceFee, text) {
  var completeButton = document.getElementById('completeButton');
  completeButton.value = text;
  hidePaymentInfoBoxes();
  var elementToDisplay = document.getElementById(elementId + 'Info');
  elementToDisplay.style.display = 'block';
  var feeEl = document.getElementById('fee');
  setHandlingFee(feeEl.value, invoiceFee);
  setDeliveryMethod(elementId);
  return true;
}

/*
## View: Checkout
## Hides payment info boxes that are visible
*/
function hidePaymentInfoBoxes() {
  var payCODInfoEl = document.getElementById('payCODInfo');
  payCODInfoEl.style.display = 'none';

  var payInvoiceInfoEl = document.getElementById('payInvoiceInfo');
  payInvoiceInfoEl.style.display = 'none';

  var payCreditInfoEl = document.getElementById('payCreditInfo');
  payCreditInfoEl.style.display = 'none';
}

/*
## View: Checkout
## Sets the correct delivery options depending
## on payment method
*/
function setDeliveryMethod(paymentEl) {
  var deliverPickupEl = document.getElementById('deliverPickup');
  var deliverCourierEl = document.getElementById('deliverCourier');
  if (paymentEl == 'payCOD') {
    var deliverServiceEl = document.getElementById('deliverService');
    deliverServiceEl.checked = true;
    deliverServiceEl.onclick();
    deliverPickupEl.disabled = true;
    deliverCourierEl.disabled = true;
  } else {
    deliverPickupEl.disabled = false;
    deliverCourierEl.disabled = false;
  }
}

/*
## View: Checkout
## Changes the type of delivery, this will also set the handling and invoice fee
*/
function changeDeliveryMethod(elementId, handlingFee, invoiceFee) {
  hideDeliveryInfoBoxes();
  var elementToDisplay = document.getElementById(elementId + 'Info');
  elementToDisplay.style.display = 'block';
  var payInvoiceEl = document.getElementById('payInvoice');
  if (payInvoiceEl.checked == false) {
    invoiceFee = 0;
  }
  setHandlingFee(handlingFee, invoiceFee);
  return true;
}

/*
## View: Checkout
## Hides delivery info boxes
*/
function hideDeliveryInfoBoxes() {
  var deliverServiceInfoEl = document.getElementById('deliverServiceInfo');
  deliverServiceInfoEl.style.display = 'none';

  var deliverCourierInfoEl = document.getElementById('deliverCourierInfo');
  deliverCourierInfoEl.style.display = 'none';

  var deliverPickupInfoEl = document.getElementById('deliverPickupInfo');
  deliverPickupInfoEl.style.display = 'none';
}


/*
## View: Checkout
## Sets the order handling and invoice fee on fee element and in order summary info box
*/
function setHandlingFee(handlingFee, invoiceFee) {
  handlingFee = handlingFee * 1;
  invoiceFee = invoiceFee * 1;
  var handlingFeeEl = document.getElementById('handlingFee');
  handlingFeeEl.value = handlingFee + invoiceFee;
  var feeEl = document.getElementById('fee');
  feeEl.value = handlingFee;
  var orderSummaryHandlingFeeEl = document.getElementById('orderSummaryHandlingFee');
  if (handlingFee != 0) {
    handlingFee = handlingFee / 100;
  }
  orderSummaryHandlingFeeEl.innerHTML = formatAmount(handlingFee);
  var orderSummaryInvoiceFeeEl = document.getElementById('orderSummaryInvoiceFee');
  if (invoiceFee != 0) {
    invoiceFee = invoiceFee / 100;
  }
  orderSummaryInvoiceFeeEl.innerHTML = formatAmount(invoiceFee);
  updateTotalPrice(handlingFee + invoiceFee);
}

/*
## View: Checkout
## Updates the total price after a change of handling and/or invoice fee
*/
function updateTotalPrice(fee) {
  var orderSummaryGoodsEl = document.getElementById('orderSummaryGoods');
  var orderSummaryTotalEl = document.getElementById('orderSummaryTotal');
  if (fee <= 0) {
    fee = 0;
  }
  orderSummaryTotalEl.innerHTML = formatAmount(orderSummaryGoodsEl.innerHTML.replace('.','').replace(',', '.') * 1 + fee);
}

/*
## View: Checkout
## Formats the amount in order summary info box
*/
function formatAmount(nr){
  nr=''+nr;
  if (nr.indexOf(',') <= 0) {
    nr = nr+',00';
  }
  var nl=nr.length;
  for (var a=6;a<nl;a+=3) {
    nr=nr.substring(0,nl-a)+'.'+nr.substring(nl-a);
  }
  return nr;
}
