var sCounter = 0; //replace this with x_y
var dEquiv = { //only required until js regex grows up to support unicode char/mark
'a': '[aAÁáÀàĂăÂâǍǎÅåÄäǞǟÃãĄąĀā]',
'b': '[bBƀ]',
'c': '[cCĆćĈĉČčĊċÇç]',
'd': '[dDĎďĐđƉð]',
'e': '[eEÉéÈèĔĕÊêĚěËëĖėĘęĒē]',
'f': '[fFƑƒ]',
'g': '[gGĞğĜĝǦǧĠġĢģǤǥ]',
'h': '[hHĤĥĦħ]',
'i': '[iIÍíÌìĬĭÎîǏǐÏïĨĩİĮįĪīıƗ]',
'j': '[jJĴĵǰ]',
'k': '[kKǨǩĶķ]',
'l': '[lLĹĺĽľĻļŁłŁłƚ]',
'n': '[nNŃńŇňÑñŅņ]',
'o': '[oOÓóÒòŎŏÔôǑǒÖöŐőÕõØøǪǫǬǭŌōƠơƟ]',
'r': '[rRŔŕŘřŖŗ]',
's': '[sSßŚśŜŝŠšŞş]',
't': '[tTÞþŤťŢţŦŧƫƮ]',
'u': '[uUÚúÙùŬŭÛûǓǔŮůÜüǗǘǛǜǙǚǕǖŰűŨũŲųŪūƯư]',
'w': '[wWŴŵ]',
'y': '[yYÝýŶŷŸÿ]',
'z': '[zZŹźŽžŻżƶ]'
};


function initPage(){
//set catFilter functionality
  $(".idx_catfilter").each(function(){
    $(this).click(function () {
      showIndexCat(this.id.split("-cf")[1]);
    });
    this.href="#";
  });

//  setSearchNavBar();

  setExtLinks();
  hiLighter();
  setFBox();

  //run any document specific initialisation
  if (window.initDoc) { initDoc(); }

}
//		scrolling : 'auto',	// 'auto', 'yes' or 'no'
function setSearchNavBar(){

//get class of button and strip function ie navBar_next = > next
//then pass as variable to runsubmit

}
function runGetSearch(func){
//func: function to carry out - if blank assume first

}
function setFBox(){
  $(".fBox").fancybox({
		'padding'             : 4,
    'hideOnContentClick'  : true,
    'transitionIn'        :	'elastic',
    'transitionOut'	      :	'elastic',
    'overlayShow'	        :	false,
    'titlePosition'       : 'inside',
    'enableEscapeButton'  : true
  });
  $(".fBoxRef").fancybox({
		'padding'             : 0,
    'hideOnContentClick'  : false,
    'transitionIn'        :	'elastic',
    'transitionOut'	      :	'elastic',
    'overlayShow'	        :	false,
    'titlePosition'       : 'inside',
    'enableEscapeButton'  : true,
    'autoScale'           : false,
		'autoDimensions'      : true,
		'scrolling'           : 'no'
  });
  $(".fBoxDoc").fancybox({
		'padding'             : 4,
    'overlayShow'	        :	false,
    'enableEscapeButton'  : true,
    'autoScale'           : true,
		'autoDimensions'      : false,
		'scrolling'           : 'auto'
  });
}

function showIndexCat(cF){
  if (cF.substring(0,1)!="_") cF = "_"+cF;

  $(".indexsubcat").hide();
  $("#idxsub"+cF).show();
  $(".menusubitem_s").removeClass("menusubitem_s");
  $("#mi"+cF).addClass("menusubitem_s");
  $(".idx-cat_foot").show();
}

function setExtLinks() {
  if (!document.getElementsByTagName && document.getElementById) return;
  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "newWindow")
       anchor.target = "_blank";
 }
}
function setIdxMenu(){


}

//poc script to find specific search result
function nextResult(){
  window.location.hash = "#sr3";
}

//functional code below
function hiLighter() {
// alert("hello");
  var sR      = window.location.search.replace(/^\?/,"");
  var sParts  = sR.split("&");
  var sReq    = new Object();

//go through each part and create a key value pair split by = for each sPart
  for(var sPart in sParts){
    var sTmp     = sParts[sPart].split("=");
    sReq[sTmp[0]] = sTmp[1];
//    alert(sTmp[0]+" => "+sTmp[1]);
   }

  if (sReq.hasOwnProperty("idxcat")){
    showIndexCat(sReq["idxcat"])
  }

  if (sReq.hasOwnProperty("s") && sReq["s"] != ""){
    sReq["s"] = decodeURIComponent(sReq["s"].replace(/\+/g, '%20'));
    sReq["s"] = repDialectics(sReq["s"]);
// alert(sReq["s"]);
    var sT = sReq["s"].split("_");
    for( var i in sT){
      var sReg = makeSearchRegex(sT[i]);
//      alert(sReg);
      hiLight($e("content"),sT[i].replace("*",""),sReg,i);
    }
  }

  if (sReq.hasOwnProperty("sReq") && sReq["sReq"] != ""){
    sReq["sReq"] = decodeURIComponent(sReq["sReq"].replace(/\+/g, '%20'));
    $e("inpsearch").value=sReq["sReq"];
    sReq["sReq"] = repDialectics(sReq["sReq"]);
    sReq["sReq"] = formatSReq(sReq["sReq"]);
//    alert(sReq["sReq"]);

    var sT = sReq["sReq"].split("_");
    for( var i in sT){
      var sReg = makeSearchRegex(sT[i]);
//      alert(sReg);
      hiLight($e("content"),sT[i].replace("*",""),sReg,i);
    }
  }

  if (sReq.hasOwnProperty("v")){
    var rP = parseRange(sReq["v"]);
    if (rP.length != 0){
      for( var i in rP){
        $e("sv"+rP[i]).className = "searchresult";
      }
    }
  }
  if (sReq.hasOwnProperty("p")){
    var rP = parseRange(sReq["p"]);
    if (rP.length != 0){
      for( var i in rP){
        $e("sp"+rP[i]).className = "searchresult";
      }
    }
  }
  if (sReq.hasOwnProperty("sec")){
    var rP = parseRange(sReq["sec"]);
    if (rP.length != 0){
      for( var i in rP){
        $e("ss"+rP[i]).className = "searchresult";
      }
    }
  }
}

function formatSReq(sR){
  var sWs = (sR.replace(/\s+/g, ' ')).split(" ");
  var fR  = "";
  var isPhrase = false;
  var tP;

  for (var sW in sWs){
    var tSw = sWs[sW];
// alert(sWs[sW].charAt(0));

    var tQpos = tSw.search('"');
    
    if (tQpos == -1){
      //no quote in word - check if in phrase and append to fR/tP
      if (isPhrase){
        tP += " "+tSw
      } else {
        if (fR.length > 0){
          fR += "_"+tSw;
        } else {
          fR = tSw;
        }
      }
    } else if (tQpos == 0){
      //quotes is at start of word - stat new phrase
      isPhrase=true;
      tP = tSw.replace('"','');
    } else if (tQpos == (tSw.length-1)){
      //quote is last character - append to tP and append tP to fR - reset isPhrase to false
      tP += " "+tSw.replace('"','');
      if (fR.length > 0){
        fR += "_"+tP;
      } else {
        fR = tP;
      }
      isPhrase=false;
    }
  }
  return fR ;
}
function parseRange(inpRange){
//input:  128,130-135
//output: 128,130,131,132,133,134,135

//split on ","" then go through each and split on "-"
//if only has [0] add to output array else add all numbers between [0] and [1]

var outVals = [];

  if (inpRange.length >0) {
    var rP = inpRange.split(",");
    if (rP.length != 0){
      for( var x in rP){
        var rPs = rP[x].split("-");
        if (rPs.length == 1){
            outVals.push(rPs[0]);
        }
        if (rPs.length > 1){
          if (IsNumeric(rPs[0]) && IsNumeric(rPs[1])){
            for (y = rPs[0];y <= rPs[1]; y++){
              outVals.push(y);
            }
          }
        }
      }
    }
  }
  return outVals;
}
function IsNumeric(inString){
  var strChar;
  var isNum = true;

  if (inString.length == 0) return false;
  var vNums = "0123456789";
  for (i = 0; i < inString.length && isNum == true; i++){
    strChar = inString.charAt(i);
    if (vNums.indexOf(strChar) == -1){
      isNum = false;
    }
  }
  return isNum;
}
function repDialectics(sS){
  var oS=sS;
  oS = oS.replace(/[aAÁáÀàĂăÂâǍǎÅåÄäǞǟÃãĄąĀā]/,"a");
  oS = oS.replace(/[bBƀ]/,"b");
  oS = oS.replace(/[cCĆćĈĉČčĊċÇç]/,"c");
  oS = oS.replace(/[dDĎďĐđƉð]/,"d");
  oS = oS.replace(/[eEÉéÈèĔĕÊêĚěËëĖėĘęĒē]/,"e");
  oS = oS.replace(/[fFƑƒ]/,"f");
  oS = oS.replace(/[gGĞğĜĝǦǧĠġĢģǤǥ]/,"g");
  oS = oS.replace(/[hHĤĥĦħ]/,"h");
  oS = oS.replace(/[iIÍíÌìĬĭÎîǏǐÏïĨĩİĮįĪīıƗ]/,"i");
  oS = oS.replace(/[jJĴĵǰ]/,"j");
  oS = oS.replace(/[kKǨǩĶķ]/,"k");
  oS = oS.replace(/[lLĹĺĽľĻļŁłŁłƚ]/,"l");
  oS = oS.replace(/[nNŃńŇňÑñŅņ]/,"n");
  oS = oS.replace(/[oOÓóÒòŎŏÔôǑǒÖöŐőÕõØøǪǫǬǭŌōƠơƟ]/,"o");
  oS = oS.replace(/[rRŔŕŘřŖŗ]/,"r");
  oS = oS.replace(/[sSßŚśŜŝŠšŞş]/,"s");
  oS = oS.replace(/[tTÞþŤťŢţŦŧƫƮ]/,"t");
  oS = oS.replace(/[uUÚúÙùŬŭÛûǓǔŮůÜüǗǘǛǜǙǚǕǖŰűŨũŲųŪūƯư]/,"u");
  oS = oS.replace(/[wWŴŵ]/,"w");
  oS = oS.replace(/[yYÝýŶŷŸÿ]/,"y");
  oS = oS.replace(/[zZŹźŽžŻżƶ]/,"z");
  return oS;
}

function makeSearchRegex(word){
//  var sReg = word;
//  var sReg = getRegexPattern(word);

  var sReg = '';
  for (var i = 0; i < word.length; i++) {
    var ch = word[i];
    if (dEquiv.hasOwnProperty(ch))
      sReg += dEquiv[ch];
    else
      sReg += ch;
  }

  if (sReg.indexOf("*") != -1){
    if (sReg.indexOf("*") != 0){
      sReg = "[^\\w]" + sReg;
    } else {
      sReg = sReg.substring(1);
    }
    if (sReg.indexOf("*") != sReg.length - 1){
      sReg = sReg + "[^\\w]";
    } else {
      sReg = sReg.substring(0,sReg.length - 1);
    }
    if (sReg.indexOf("*") != 0 && sReg.indexOf("*") != sReg.length - 1){
      sReg = sReg.replace("*","(.*)");
    }
  } else {
    sReg = "[^\\w]"+sReg+"+[^\\w]";
  }

//alert(sReg);
  return sReg;
}
function hiLight(node,word,sReg,i) {

  if (node.hasChildNodes) {
    var hi_cn;
    for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
      hiLight(node.childNodes[hi_cn],word,sReg,i);
    }
  }
  if (node.nodeType == 3) {
    tempNodeVal = node.nodeValue.toLowerCase();
    tempWordVal = word.toLowerCase();
    var re = new RegExp(sReg,"gi");

//sReg = "([^\\w])("+sReg+")([^\\w])";


    var rMatch = tempNodeVal.match(re);

    if (rMatch != null){
      pn = node.parentNode;
      if (pn.className!= "sres"+i) {
        nv = node.nodeValue;
//Need to add 1 to match if using word boundaries as boundary is returned as first char
//        ni = tempNodeVal.indexOf(rMatch[0])+1;
//[^\\w]

//alert(sReg.substr(0,5));

        ni = tempNodeVal.indexOf(rMatch[0]);
        if (sReg.substr(0,5) == "[^\\w]"){ ni += 1; }

        before = document.createTextNode(nv.substr(0,ni));
        docWordVal = nv.substr(ni,word.length);
        after = document.createTextNode(nv.substr(ni+word.length));

//alert( ni+re+"\n"+nv.substr(0,ni)+"\n\n"+docWordVal+"\n\n"+nv.substr(ni+word.length));

        hiwordtext = document.createTextNode(docWordVal);
        hiword = document.createElement("span");
        hiword.className = "sres"+i;
        hiword.id = "srw"+sCounter;
        hiword.appendChild(hiwordtext);
        pn.insertBefore(before,node);
        pn.insertBefore(hiword,node);
        pn.insertBefore(after,node);
        pn.removeChild(node);

        hianchor = document.createElement("a");
        hianchor.name = "sr"+sCounter;
        hiword.appendChild(hianchor);
        sCounter++;
      }
    }
  }
}
window.onload=initPage;
