/*
 * <copyright>
 *  Copyright (c) 2003 by Hyperwave AG
 * </copyright>
 *
 * <file>
 *  Name:        CSSearch.js
 *  Created:     2003-01-28 by sweber
 *  Description: client side java script for handling some search actions
 *
 *  $Id: $
 * </file>
 */

//--------------------------------------------------------------------
/**
 * this function returns the url from the HW_MainframeUrl cookie
 * (as fallback, the current window pathname will be used)
 *
 * @return string: path for opening windows/locations
 */
function getCurrPath()
{
  var urlcookie = getCookie("HW_MainframeUrl");
  if (urlcookie != null)
    return urlcookie;

  var curr_path = window.location.pathname || "/";
  var idxs = []; // include the positiv indeces
  var strs = [';internal', '?', '#']; // check the current pathname  for this strings
  for (var i = 0; i < strs.length; i ++) {
    var tmp = curr_path.indexOf(strs[i]);
    if (tmp != -1) // store a positiv index
      idxs.push(tmp);
  }
  if (idxs.length == 0)
    return curr_path;
  var idx = idxs[0]; // is the minimum index
  if (idxs.length > 1) {
    // more than 1 relevant indexes
    for (var i = 1; i < idxs.length; i ++)
      idx = Math.min(idx, idxs[i]);
  }
  return curr_path.substr(0, idx) || "/";
}


/*
 * this function needs 1 client side wariable
 *   ~ window.search_alert4 =>
 */
function executeAction(theType, args) {
  if (theType == 'performsearch') 
  {
    var form_info = new CSFormData("");
    //reset Navigation if present 
    if (typeof document.bodyform.HW_HiddenEnv_Dir != "undefined")
      document.bodyform.HW_HiddenEnv_Dir.value = "";
    if (typeof document.bodyform.HW_HiddenEnv_MaxVisPage != "undefined")
      document.bodyform.HW_HiddenEnv_MaxVisPage.value = "";
    if (typeof document.bodyform.HW_HiddenEnv_LastNavStart != "undefined")
      document.bodyform.HW_HiddenEnv_LastNavStart.value = "";
    if (typeof document.bodyform.HW_HiddenEnv_CurrentPage != "undefined")
      document.bodyform.HW_HiddenEnv_CurrentPage.value = "";
    if (typeof document.bodyform.HW_HiddenIteratorId != "undefined")
    {
      document.bodyform.HW_HiddenIteratorId.value = "createnewiterator";
    }
    //store Formdata
    document.bodyform.HW_HiddenFormData.value = form_info.readForm(document.bodyform, {storeHiddenFields: true});
    return false;
  }
  else if (theType == 'resetsearch') 
  {
    if (typeof document.bodyform.HW_HiddenIteratorId != "undefined")
    {
      //reset Formdata
      document.bodyform.HW_HiddenFormData.value = "";
      var the_action = THE_OBJECT_URL + ';internal&action=dialog.search.action';
      document.bodyform.action = the_action;
      document.bodyform.submit();
    }
    else
     return false;
  }
  // case for changed number of results
  else if (theType == 'changenumber') {
    document.bodyform.HW_HiddenEnv_Dir.value = "";
    document.bodyform.HW_HiddenEnv_MaxVisPage.value = "1";
    document.bodyform.HW_HiddenEnv_LastNavStart.value = "1";
    document.bodyform.HW_HiddenEnv_CurrentPage.value = "1";
    var pars = new ParameterHandler(document.bodyform.HW_HiddenFormData.value);
    pars.reset(args.name, args.value);
    document.bodyform.HW_HiddenFormData.value = pars.asString();
    document.bodyform.submit();
    return false;
  }
  else if (theType == 'changethreshold') {
    document.bodyform.HW_HiddenEnv_Dir.value = "";
    document.bodyform.HW_HiddenEnv_MaxVisPage.value = "1";
    document.bodyform.HW_HiddenEnv_LastNavStart.value = "1";
    document.bodyform.HW_HiddenEnv_CurrentPage.value = "1";
    if (document.bodyform.numberOfObjectsFound)
    document.bodyform.numberOfObjectsFound.value="";
    var pars = new ParameterHandler(document.bodyform.HW_HiddenFormData.value);
    pars.reset(args.name, args.value);
    document.bodyform.HW_HiddenFormData.value = pars.asString();
    document.bodyform.submit();
    return false;
  }
  // case for change search description
  else if (theType == 'changedescription') {
    var pars = new ParameterHandler(document.bodyform.HW_HiddenFormData.value);
    pars.reset(args.name, args.value);
    document.bodyform.HW_HiddenFormData.value = pars.asString();
    document.bodyform.submit();
    return false;
  }
  // case for navigation around the search results
  else if (theType == 'navigate') {
    document.bodyform.HW_HiddenEnv_Dir.value = args;
    document.bodyform.submit();
    return false;
  }
  else if (theType == 'close') {
    return false;
  }
  return false;
}

function freeIterator(theId, useSelfWindow) {
  if (isNaN(theId)) {
    return;
  }
  if (useSelfWindow) {
    window.onunload = new Function("");
    window.location.pathname = getCurrPath() + ';internal&action=free.iterator.action&Parameter=' + theId;
  }
  else if (!top.opener || top.opener.closed || !top.opener.top || typeof top.opener.top.callServerFunction != 'function') {
    opDlg(getCurrPath() + ';internal&action=free.iterator.action&Parameter=' + theId, 'temp', '');
  }
  else {
    top.opener.top.callServerFunction({serverFunctionName: 'HW_Search.static_.freeIterator', callback: '', parameters: {iteratorId: theId}});
  }
}

//--------------------------------------------------------------------
/**
 * this function converts all possible dates in search formular to user selected
 * date format. this is necessary, because we restore the form values onload and
 * the dates will be restores in HWDate format. this  function has to be called
 * onload, after restoring the fomdata.
 *
 * @param theForm: object: a reference to a html formular
 */
function convertDatesInSearchForm(theForm) {
  for (var i = 0; i < theForm.elements.length; i ++) {
    var curr = theForm.elements[i];
    if (SpecArray[curr.name] && SpecArray[curr.name].type == "HW_API_Date" && curr.value) {
      // found a form element of type HW_API_Date ... convert inot user selected date format
      convDateInForm(curr, {sFormat: HWDate, dFormat: HW_UI_Date, dateOnly: true});
    }
  }
}

//--------------------------------------------------------------------
/**
 *
 */
function checkScopeSelected()
{
  var theForm = document.bodyform;
  for (var i = 0;i < theForm.elements.length; i ++) 
  {
    var curr = theForm.elements[i];
    var s_index= curr.name.indexOf("scope_");
    if (s_index!= -1)
    {
      if (curr.checked) 
      {
       return true;
      }
    }
  }
  alert(search_alert_noscope);
  return false;
}
//--------------------------------------------------------------------
/**
 *
 */
function checkSearchStringpresent()
{
  var theForm = document.bodyform;
  var ss_set = false;
  for (var i = 0;i < theForm.elements.length; i ++) 
  {
    var curr = theForm.elements[i];
    var s_index= curr.name.indexOf("searchstring_");
    if (s_index!= -1)
    {
      if (curr.value != "")
      {
        if (curr.value.match(/(^[^\*]{0,2}[\*]+$)|(^[\*]+[^\*]{0,2}$)|(^[\*]+[^\*]{0,2}[\*]+$)|(^ *\* +)|( \* *$)/)) 
        {
          // invalid search string is given -> alert the user
          alert(search_alertwrongsstring);
          return false;
        }
        ss_set = true;
      }
    }
  }
  if (!ss_set)
  {
    alert(search_alertnosstring);
    theForm.searchstring_0.select();
    theForm.searchstring_0.focus();
    return false;
  }
  return ss_set;
}

//--------------------------------------------------------------------
/**
 *
 */
function checkDateRange()
{
  var theForm = document.bodyform;
  var fromdate = (theForm.yearFrom.value || "")+"-"+(theForm.monthFrom.value || "")+"-00";
  var todate   = (theForm.yearTo.value || "")  +"-"+(theForm.monthTo.value || "")+"-32";
  if (fromdate > todate)
  {
    alert("Wrong Date range: From-Date must be smaller than To-Date. Please correct your Input!");
    theForm.monthFrom.focus();
    return false;
  }
  return true;
}

//--------------------------------------------------------------------
/**
 *
 */
function checkSubmit()
{
  return (checkSearchStringpresent() && checkScopeSelected() && checkDateRange());
}


function getNamefromForm(form_action)
{
  var form_act=form_action || "";
  if (form_act == "")
  {
    return form_act;
  }
  var index =form_act.indexOf(";");
  if (index != -1)
  {
     form_act = form_act.substring(0,index);
  }
  return form_act;
}

/**
 *SIMPLESEARCH
 */
function checkPerformSearch (theForm) {
  if (theForm.searchstring_0.value.match(/(^[^\*]{0,2}[\*]+$)|(^[\*]+[^\*]{0,2}$)|(^[\*]+[^\*]{0,2}[\*]+$)|(^ *\* +)|( \* *$)/)) {
    // invalid search string is given -> alert the user
    alert("This search string is not allowed!");
    theForm.searchstring_0.select();
    theForm.searchstring_0.focus();
    return false;
  }
  else if (theForm.searchstring_0.value.match(/\S/)) {
    // a search string is given
    // prepare the search parameter
    var search_pars = new ParameterHandler();
    search_pars.add('Caller', 'UserBlock');
    // open a dialog window
    var window_obj = opDlg("/wavemaster.internal/v6.3/lib/empty.html", "search",{width:650,height:650});
    // set the formular target to the dialog window
    if (window_obj && window_obj.name)
      theForm.target = window_obj.name;
    theForm.action = getNamefromForm(theForm.action) + ";internal&action=execute.search.action" + search_pars;
    theForm.searchstring_1.value = theForm.searchstring_0.value;
    var form_info = new CSFormData();
    form_info.readForm(theForm, {storeHiddenFields: true});
    theForm.HW_HiddenFormData.value = form_info.asString();
    theForm.submit();
    return true;
  }
  else 
  {
    opDlg(getNamefromForm(theForm.action) + ";internal&action=dialog.search.action", "search",{width:650,height:650});
    return false;
  }
}
