/* Global functions available in all pages */
var allOK;

function setupAJAX()
{
  // create a boolean variable to check for a valid Internet Explorer instance.
  var xmlhttp = false;
  // check if we are using IE.
  try
  {
    // if the Javascript version is greater than 5.
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    // you are using Microsoft Internet Explorer.
  }
  catch (e)
  {
    try
    {
      // if not, then use the older active x object.
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      // you are using Microsoft Internet Explorer.
    }
    catch (E)
    {
      // else we must be using a non-IE browser.
      xmlhttp = false;
    }
  }

  //if we are using a non-IE browser, create a javascript instance of the object.
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
  {
    xmlhttp = new XMLHttpRequest();
    // you are not using Microsoft Internet Explorer.
  }
  return xmlhttp;
}


function AJAXRequest(serverPage, objID, getOrPost, str)
{
  xmlhttp = setupAJAX();
  var obj = document.getElementById(objID); 

  showLoadingIndicator(obj);

  if (getOrPost == "get")
  {
    xmlhttp.open("GET", serverPage);
    xmlhttp.onreadystatechange = function()
    {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
      {
        obj.innerHTML = xmlhttp.responseText;
        hideLoadingIndicator();
      }
    }
    xmlhttp.send(null);
  }
  else
  {
    xmlhttp.open("POST", serverPage, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttp.onreadystatechange = function()
    {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
      {
        obj.innerHTML = xmlhttp.responseText;
        hideLoadingIndicator();
      }
    }
    xmlhttp.send(str);
  }
}


function submitForm(form, serverPage, objID, validationFunction)
{
  var str = getFormValues(form, validationFunction);

  // if the validation is ok.
  if (allOK == true)
  {
    AJAXRequest(serverPage, objID, 'post', str);
  }
}


function getFormValues(objForm, validationFunction)
{
  var str = '';
  allOK = true;
  var validated;

  // Run through a list of all objects contained in the form.
  for (var i = 0; i < objForm.elements.length; i++)
  {
    validated = validationFunction(objForm.elements[i].value, objForm.elements[i].name);
    if (validated == false)
    {
      allOK = false;
    }
    if (objForm.elements[i].type == 'radio')
    {
      if (objForm.elements[i].checked)
        strValue = escape(objForm.elements[i].value);
    }
    else if (objForm.elements[i].type == 'checkbox')
    {
      if (objForm.elements[i].checked)
        strValue = 'on'
      else
        strValue = 'off';
    }
    else
    {
      strValue = escape(objForm.elements[i].value);
    }
    str += objForm.elements[i].name + '=' + strValue + '&';
  }
  // return the string of values.
  return str;
}


// stop the enter key from working on all pages
function stopRKey(evt)
{
	var evt  = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text"))
	{
	  return false;
	}
}

//document.onkeypress = stopRKey;


function getPositionTop(obj)
{
    var top = 0;
    while(obj)
    {
        top += obj.offsetTop;
        obj = obj.offsetParent;
    }
    return top;    
}


function getPositionLeft(obj)
{
    var left = 0;
    while(obj)
    {
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    return left;    
}


function centerObjectTop(objectHeight)
{
  var availHeight;
  var yOffset;

  if (typeof(window.innerWidth) == 'number')
    availHeight = window.innerHeight;
  else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    availHeight = document.documentElement.clientHeight;
  else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    availHeight = document.body.clientHeight;

  if (self.pageYOffset)
  {
    // all except Explorer
    yOffset = self.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop)
  {
    // Explorer 6 Strict
    yOffset = document.documentElement.scrollTop;
  }
  else if (document.body)
  {
    // all other Explorers
    yOffset = document.body.scrollTop;
  }

  var top = ((availHeight / 2) + yOffset) - (objectHeight / 2);
  return top;
}


function centerObjectLeft(objectWidth)
{
  var availWidth;

  if (typeof(window.innerWidth) == 'number')
    availWidth = window.innerWidth;
  else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    availWidth = document.documentElement.clientWidth;
  else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    availWidth = document.body.clientWidth;

  var left = (availWidth / 2) - (objectWidth / 2);
  return left;
}


function showLoadingIndicator(refreshObject)
{
  document.getElementById('divLoadingTransparentCover').style.display = 'block';
  var divIndicator = document.getElementById('divLoadingIndicator');

  divIndicator.style.top = centerObjectTop(100) + "px";
  divIndicator.style.left = centerObjectLeft(250) + "px";
  divIndicator.style.display = "block";
}


function hideLoadingIndicator()
{
  document.getElementById('divLoadingTransparentCover').style.display = 'none';
  document.getElementById('divLoadingIndicator').style.display = "none";
}


function showPopupForm(frmAjaxUrl, frmHeight, frmWidth)
{
  var divPopupFormOuter = document.getElementById('divPopupFormOuter');
  var divPopupFormInner = document.getElementById('divPopupFormInner');
  
  divPopupFormOuter.style.width = '100%';
  divPopupFormOuter.style.height = '100%';
  divPopupFormOuter.style.top = 0 + 'px';
  divPopupFormOuter.style.left = 0 + 'px';
  divPopupFormOuter.style.display = "block";

  surroundHeight = frmHeight + 50;
  surroundWidth = frmWidth + 50;

  divPopupFormInner.style.width = surroundWidth;
  divPopupFormInner.style.height = surroundHeight;
  divPopupFormInner.style.top = centerObjectTop(surroundHeight) + "px";
  divPopupFormInner.style.left = centerObjectLeft(surroundWidth) + "px";
  divPopupFormInner.style.display = "block";

  AJAXRequest(frmAjaxUrl, 'divPopupFormInner', 'get', '');
}


function hidePopupForm()
{
  document.getElementById('divPopupFormOuter').innerHTML = "";
  document.getElementById('divPopupFormOuter').style.display = "none";
  document.getElementById('divPopupFormInner').innerHTML = "";
  document.getElementById('divPopupFormInner').style.display = "none";
}


function showZoomPhoto(imageUrl, imgWidth, imgHeight)
{
  var divZoomPhotoOuter = document.getElementById('divZoomPhotoOuter');
  var divZoomPhotoInner = document.getElementById('divZoomPhotoInner');

  divZoomPhotoOuter.style.width = '100%';
  divZoomPhotoOuter.style.height = '100%';
  divZoomPhotoOuter.style.top = 0 + 'px';
  divZoomPhotoOuter.style.left = 0 + 'px';
  divZoomPhotoOuter.style.display = "block";

  surroundHeight = imgHeight + 70;
  surroundWidth = imgWidth + 40;

  divZoomPhotoInner.style.width = surroundWidth;
  divZoomPhotoInner.style.height = surroundHeight;
  divZoomPhotoInner.style.top = centerObjectTop(surroundHeight) + "px";
  divZoomPhotoInner.style.left = centerObjectLeft(surroundWidth) + "px";
  divZoomPhotoInner.style.display = "block";

  divZoomPhotoInner.innerHTML = "<br>&nbsp;&nbsp;&nbsp;<img src='" + imageUrl + "' width=" + imgWidth + " height=" + imgHeight + ">&nbsp;&nbsp;&nbsp;<br><br><a class=Button href=\"javascript: hideZoomPhoto();\"><img src='/images/buttons/close.jpg'></a>";  
}

function hideZoomPhoto()
{
  document.getElementById('divZoomPhotoOuter').innerHTML = "";
  document.getElementById('divZoomPhotoOuter').style.display = "none";
  document.getElementById('divZoomPhotoInner').innerHTML = "";
  document.getElementById('divZoomPhotoInner').style.display = "none";
}


function isMandatoryFormFieldEntered(fieldName, labelName)
{
  if (!document.getElementById(fieldName).value.length > 0)
  {
    document.getElementById(labelName).style.color = 'red';
    return false;
  }
  else
  {
    document.getElementById(labelName).style.color = 'black';
    return true
  }
}


function isFormFieldNumeric(fieldName, labelName)
{
  if (!isNumeric(document.getElementById(fieldName).value))
  {
    document.getElementById(labelName).style.color = 'red';
    return false;
  }
  else
  {
    document.getElementById(labelName).style.color = 'black';
    return true
  }
}


function isNumeric(string)
{
  var validChars = "0123456789.-";
  var char;
  var result = true;
  var decimalFound = false;

  if (string.length == 0) return false;

  for (i = 0; i < string.length && result == true; i++)
  {
    char = string.charAt(i);
    if (validChars.indexOf(char) == -1 || (i > 0 && char == '-') || (char == '.' && decimalFound))
      result = false;
    if (char == '.')
      decimalFound = true;
  }
  return result;
}


function isValidEmail(str)
{
  var at="@"
  var dot="."
  var lat=str.indexOf(at)
  var lstr=str.length
  var ldot=str.indexOf(dot)

  if (str.indexOf(at)==-1)
    return false

  if (str.indexOf(at)==0 || str.indexOf(at)==lstr)
    return false

  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
    return false

  if (str.indexOf(at,(lat+1))!=-1)
    return false

  if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
    return false

  if (str.indexOf(dot,(lat+2))==-1)
    return false
		
  if (str.indexOf(" ")!=-1)
    return false

  return true					
}




// beta request
function openBetaRequestForm()
{
  showPopupForm('/ajax_frmBetaRequest.php', 560, 650);
}


function validateFrmBetaRequest()
{
  var allGood = true;

  if (!document.getElementById('txtFirstName').value.length > 0)
  {
    alert ('You must enter your first name');
    allGood = false;
  }
  if (!document.getElementById('txtLastName').value.length > 0)
  {
    alert ('You must enter your last name');
    allGood = false;
  }
  if (document.getElementById('txtPreferredUsername').value.length < 3 ||
      document.getElementById('txtPreferredUsername').value.length > 15)
  {
    alert ('You must enter your preferred username (between 3 and 15 characters)');
    allGood = false;
  }
  if (!document.getElementById('txtEmail').value.length > 0)
  {
    alert ('You must enter your email address');
    allGood = false;
  }
  if (!isValidEmail(document.getElementById('txtEmail').value))
  {
    alert ('You must enter a valid email address');
    allGood = false;
  }
  if (document.getElementById('txtEmailCheck').value != document.getElementById('txtEmail').value)
  {
    alert ('The two email addresses you entered do not match');
    allGood = false;
  }

  return allGood;
}


function submitBetaRequestForm()
{
  if (validateFrmBetaRequest())
  {
    alert('Your request has been submitted. You should receive an email shortly with details on how to set up your account and profile.');
    submitForm(document.getElementById('frmBetaRequest'), '/ajax_frmBetaRequest_process.php', 'divNothing', function() {return true;});
    hidePopupForm();
  }
}


function closeRequestBetaForm()
{
  hidePopupForm();
}



// beta invite
function openBetaInviteForm()
{
  showPopupForm('/ajax_frmBetaInvite.php', 340, 650);
}


function validateFrmBetaInvite()
{
  var allGood = true;

  if (!document.getElementById('txtInviteEmail').value.length > 0)
  {
    alert ('You must enter the email address to send the invite to');
    allGood = false;
  }
  if (!isValidEmail(document.getElementById('txtInviteEmail').value))
  {
    alert ('You must enter a valid email address');
    allGood = false;
  }
  if (!document.getElementById('txtInviteFrom').value.length > 0)
  {
    alert ('You must enter your name so the recipient will know who the invite is from');
    allGood = false;
  }

  return allGood;
}


function submitBetaInviteForm()
{
  if (validateFrmBetaInvite())
  {
    alert('Your invite has been sent to the elected email address. When the recipient responds, you will receive 30 status points.');
    submitForm(document.getElementById('frmBetaInvite'), '/ajax_frmBetaInvite_process.php', 'divNothing', function() {return true;});
    hidePopupForm();
  }
}


function closeInviteBetaForm()
{
  hidePopupForm();
}
