/**
 * A collection of utility functions for the PBS Website
 * 
 * @author Christophe Lauret (Allette Systems)
 * @author Jean-Baptiste Reure (Allette Systems)
 * @author Tu Tak Tran (Allette Systems)
 * 
 * @version 13 June 2008
 */

/**
 * Reloads the current location.
 */
function doRefresh() {
  this.location.reload();
}

/**
 * Toggle on and off a block.
 * 
 * This function uses the 'class' of a block to determine its state (isopen|isclosed).
 * It does nothing if the element ID could not be found on the page.
 *
 * @param id The id of the toggled block.
 * 
 * @return always false
 */
function toggle(id) {
  var block = document.getElementById(id);
  if (block) {
    if (block.className.indexOf('isopen') != -1) {
      block.className = block.className.replace(/isopen/, 'isclosed');
    } else if (block.className.indexOf('isclosed') != -1) {
      block.className = block.className.replace(/isclosed/, 'isopen');
    }
    // prevents the page from moving
    return false;
  } else return true;
}

/**
 * Toggle on and off a block and loads the contents if it has not been previously loaded.
 * 
 * @param id The id of the toggled block.
 * @param url The id of the toggled block.
 * 
 * @return <code>true</code> if the link should be followed instead;
 *         <code>false</code> otherwise.
 */
function toggleContents(id, url) {
  var notfound = toggle(id);
  if (notfound) return true;
  // already loaded ?
  if (document.getElementById(id + '-loaded')) return false;
  retrieveDataAsHTML(url, id + '-contents');
  return false;
}

/**
 * Checks whether the search includes search terms.
 * 
 * @param form The Consumer search form.
 * 
 * @return Always false
 */
function checkConsumerSearchForm(form) {
	// return true if there is a value for Medicine
  if (form.term && form.term.value != '')
	  return true;
  if (form.medicine && form.medicine.value != '')
	  return true;
	// return true if there is a value for Manufacturer
  if (form.manufacturer && form.manufacturer.value != '')
   return true;
  // return false in all other cases
  alert('Please enter a medicine or a manufacturer name.');
  return false;
}

/**
 * Checks whether the search includes search terms.
 * 
 * @param form The Health Professional search form.
 * 
 * @return true if valid form, false if invalid
 */
function checkProfessionalSearchForm(form) {
  // return true if there is a value for Medicine
  if (form.term && (form.term.value != ''))
    return true;
  
  // return true if there is a value for Body System
  if (form.bodysystem && (form.bodysystem.value != ''))
    return true;
  
  // return true if there is a value for Manufacturer
  if (form.manufacturer && (form.manufacturer.value != ''))  
    return true;
  
  // return true if any one of the "Only show products which are" checkboxes are
  // set (should be 9 checkboxes in total)
  // Check all checkboxes of name 'publication' (should be 7)
  publicationCheckboxes = form.publication 
  for (var i = 0; i < publicationCheckboxes.length; i++) {	
	if (publicationCheckboxes[i].checked == true)
	  return true; // If any checkboxes are checked, form is valid     
  }
  // Note the use of .elements[], as javascript can't handle '-' in variables.
  // It thinks it is a minus sign.    	
  if (form.elements["streamlined-authority-only"] && (form.elements["streamlined-authority-only"].checked == true)) {    
    return true;
  } 
  if (form.medicine && (form.medicine.checked == true))
    return true;   
    
  // return false in all cases fail
  alert('Please enter a brand/generic name or an body system name.');
  return false;
}


/**
 * Checks whether the search includes search terms.
 * 
 * @param form The Health Professional search form.
 * 
 * @return true if valid form, false if invalid
 */
function checkIndustrySearchForm(form) {
	checkProfessionalSearchForm(form);
}

/**
 * Submits the form if it contains check boxes that have been ticked.
 * 
 * Does nothing otherwise.
 * 
 * @param form The form to submit
 */
function checkItemsToWatchForm(form) {
  var inputs = form.elements;
  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == 'checkbox' && inputs[i].checked) {
      return true;
    }
  }
  return false;
}

// Not reviewed yet -------------------------------------------------------

/**
 */
function unWatch(form) {
  var inputs = form.elements;
  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].type == 'checkbox' && inputs[i].checked == false) {
      form.unwatch.value += inputs[i].value + ', ';
    }
  }
  return true;
}

/**
 * Adds a value then submit.
 * 
 * @param url The URL for the popup.
 */
function addValueThenSubmit(startUrl, code) {
  toggle(code);
  // already loaded ?
  if (document.getElementById(code + '-loaded')) return false;
  retrieveDataAsHTML(startUrl+'/html/select/body-system/browse?code=' + code, code + '-children');
  return false;
}

/**
 * Toggle on/off a branch of the ATC hierarchy using the fragment.
 * 
 * @param servletPath The servlet path
 * @param area        'consumer', 'select' or 'healthpro'
 * @param code        The ATC code
 */
function toggleBranchATC(servletPath, area, code) {
  toggle(code);
  // already loaded ?
  if (document.getElementById(code + '-loaded')) return false;
  retrieveDataAsHTML(servletPath+'/fragment/'+area+'/body-system?code=' + code, code + '-contents');
  return false;
}

/**
 * Adds a value then submit.
 * 
 * @param servletPath The URL for the popup.
 * @param code        The ATC code
 * 
 * @deprecated use #toggleBranchATC
 */
function toggleProfessionalATC(servletPath, code) {
  return toggleBranchATC(servletPath, 'healthpro' ,code);
}

/**
 * Opens a window for the print layout.
 * 
 * This popup should not be too large for 800x600 screens.
 * 
 * @param url The URL for the popup.
 * 
 * @return Always false
 */
function printWindow(url) {
  window.open(url, 'popup', 'height=400,width=600,titlebar=no,toolbar=no,menubar=no,resizeable=yes,status=no,scrollbars=yes');
  return false;
}

/**
 * Opens the select window in a new window.
 * 
 * This popup should not be too large for 800x600 screens.
 * 
 * @param url The URL for the popup.
 */
function openSelectWindow(url) {
  window.open(url, 'select', 'height=400,width=500,titlebar=no,toolbar=no,menubar=no,resizeable=yes,status=no,scrollbars=yes');
}

/**
 * Opens the CMI PDF file in a new window for consumers.
 * 
 * This popup should not be too large for 800x600 screens.
 * 
 * @param url    The URL for the popup.
 * @param online true if there is an Internet connection to this file; false otherwise.
 */
function cmiLink(url, online) {
  if (online) {
    var ok = confirm('You are about to access information provided by a pharmaceutical company. The Department of Health and Ageing has not checked, endorsed or approved this information.\n\nYou should seek advice from your doctor to confirm the suitability of this medication for your particular health condition before relying on information in this consumer fact sheet.\n\nFor more information, please see the site Disclaimer.\n');
    if (ok)
      window.open(url, 'cmi', 'height=500,width=600,titlebar=no,toolbar=no,menubar=no,resizable=yes,status=no,scrollbars=yes');
  } else {
  	alert('You are using the offline version of this site.\nPlease connect to the Internet in order to access this Consumer Medicine Information sheet.');
  }
  return false;
}

/**
 * Opens the CMI/PI PDF file in a new window for Health Professionals.
 * 
 * This popup should not be too large for 800x600 screens.
 * 
 * @param url    The URL for the popup.
 * @param online true if there is an Internet connection to this file; false otherwise.
 */
function picmiHPLink(e, evElement, url, online) {
  if (online) {
    var ok = confirm('You are about to access information provided by a pharmaceutical company. The Department of Health and Ageing has not checked, endorsed or approved this information.\n\nFor more information please see the site Disclaimer.\n');
    if (ok)
      window.open(url, 'cmi', 'height=500,width=600,titlebar=no,toolbar=no,menubar=no,resizable=yes,status=no,scrollbars=yes');
  } else {
  	alert('You are using the offline version of this site.\nPlease connect to the Internet in order to access CMI/PI.');
  }

  return false;
}

/**
 * Opens the PDF file for a publication in a new window.
 * 
 * This popup should not be too large for 800x600 screens.
 * 
 * @param url The URL for the popup.
 */
function pdfLink(url) {
  window.open(url, 'cmi', 'height=500,width=600,titlebar=no,toolbar=no,menubar=no,resizable=yes,status=no,scrollbars=yes');
  return false;
}

/**
 * Set the value in the form
 * 
 * @param value The value to put in the form.
 * @param id    The id of the form input.
 * 
 * @return false if the value could be updated;
 *         true otherwise.
 */
function setFormValue(value, id) {
  if (window.opener && window.opener.document.getElementById(id)) {
  	var input = window.opener.document.getElementById(id)
    input.value = value;
    input.className = input.className.replace(/emptybox/, '');
    window.close();
    return false;
  } else {
    return true;
  }
}

/**
 * This function is triggered by the body.onload event.
 * 
 * Gives focus to elements in forms.
 */
function onLoad() {
  
  // If javascript is enable, show content within <span class="with-js">
  var classes = getElementsByClassName('with-js');
  for (var i=0; i < classes.length; i++){
    classes[i].className = classes[i].className.replace(/isclosed/, 'isopen');
  }
  
	var isSearchPage = (document.getElementById('service-healthpro-home') != null)
                  || (document.getElementById('service-consumer-home') != null)
                  || (document.getElementById('service-healthpro-search-advanced') != null)
                  || (document.getElementById('service-consumer-search-advanced') != null);
  if (isSearchPage) {
  	// focus on the main search term text input
    var found = focusOn('form-search-medicine');
	  if (!found) focusOn('form-search-term');
  }
 
}

/**
 * Gives focus to the element with the specified ID.
 * 
 * @param id The id of the element.
 * 
 * @return <code>true</code> if the focus was given to the specified element;
 *         <code>false</code> otherwise.
 */
function focusOn(id) {
	var element = document.getElementById(id);
  if (element) {
  	element.focus();
  	return true;
  } else return false;
}


function getElementsByClassName(classname) {
  var node = document.getElementsByTagName("body")[0];
  var a = [];
  var re = new RegExp('\\b' + classname + '\\b');
  var els = node.getElementsByTagName("*");
  for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))a.push(els[i]);return a;
}
       




