/*
 * File           : $Header: //depot/RELEASE/widget-framework-1.0/src/main/webapp/resources/js/searchFormHandler.js#2 $
 * Last edited by : $Author: erkr $ $Date: 2009/12/15 $
 * Version        : $Revision: #2 $
 *
 */

function isEmpty(form, fieldName) {
  var value = form[fieldName].value;
  return value == null || value == "";
}
function validateSearchForm(form,errorParaId) {
  var validationFailed = isEmpty(form,'all') && isEmpty(form,'exactPhrase') && isEmpty(form,'atLeastOne') && isEmpty(form,'without');
  if(validationFailed==true) {
    form['all'].style.border = '1px solid red';
    form['exactPhrase'].style.border = '1px solid red';
    form['atLeastOne'].style.border = '1px solid red';
    form['without'].style.border = '1px solid red';
    form['all'].focus();
    getElementById(errorParaId).style.display = 'block';
  }
  else {
    form['all'].style.border = '1px solid #A9A9A9';
    form['exactPhrase'].style.border = '1px solid #A9A9A9';
    form['atLeastOne'].style.border = '1px solid #A9A9A9';
    form['without'].style.border = '1px solid #A9A9A9';
    getElementById(errorParaId).style.display = 'none';
  }
  return !validationFailed;
}
function parseDateAndFormSubmit(advancedSearchForm, searchExprErrorParaId) {
  var currentDate = new Date();
  var currentDay = currentDate.getDate();
  var currentMonth = currentDate.getMonth() + 1;
  var currentYear = currentDate.getFullYear();

  if (currentMonth != "0") {
    currentMonth = "0" + currentMonth;
  }
  if (currentDay != "0") {
    currentDay = "0" + currentDay;
  }
  var fromDate = getElementById("searchFromDate").value;
  if (fromDate == null || fromDate == "") {
    fromDate = "2000-01-01";
  }
  var toDate = getElementById("searchToDate").value;
  if (toDate == null || toDate == "") {
    toDate = currentYear + "-" + currentMonth + "-" + currentDay;
  }
  fromDate = fromDate.replace("-", ",");
  fromDate = fromDate.replace("-", ",");
  toDate = toDate.replace("-", ",");
  toDate = toDate.replace("-", ",");
  var compareDateOne = new Date(fromDate);
  var compareDateTwo = new Date(toDate);
  // to make sure start date is before the end date
  if (compareDateOne > compareDateTwo) {
    toDate = fromDate;
  }

  var startDay = fromDate.substring(8, 10);
  var startMonth = fromDate.substring(5, 7);
  var startYear = fromDate.substring(0, 4);
  var toDay = toDate.substring(8, 10);
  var toMonth = toDate.substring(5, 7);
  var toYear = toDate.substring(0, 4);

  getElementById("searchStartDay").value = startDay;
  getElementById("searchStartMonth").value = startMonth;
  getElementById("searchStartYear").value = startYear;
  getElementById("searchToDay").value = toDay;
  getElementById("searchToMonth").value = toMonth;
  getElementById("searchToYear").value = toYear;

  if(validateSearchForm(advancedSearchForm, searchExprErrorParaId)) {
    advancedSearchForm.submit();
  }
}


