function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++;
        }
    }
}

//change the opacity for different browsers 
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    if(opacity > 0) {
      object.visibility = "visible";
      object.opacity = (opacity / 100);
      object.MozOpacity = (opacity / 100);
      object.KhtmlOpacity = (opacity / 100);
      object.filter = "alpha(opacity=" + opacity + ")";
    } else {
      object.visibility = "hidden";
    }
}

/*** Functions to manage jQuery date selectors ***/

//Get the x/y position of a DOM element
function getXYpos(elem) {
   if (!elem) {
      return {"x":0,"y":0};
   }
   var xy={"x":elem.offsetLeft,"y":elem.offsetTop}
   var par=getXYpos(elem.offsetParent);
   for (var key in par) {
      xy[key]+=par[key];
   }
   return xy;
}

var currentCalendarDate;

function showCalendar(fieldId,posTop,posLeft) {
  currentCalendarDate = document.getElementById(fieldId);
  var coords = getXYpos(currentCalendarDate);
  //alert("X: " + coords["x"] + ", Y: " + coords["y"]);
  var dateParts = currentCalendarDate.value.split("/");
  var usDate = new Date();
  if(dateParts.length == 3)
    usDate = new Date(dateParts[1] + "/" + dateParts[0] + "/" + dateParts[2]);
  $('#calendar').datepicker('setDate',usDate);
  var cal = document.getElementById("calendar");
  cal.style.top = coords["y"] - 50;
  cal.style.left = coords["x"] - 50;
  cal.style.display = "block";
}

function calendarDateSelected(newDate) {
  currentCalendarDate.value = newDate;
  document.getElementById("calendar").style.display = "none";
}

/*** Validate the input of a new or edited listing ***/

function validateListing(listingForm) {
  var errorMessages = Array();
  var showFromCompleted = false;
  var showUntilCompleted = false;
  //Check all the compulsory fields have a value
  for(var c = 0; c < listingForm.elements.length; c++) {
    var thisElement = listingForm.elements[c];
    if(thisElement.name == "listingType" &&
       thisElement.value.length == 0)
      errorMessages.push("You must select a listing type");
    if(thisElement.name == "listingTitle" &&
       thisElement.value.length == 0)
      errorMessages.push("You must enter a title for the listing");
    /*if(thisElement.name == "listingText" &&
       $('#listingText').attr('html').length == 0)
      errorMessages.push("You must enter some text for the listing");*/
    if(thisElement.name == "listingShowFrom" &&
       thisElement.value.length == 0) {
      errorMessages.push("You must select a show from date for the listing");
    } else {
      showFromCompleted = true;
    }
    if(thisElement.name == "listingShowUntil" &&
       thisElement.value.length == 0) {
      errorMessages.push("You must select a show until date for the listing");
    } else {
      showUntilCompleted = true;
    }
    if(thisElement.name == "listingEventDate" &&
       document.getElementById("listingIsSubscribable").checked &&
       thisElement.value.length == 0) {
      errorMessages.push("You must enter an event date if customers can sign up");
    }
    if(thisElement.name == "listingCost" &&
       document.getElementById("listingIsSubscribable").checked &&
       thisElement.value.length == 0) {
      errorMessages.push("You must enter a cost if customers can sign up");
    }
  }
  //Check the show until date is after the show from date
  if(showFromCompleted && showUntilCompleted) {
   //TODO: make sure dates are ok
  }
  if(errorMessages.length > 0) {
    var errorMessage = "Your listing could not be saved because of the following problems:\n\n";
    errorMessage += errorMessages.join("\n");
    alert(errorMessage);
    return false;
  } else {
    return true;
  }
}

function menuButton_mouseover(element) {
  element.style.fontWeight = 'bold';
  element.style.cursor = 'pointer';
  element.style.cursor = 'hand';
}

function menuButton_mouseout(element) {
  element.style.fontWeight = 'normal';
  element.style.cursor = 'auto';
}

function refreshOpener(page,querystring) {
  if (!(window.focus && window.opener))
    return true;
  window.opener.focus();
  window.opener.location = page + '?' + querystring;
  window.close();
  return false;
}

function listingIsSubscribable_checked() {
  var checkVal = document.getElementById("listingIsSubscribable").checked;
  document.getElementById("listingEventDate").disabled = !checkVal;
  document.getElementById("listingEventTime").disabled = !checkVal;
  document.getElementById("listingCost").disabled = !checkVal;
  document.getElementById("listingCapacity").disabled = !checkVal;
  document.getElementById("listingExtraQuestions").disabled = !checkVal;
  document.getElementById("listingBookingFee").disabled = !checkVal;
}

function comparePasswords() {
  var origPwd = document.getElementById("customerPassword");
  var repPwd = document.getElementById("customerPasswordRepeat");
  var pwdMsg = document.getElementById("passwordMessage");
  if(origPwd.value == repPwd.value) {
    if(origPwd.value.length > 0) {
      //Passwords match and meet standards
      if(origPwd.value.length >= 8 &&
         origPwd.value.find(/[a-z][A-Z]/) &&
         origPwd.value.find(/[0-9]/)) {
        return true;
      } else {
        pwdMsg.innerHTML = "Password must be at least 8 characters long, and contain at least one letter and one number";
        return false;
      }
    } else {
      pwdMsg.innerHTML = "Passwords are blank";
      return false;
    }
  } else {
    //Passwords do not match
    pwdMsg.innerHTML = "Passwords do not match";
    return false;
  }
}

function errorAlert(msg) {
  var errorMsg = "An error has occurred:\n\n";
  errorMsg += msg;
  alert(errorMsg);
}

function termsAndConditionsToggle() {
  var termsCheckbox = document.getElementById("termsAndConditionsConfirm");
  document.getElementById("confirmButton").disabled = !termsCheckbox.checked;
  if(termsCheckbox.checked)
    document.getElementById("termsWarning").innerHTML = "&nbsp;";
  else
    document.getElementById("termsWarning").innerHTML = 'You must agree to the <a href="termsAndConditions.html" target="_blank">terms and conditions</a>.';
}

function incrementQuantity(placesLeft) {
  var quantityField = document.getElementById("quantity");
  if(quantityField.value.match(/[0-9.]/)) {
    if(quantityField.value < placesLeft)
      quantityField.value++;
  } else {
    quantityField.value = 1;
  }
  calculateTotalCost();
}

function decrementQuantity() {
  var quantityField = document.getElementById("quantity");
  if(quantityField.value.match(/[0-9.]/) && quantityField.value > 1) {
    quantityField.value--;
  } else {
    quantityField.value = 1;
  }
  calculateTotalCost();
}

function calculateTotalCost() {
  var unitCost = document.getElementById("listingCostValue").innerHTML;
  var totalCostField = document.getElementById("totalCost");
  var quantityField = document.getElementById("quantity");
  if(!isNaN(unitCost)) {
    var costVal = parseFloat(unitCost) * quantityField.value;
    totalCostField.innerHTML = costVal.toFixed(2);
  } else {
    totalCostField.innerHTML = "Unknown";
  }
}

function textAreaMaxLength(field,maxChars) {
  return(field.value.length < maxChars ||
         (window.event.keyCode == 8 ||
	  window.event.keyCode == 46 ||
	  (window.event.keyCode >= 37 &&
           window.event.keyCode <= 40)));
}

function checkTextAreaMaxLength(field,maxChars) {
  if(field.value.length > maxChars) {
    alert("Field can hold a maximum of " + maxChars + " characters");
    field.value = field.value.substring(0,maxChars);
  }
}

function colorToHex(color) {
  if (color.substr(0, 1) === '#') {
      return color;
  }

  var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

  var red = parseInt(digits[2]);
  var green = parseInt(digits[3]);
  var blue = parseInt(digits[4]);

  var rgb = blue | (green << 8) | (red << 16);
  return digits[1] + '#' + rgb.toString(16);
};

function blink(idname) {
  var speed = 300;
  s = document.getElementById(idname);
  if (typeof(s) !== 'undefined')  {
    //alert(s.style.color);
    s.style.color = (colorToHex(s.style.color) == '#de1d7b') ? '#18a5e9' : '#de1d7b';
  }
  setTimeout("blink(\""+ idname + "\")",speed);
}

//Admin user has changed the data type of a new question
function newDataTypeSelectBoxChanged(selBox) {
  //Switch on/off lookup values box depending on data type
  //Value list for checkboxes, radio buttons and select box
  var valueListBox = document.getElementById("newValueList");
  var isCompulsoryCheckBox = document.getElementById("newIsCompulsory");
  if(selBox.value == "SELECT" ||
     selBox.value == "CHECKBOX" ||
     selBox.value == "RADIO") {
    valueListBox.disabled = false;
  } else {
    valueListBox.disabled = true;
  }
  if(selBox.value == "CHECKBOX") {
    isCompulsoryCheckBox.disabled = true;
  } else {
    isCompulsoryCheckBox.disabled = false;
  }
}

//Check both phone numbers are filled out
//on the customer registration screen
function checkPhoneNumber() {
  var phone1 = document.getElementById("newCustomerPhone1");
  var phone2 = document.getElementById("newCustomerPhone2");
  return(phone1.value.length > 0 && phone2.value.length > 0);
}

function setHomePageVisible(homePageId) {
  if(confirm("Are you sure you want to set this home page text to be visible?")) {
    document.getElementById("selectedVisibleRadio").value = homePageId;
    document.getElementById("existingHomePagesForm").submit();
  } else {
    return false;
  }
}
