
/**
* elements uids
**/
var KIND_SEL_ID = 'kind';
var SUBKIND_SEL_ID = 'subkind';
var DOING_SEL_ID = 'doing';
var PROPERTY_PREFIX_EL_ID = 'req';

/**
* Anchors symbols
**/
var KIND_ANCHOR = 'k';
var DOING_ANCHOR = 'd';
var SUBKIND_ANCHOR = 'sk';
var PROPERTY_ANCHOR = 'p';


//var sAjaxBusyIcon = "<div><img src='/fileadmin/img/gray_busy.gif'></div>";
var sAjaxBusyIcon = "<div><img src='/fileadmin/img/spinner.gif'></div>";


/**
* Blocks uids
**/
var SUBKIND_BLOCK_ID = 'subkind_block';
var KIND_BLOK_ID = 'kind_block';
var PROPERTIES_BLOCK_ID = 'checkboxlist';
var CHECKBOXLIST_BLOCK_ID = 'checkboxlist';
var DOING_BLOCK_ID = 'doings_block';

/**
* hidden fields id's
**/
var SITE_URL_HIDDEN_ID = 'site_url';
var URL_PARAMS_HIDDEN_ID = 'url_params';

/**
* main anchors positions, need for know what element was selected first;
**/
var sAnchorKindPosition = '';
var sAnchorDoingPosition = '';


/**
 * redirect to page with needed parameters for search
 *
 * @param str sPageUid
 */
function goSearch(sPageUid) {
  sUrlHash = window.location.hash;
    if (sUrlHash.indexOf("#") == 0) {
      sCut = 1;
      sUrlHash = sUrlHash.substr(sCut);
    }
    if (sUrlHash != '') {
      sUrlHash = urlencode(sUrlHash);
//      window.location.href = sPageUid + '&anchors=' + sUrlHash + window.location.hash;
      window.location.href = sPageUid + '?anchors=' + sUrlHash + window.location.hash;
    }
}

/**
 * php compatible encode function
 *
 * @param str s
 * @return str
 */
function urlencode(s) {
  s = encodeURIComponent(s);
  return s.replace(/~/g,'%7E').replace(/%20/g,'+');
}

/**
 * php compatible decode function
 *
 * @param str s
 * @return str
 */
function urldecode(s) {
  str = s.replace(/%7E/g,'~').replace(/\+/g,'%20');
  str = decodeURIComponent(str);
  return str;
}

/**
 * php compatible decode function
 *
 * @param str s
 */
function CheckFormParams() {
  checkParams();
}

/**
 * get element value by html element id
 *
 * @param str sElId
 * @return str
 */
function getElValue(sElId) {
  var sValue = '';
  if (sElId != '') {
    oEl = document.getElementById(sElId);
    if (oEl) {
      sValue = oEl.value;
    }
  }

  return sValue;
}

/**
 * put default value for select box by id
 *
 * @param str sElId
 */
function setSelectDefaultById(sElId) {
  if (sElId != '') {
    oEl = document.getElementById(sElId);
    if (oEl) {
      oEl.value = '';
    }
  }
}

/**
 * sends ajax query for restore default values of all form elements
 *
 */
function clearForm() {
  var sUrlHash = window.location.hash;
  var i;
  var sCut = 0;

  if (sUrlHash != '') {
    if (sUrlHash.indexOf("#") == 0) {
      sCut = 1;
    }
    sUrlHash = sUrlHash.substr(sCut);

    if (sUrlHash != '') {
      $sAjaxUrl = getElValue(URL_PARAMS_HIDDEN_ID).replace("+anchors+", '').replace("anchors_load", 'resetall');
      vUpdateAllContent(getElValue(SITE_URL_HIDDEN_ID),$sAjaxUrl, 'reset');
    }
  }
}

/**
 * litle controller function for Kind select box
 *
 * @param str sAnchor
 * @param obj sElId
 */
function KindController(sAnchor, oEl) {
  generateSingleParam(sAnchor, oEl);
  CheckSubKind(SUBKIND_BLOCK_ID);
  CheckProperties(PROPERTIES_BLOCK_ID);
  changeFocus(oEl.value, 'resetbutton');
}

/**
 * litle controller function for Doing select box
 *
 * @param str sAnchor
 * @param obj sElId
 */
function DoingControler(sAnhor, oEl) {
  generateSingleParam(sAnhor, oEl);
  CheckProperties(PROPERTIES_BLOCK_ID);
  changeFocus(oEl.value, 'resetbutton');
}

/**
 * onload function which check url params and generate/parse anchors also doing preselection mode
 *
 */
function checkParams() {
  var sUrlHash = window.location.hash;
  var sSearch = window.location.search;
  var i;
  var sCut = 0;
  var $sAnchorProiperties = '';
  var sAnchorSubKind = '';
  var sAnchorPosition = '';

  if (sUrlHash != '') {
    if (sUrlHash.indexOf("#") == 0) {
      sCut = 1;
    }
    sUrlHash = sUrlHash.substr(sCut);
    if (sUrlHash != '') {
      sAnchorKindPosition = sUrlHash.indexOf(KIND_ANCHOR+":");
      sAnchorDoingPosition = sUrlHash.indexOf(DOING_ANCHOR+":");
      sAnchorPos = "&kindposition=" + sAnchorKindPosition + "&doingposition=" + sAnchorDoingPosition + "&";
      if (sAnchorKindPosition == -1 && sAnchorDoingPosition == -1) {
        CheckSubKind(SUBKIND_BLOCK_ID);
        CheckProperties(PROPERTIES_BLOCK_ID);
        return;
      }

      $sAjaxUrl = getElValue(URL_PARAMS_HIDDEN_ID).replace("+anchors+", urlencode(sUrlHash)+sAnchorPos);
      vUpdateAllContent(getElValue(SITE_URL_HIDDEN_ID),$sAjaxUrl, '');
    } else {
      CheckSubKind(SUBKIND_BLOCK_ID);
      CheckProperties(PROPERTIES_BLOCK_ID);
    }
  } else if (sUrlHash == '') {
      CheckSubKind(SUBKIND_BLOCK_ID);
      CheckProperties(PROPERTIES_BLOCK_ID);
  }

  if (sSearch != '' && sUrlHash == '') {
    sSearch = urldecode(sSearch);
    $sParamPosition  = sSearch.indexOf("anchors=");
    if ($sParamPosition > 0) {
      var sExpression = "anchors=((\\w)+:(\\d)+,?)+";
      //var sPattern = new RegExp(sExpression);
      //var aAnchorsPart = sPattern.exec(sSearch);
      aAnchorsPart = sSearch;
      if (aAnchorsPart != '') {
        //var sAnchors = aAnchorsPart.join().replace("anchors=", "");
        var sAnchors = aAnchorsPart.replace("?anchors=", "");
        window.location.hash = sAnchors;
        checkParams();
      }
    }
  }
}

/**
 * enables checked properties, now not use but maybe needed in future
 *
 */
/*
function EnableChecked(sElIdPart, sValues) {
  oKind = document.getElementById(KIND_SEL_ID);
  oDoing = document.getElementById(DOING_SEL_ID);
  aValues = sValues.split(".");
  if (oKind.value != '' || oDoing.value != '') {
    for (i = 0; i < aValues.length; i++) {
      sElId = sElIdPart + aValues[i];
      oCbx = document.getElementById(sElId);
      oCbx.checked = true;
    }
  }
}
*/

/**
 * past selected value to select box, now not use but maybe needed in future
 *
 */
/*
function pastSelected(oId, elValue) {
  if (oId) {
    oEl = document.getElementById(oId);
    if (!isNaN(elValue)) {
      for (i = 0; i < oEl.length; i++) {
        if (oEl.options[i].value == elValue) {
          oEl.options[i].selected = true;
        }
      }
    }
  }
}
*/

/**
 * check/change, add/remove one some anchor for select box
 *
 * @param str sAnchor
 * @param obj oEl
 */
function generateSingleParam(sAnchor, oEl) {
  if (sAnchor != '' && sAnchor.length > 0)  {
  var sUrl = window.location.hash;
  var sNewParam = '';
  var sReplace = '';
  var sExpression = '';

    if (!isNaN(oEl.value)) {
      if (sUrl == '' || sUrl == '#') {
        window.location.hash = sAnchor + ':' + oEl.value;
      } else {
        iPos = sUrl.indexOf(sAnchor + ":");
        if (iPos < 0) {
          window.location.hash = sUrl + ',' + sAnchor + ':' + oEl.value;

        } else {
          if (oEl.value != '') {
            sExpression = sAnchor + ":(\\d)+";
            sNewParam = sAnchor + ':' + oEl.value;
          } else {
            if (iPos > 1) {
              sExpression = ',?' + sAnchor + ":(\\d)+";
            } else if (iPos == 1) {
              sExpression = sAnchor + ":(\\d)+,?";
            }
          }
          sReplace = new RegExp(sExpression);
          window.location.hash = sUrl.replace(sReplace, sNewParam);
        }
      }
    }
  }
}

/**
 * check/change, add/remove anchor for checkbox
 *
 * @param str sAnchor
 * @param obj oEl
 */
function generateCheckBoxParam(sAnchor, oEl) {
  if (sAnchor != '' && sAnchor.length > 0) {
  var sUrl = window.location.hash;
  var sNewParamStr = '';
  var sReplace = '';
  var sExpression = '';
  var aParams = new Array();
  var mFound = '';
    if (!isNaN(oEl.value) && oEl.value > 0 ) {
      if (sUrl == '') {
        window.location.hash = sAnchor + ':' + oEl.value;
      } else {
        iPos = sUrl.indexOf(sAnchor + ":");

        if (iPos < 0) {
          window.location.hash = sUrl + ',' + sAnchor + ':' + oEl.value;
        } else if (iPos > 1) {
          sExpression = ',?' + sAnchor + ":((\\d)+(\\.)*)+";

          sPattern = new RegExp(sExpression);
          sTempStr = sPattern.exec(sUrl);
          if (sTempStr[0]) {
            aAnchor = sTempStr[0].split(":");
            aParams = aAnchor[1].split(".");

            if (oEl.checked == true) {
              iFound = array_search(oEl.value, aParams);
              if (iFound == -1) {
                aParams.push(oEl.value);
              }
              sNewParamStr = aAnchor[0] + ':' + aParams.join(".");
            } else {
              iFound = array_search(oEl.value, aParams);
              if (iFound != -1) {
                iIndex = getArrayIndex(oEl.value, aParams);
                if (iIndex != -1) {
                  aParams.splice(iIndex, 1);
                }
              }
              sParamsStr = aParams.join(".");
              if (sParamsStr != '') {
                sNewParamStr = aAnchor[0] + ':' + sParamsStr;
              }
            }

            sReplace = sTempStr[0];
            window.location.hash = sUrl.replace(sReplace, sNewParamStr);
          }
        }
      }
    }
  }
}

/**
 * search needle value in array
 *
 * @param str needle
 * @param array haystack
 * @param bool strict
 * @return value if found or -1 if not
 */
function array_search(needle, haystack, strict) {
  var strict = !!strict;
  for (var key in haystack) {
    if((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)){
      return key;
    }
  }
  return -1;
}

/**
 * search index of element in array by value
 *
 * @param str sVal
 * @param array aArray
 * @return index if found, if not return -1
 */
function getArrayIndex(sVal, aArray) {
  var iCount = 0;
  var i;
  if (aArray.length > 0 && sVal!= '') {
    for(i = 0; i < aArray.length; i++) {
      if (sVal == aArray[i]) {
        return iCount;
      }
      iCount++;
    }
  }
  return -1;
}

/**
 * check subkind select box, if kind selected show subkind block, if not hide subkind block
 *
 * @param obj oDivBlock
 */
function CheckSubKind(oDivBlock) {
  oKind = document.getElementById(KIND_SEL_ID);
  oSubKind = document.getElementById(SUBKIND_SEL_ID);
  oDiv = document.getElementById(oDivBlock);

  if (oKind) {
    if (oKind.value == '') {
      clearAnchor(SUBKIND_ANCHOR);
      if (oSubKind) {
        oSubKind.value = '';
      }
      oDiv.style.display = "none";
    } else {
      oDiv.style.display = "block";
    }
  } else {
    clearAnchor(SUBKIND_ANCHOR);
    oDiv.style.display = "none";
  }
}

/**
 * check checkbox list with properties, if kind or doing selected show properties block,
 * if not hide properties block
 *
 * @param obj oDivBlock
 */
function CheckProperties(oDivBlock) {
  oDiv = document.getElementById(oDivBlock);
  oKind = document.getElementById(KIND_SEL_ID);
  oDoing = document.getElementById(DOING_SEL_ID);
  oListDiv = document.getElementById(CHECKBOXLIST_BLOCK_ID);
  aElList = oListDiv.childNodes;

  if (oKind && oDoing) {
    if (oKind.value != '' || oDoing.value != '') {
      oDiv.style.display = "block";
    } else {
      for (i=0; i < aElList.length; i++) {
        if (aElList[i].type == "checkbox") {
          aElList[i].checked = false;
        }
      }
      clearAnchor(PROPERTY_ANCHOR);
      oDiv.style.display = "none";
    }
  }
}

/**
 * clear selected anchor
 *
 * @param str sAnchor
 */
function clearAnchor(sAnchor) {
  if (sAnchor != '' && sAnchor.length > 0) {
    var sUrl = window.location.hash;
    var sReplace = '';
    var sExpression = '';

    if (sUrl != '') {
      iPos = sUrl.indexOf(sAnchor + ":");
      if (iPos > 1) {
        if (sAnchor == PROPERTY_ANCHOR) {
          sExpression = ',?' + sAnchor + ":((\\d)+(\\.)?)+";
        } else {
          sExpression = ',?' + sAnchor + ":(\\d)+";
        }
      } else if (iPos == 1) {
        if (sAnchor == PROPERTY_ANCHOR) {
          sExpression = sAnchor + ":((\\d)+(\\.)?)+,?";
        } else {
          sExpression = sAnchor + ":(\\d)+,?";
        }
      }

      sReplace = new RegExp(sExpression);
      window.location.hash = sUrl.replace(sReplace, '');
    }
  }
}

/**
 * after anchor clearing, focus on some form element for decrease page jumping to top
 * also fix ie bug "scroll-wheel on the mouse"
 *
 * @param str oEl
 * @param str sFocusId
 */
function changeFocus(oEl, sFocusId) {
  if (oEl == "") {
    sHash = window.location.hash;
    if (sHash.length == 1 || sHash == "#") {
      Form.Element.focus(sFocusId);
    } else if (sHash == "") {
      Form.Element.focus(sFocusId);
    }
  } else {
    if (navigator.appName == "Microsoft Internet Explorer") {
      document.body.focus();
    }
  }
}
