//////////////////////
///// JSI COMMON /////
//////////////////////

var curTheme='business';
var soundPlay=true;
var tooltips = new Array();
var tooltipShowAnimation;
var tooltipHideAnimation;
var TooltipTopAnimation    = -1;
var TooltipLeftAnimation   = -1;
var TooltipWidthAnimation  = -1;
var TooltipHeightAnimation = -1;
var tooltipElement;
var tooltipIndex;
var jsiTimeoutId;
// Timer 0 is used for animations & system purposes, so DO NOT USE IT
var jsiTimeId  = new Array();
var jsiTimeCBF = new Array();

var logoutCountdownTime;
var _startX = 0; // mouse starting positions
var _startY = 0;
var _offsetX = 0; // current element offset
var _offsetY = 0;
var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove
var _postMouseUpCB = null;
var _postDragStartCB = null;

function $(id) { return document.getElementById(id); }

function jsiById (pId) {

 return document.getElementById (pId);

}

function jsiClearTimeout () {

   window.clearTimeout (jsiTimeoutId);
   clearTimeout (jsiTimeoutId);

}

function jsiClearTimeoutById (pId) {
var pTimerId;

   if (pId == 0) pTimerId = jsiTimeId[0];
   if (pId == 1) pTimerId = jsiTimeId[1];
   if (pId == 2) pTimerId = jsiTimeId[2];
   if (pId == 3) pTimerId = jsiTimeId[3];
   if (pId == 4) pTimerId = jsiTimeId[4];
   if (pId == 5) pTimerId = jsiTimeId[5];
   if (pId == 6) pTimerId = jsiTimeId[6];
   if (pId == 7) pTimerId = jsiTimeId[7];
   if (pId == 8) pTimerId = jsiTimeId[8];
   if (pId == 9) pTimerId = jsiTimeId[9];
   window.clearTimeout (pTimerId);
   clearTimeout (pTimerId);

}

function jsiGetOffsetTop (pElement) {
	var iReturnValue = 0;
	while( pElement != null ) {
		iReturnValue += pElement.offsetTop - pElement.scrollTop;
		pElement = pElement.offsetParent;
	}
	return iReturnValue;
}

function jsiGetOffsetLeft (pElement) {
	var iReturnValue = 0;
	while( pElement != null ) {
		iReturnValue += pElement.offsetLeft - pElement.scrollLeft;
		pElement = pElement.offsetParent;
	}
	return iReturnValue;
}

function jsiAddEvent (obj, type, fn) {

  if (obj.attachEvent) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent ('on'+type, obj[type+fn]);
  } else obj.addEventListener (type, fn, false);

}

function jsiRemoveEvent (obj, type, fn) {

  if (obj.detachEvent) {
    obj.detachEvent ('on'+type, obj[type+fn]);
    obj[type+fn] = null;
  } else obj.removeEventListener (type, fn, false);

}

function jsiRemoveElement (pElement) {

   if (document.getElementById(pElement) == null) return;
   document.getElementById(pElement).parentNode.removeChild(document.getElementById(pElement));

}

function jsiSetBrowserInfo() {

   document.forms['loginform'].elements['wb_application'].value = navigator.appName;
   document.forms['loginform'].elements['wb_code'].value        = navigator.appCodeName;
   document.forms['loginform'].elements['wb_version'].value     = navigator.appVersion;
   document.forms['loginform'].elements['wb_platform'].value    = navigator.platform;
   document.forms['loginform'].elements['wb_useragent'].value   = navigator.userAgent;
   document.forms['loginform'].elements['wb_widthheight'].value = "w:" + jsiClientWidth() + " h:" + jsiClientHeight();

}

function jsiIEVersion () {
var usrAgent = navigator.userAgent.toLowerCase();
// silinecek // usrAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3)".toLowerCase();
// if browser is IE returns the major version of the browser, if it is not IE returns 0 
if (usrAgent.indexOf("msie") >= 0) return parseInt (usrAgent[usrAgent.indexOf("msie")+5]);
   else return 0;
}

function jsiSetClass (pElement, pClass) {

   if (pElement == null) return;

   if (jsiIEVersion () == 7) {
      if (pElement.getAttribute("className") == null)
          pElement.setAttribute("className", pClass);
      else {
           // if element has not already have the class
           if (pElement.getAttribute("className").indexOf(pClass) < 0)
       	      pElement.setAttribute("className", pElement.getAttribute("className") + " " + pClass);
      }
   }
   else {
        if (pElement.getAttribute("class") == null)
            pElement.setAttribute("class", pClass);
        else {
             // if element has not already have the class
             if (pElement.getAttribute("class").indexOf(pClass) < 0)
                 pElement.setAttribute("class", pElement.getAttribute("class") + " " + pClass);
        }
   }

}

function jsiDelClass (pElement, pClass) {

   if (pElement == null) return;

   if (jsiIEVersion () == 7)
        pElement.setAttribute("className", pElement.getAttribute("className").replace(pClass, "")); 
   else pElement.setAttribute("class",     pElement.getAttribute("class").replace(pClass, ""));

}

function jsiGetClass (pElement) {

   if (pElement == null) return;

   if (jsiIEVersion () == 7)
        return (pElement.getAttribute("className")); 
   else return (pElement.getAttribute("class"));

}

function jsiGetURLParameter (name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp (regexS);
  var results = regex.exec (window.location.href);
  if (results == null)
     return "";
  else
     return results[1];
}

function jsiSetSelected (Id, Val) {

   sel = document.getElementById (Id);
   for (i=0; i<sel.options.length; i++) {
       if (sel.options[i].value == Val) {
          sel.selectedIndex = i;
       }
   }
}

function jsiGetSelectedValue (pId) {

   return jsiById(pId).options[jsiById(pId).selectedIndex].value;

}

function jsiGetSelectedText (pId) {

   return jsiById(pId).options[jsiById(pId).selectedIndex].text;

}


function jsiElementCount (pElement) {
var container;
var childCount = 0;

   if (document.getElementById (pElement) == null) return (0);
			container = document.getElementById (pElement);
   if (document.getElementById(pElement).childElementCount != undefined) childCount = container.childElementCount;
   else { // IE
        if (container.children) childCount = container.children.length;
        else { // Firefox 3.5-
             var child = container.firstChild;
             while (child) {
                   if (child.nodeType == 1 /*Node.ELEMENT_NODE*/) childCount++;
                   child = child.nextSibling;
             }
        }
   }
   return (childCount);
}


function jsiInit () {
var divElements = document.getElementsByTagName("div");
var divElement;
var divParentElement;
var jsiType;
var jsiBorder;
var jsiNo;
var jsiTooltip;
var jsiImage;
var imgElement,
    wrapperElement;


   jsiResetAutoLogout();

   if (document.addEventListener) {
       document.addEventListener("click",  jsiResetAutoLogout,  false);
   }
   else if (document.attachEvent) {
            document.attachEvent("onclick",  jsiResetAutoLogout);
        }
        else {
             document.onclick = jsiResetAutoLogout;
        }

   for (i=0; i < divElements.length;i++) {
       jsiType    = divElements[i].getAttribute('jsiType');
       jsiBorder  = divElements[i].getAttribute('jsiBorder');
       jsiNo      = divElements[i].getAttribute('jsiNo');
       jsiTooltip = divElements[i].getAttribute('jsiTooltip');

       if (jsiTooltip) {
       	 jsiAddEvent (divElements[i], "mouseover", function () { jsiShowTooltip (this); } );
       	 jsiAddEvent (divElements[i], "mouseout",  function () { jsiHideTooltip (this); } );
       }

       if (jsiType == 'widget') {
          if (divElements[i].className != "") {
             divElements[i].className += " border_" + jsiBorder;
          }
          else {
               divElements[i].className = "border_" + jsiBorder;
          }

          // create a wrapper border div
          divParentElement = jsiCreateElement ("div", "", "border", divElements[i]);
          divParentElement.style.height="100%";
          divParentElement.style.position="relative";

          // create div(s) for border parts
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_ul", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_um", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_ur", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_ml", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_mm", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_mr", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_ll", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_lm", divParentElement);
          jsiCreateElement ("div", "", "border_" + jsiBorder + "_lr", divParentElement);
       }

       if (jsiType == 'button') {
       	 jsiSetClass (divElements[i], 'btn' + jsiNo);
          jsiAddEvent (divElements[i], "mouseover", function () { jsiButtonMouseOver (this); } );
          jsiAddEvent (divElements[i], "mouseout",  function () { jsiButtonMouseOut  (this); } );
          divElements[i].style.cursor = "pointer";

       	 jsiImage = divElements[i].getAttribute('jsiImage');
       	 // if image file ise specified (jsiImage='.jpg'), this file is inserted into div as image object
       	 // filename will be 'btn' + no + '.jpg' 
       	 if (jsiImage) {
             imgElement = jsiCreateElement ("img", divElements[i].id + "_img", "btn" + jsiNo + "_img", divElements[i]);
             imgElement.src = "img/" + curTheme + "/btn" + jsiNo + jsiImage;
             imgElement.style.width  = "100%";
             imgElement.style.height = "100%";
       	 }
       	 // if image file is not sprcified, left, right, middle 
          else {
               jsiCreateElement ("div", "", "btn" + jsiNo + "_left",   divElements[i]);
               jsiCreateElement ("div", "", "btn" + jsiNo + "_middle", divElements[i]);
               jsiCreateElement ("div", "", "btn" + jsiNo + "_right",  divElements[i]);
          }
          // text division for a button is created in all cases
          divElement = jsiCreateElement ("div", divElements[i].id + "_text", "btn" + jsiNo + "_text",   divElements[i]);
          divElement.innerHTML = divElements[i].getAttribute('jsiText');
          // if button is not enable, disable it
          if (divElements[i].getAttribute('jsiEnable') == "false")
               jsiButtonEnable (divElements[i], false);
          else jsiButtonEnable (divElements[i], true);
       }
   }

   // create divisions for tooltip messages
   wrapperElement = jsiCreateElement ("div", "divTooltip", "tooltip", jsiById ("divTheme") );
   wrapperElement.style.visibility  = "hidden";
   
   divElement = jsiCreateElement ("div", "divTooltipShadow",  "tooltipShadow",  wrapperElement);
   divElement = jsiCreateElement ("div", "", "ul",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "um",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "ur",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "ml",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "mm",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "mr",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "ll",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "lm",    wrapperElement);
   divElement = jsiCreateElement ("div", "", "lr",    wrapperElement);
   divElement = jsiCreateElement ("div", "divTooltipClose", "close",    wrapperElement);
   divElement = jsiCreateElement ("div", "divTooltipArrow", "topright", wrapperElement);
   wrapperElement = jsiCreateElement ("div", "divTooltipContentWrapper", "tooltipContentWrapper", wrapperElement);
   divElement = jsiCreateElement ("div", "divTooltipContent", "tooltipContent", wrapperElement);

   // create division & image for 'wait loading message'
   divElement = jsiCreateElement ("div", "divLoading", "", jsiById ("divTheme") );
   divElement.style.visibility = "hidden";
   divElement.style.backgroundColor = "black";
   divElement.style.opacity = '0.4';
   divElement.style.filter  = 'alpha(opacity=40)';
   divElement.style.zIndex = 1000;
   divElement.style.top = 0;
   divElement.style.left = 0;
   divElement.style.width  = "100%";
   divElement.style.height = "100%";

   wrapperElement = jsiCreateElement ("div", "wrapperLoading", "", divElement);
   wrapperElement.style.left = ((jsiClientWidth () - 64) / 2) + "px";
   wrapperElement.style.top  = "10px";

   imgElement = jsiCreateElement ("img", "imgLoading", "", wrapperElement);
   imgElement.src = "img/all/wait.gif";
   imgElement.style.width  = "64px";
   imgElement.style.height = "64px";
   imgElement.style.position = "fixed";
   divElement.style.zIndex = 1001;

   divElements = document.getElementsByTagName("input");
   for (i=0; i < divElements.length;i++) {
       if (divElements[i].getAttribute('jsiTooltip')) {
       	 jsiAddEvent (divElements[i], "mouseover", function () { jsiShowTooltip (this); } );
       	 jsiAddEvent (divElements[i], "mouseout",  function () { jsiHideTooltip (this); } );
       }
   }

   divElements = document.getElementsByTagName("a");
   for (i=0; i < divElements.length;i++) {
       if (divElements[i].getAttribute('jsiTooltip')) {
       	 jsiAddEvent (divElements[i], "mouseover", function () { jsiShowTooltip (this); } );
       	 jsiAddEvent (divElements[i], "mouseout",  function () { jsiHideTooltip (this); } );
       }
   }

}

////////////////////////////
///// BUTTON FUNCTIONS /////
////////////////////////////

function jsiButtonMouseOver (pElement) {

   // animate if button ise enabled
   if (pElement.getAttribute('jsiEnable') == "true") {
      pElement.style.top  = (jsiGetStyleInt (pElement.id, "top")  + 1) + "px";
      pElement.style.left = (jsiGetStyleInt (pElement.id, "left") + 1) + "px";
      jsiSetClass (pElement, "mouseover");
      jsiSetClass ($(pElement.id+"_text"), "mouseover");
   }

}

function jsiButtonMouseOut (pElement) {

   // animate if button ise enabled
   if (pElement.getAttribute('jsiEnable') == "true") {
      pElement.style.top  = (jsiGetStyleInt (pElement.id, "top")  - 1) + "px";
      pElement.style.left = (jsiGetStyleInt (pElement.id, "left") - 1) + "px";
      jsiDelClass (pElement, "mouseover");
      jsiDelClass ($(pElement.id+"_text"), "mouseover");
   }

}

function jsiButtonEnable (pElement, pEnable) {
var pOnClick;

  pOnClick = pElement.getAttribute('jsiClick');
  if (pEnable) {
     pElement.style.cursor = "pointer";
     pElement.setAttribute('jsiEnable', 'true');
     if (jsiIEVersion () > 0 ) jsiRemoveProperty (pElement, "opacity");
        else                   pElement.style.opacity = "1";
     if (pOnClick) pElement.setAttribute ("onclick", pOnClick);
  }
  else {
       pElement.style.cursor = "";
  	    pElement.setAttribute('jsiEnable', 'false');
       if (jsiIEVersion () > 0) pElement.style.filter ="alpha(opacity=60)";
          else         pElement.style.opacity = "0.6";
       jsiDelClass (pElement, "mouseover");
       jsiDelClass ($(pElement.id+"_text"), "mouseover");
       if (pOnClick) pElement.setAttribute ("onclick", "");
  }

}

function jsiIsButtonEnabled (pElement) {
if (pElement.getAttribute('jsiEnable') == 'true') return true;
return false;
}

//////////////////////////

function jsiClientWidth (){
var myWidth = 0;

   if (typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      myWidth = window.innerWidth;
   } else if (document.documentElement && document.documentElement.clientWidth) {
             //IE 6+ in 'standards compliant mode'
             myWidth = document.documentElement.clientWidth;
          } else if (document.body && document.body.clientWidth) {
                    //IE 4 compatible
                    myWidth = document.body.clientWidth;
                 }
   return myWidth;
}

function jsiClientHeight (){
var myHeight = 0;

   if (typeof( window.innerHeight ) == 'number' ) {
      //Non-IE
      myHeight = window.innerHeight;
   } else if (document.documentElement && document.documentElement.clientHeight) {
             //IE 6+ in 'standards compliant mode'
             myHeight = document.documentElement.clientHeight;
          } else if (document.body && document.body.clientHeight) {
                    //IE 4 compatible
                    myHeight = document.body.clientHeight;
                 }
   return myHeight;
}

function jsiTotalWidth (pElementId){
var myWidth = 0;

   if (document.getElementById(pElementId) == null) return -1;

   myWidth  = document.getElementById(pElementId).clientWidth;
   if (document.getElementById(pElementId).style.marginLeft != "") 
      myWidth = myWidth + parseInt(document.getElementById(pElementId).style.marginLeft);
   if (document.getElementById(pElementId).style.marginRight != "") 
      myWidth = myWidth + parseInt(document.getElementById(pElementId).style.marginRight);
 
   return myWidth;
}

function jsiTotalHeight (pElementId){
var myHeight = 0;

   if (document.getElementById(pElementId) == null) return -1;
			
   myHeight  = document.getElementById(pElementId).clientHeight;
   if (document.getElementById(pElementId).style.marginTop != "") 
      myHeight = myHeight + parseInt(document.getElementById(pElementId).style.marginTop);
   if (document.getElementById(pElementId).style.marginBottom != "") 
      myHeight = myHeight + parseInt(document.getElementById(pElementId).style.marginBottom);

   return myHeight;
}

function jsiCreateElement (pType, pId, pClass, pParent) {
var currentElement;  // created element

   currentElement = document.createElement(pType);
   jsiSetClass(currentElement, pClass);
   currentElement.setAttribute("id", pId);
   if (pParent != null) {
      pParent.appendChild(currentElement);
   }

   return currentElement;
}

function jsiLoadingImage (pShow) {

   if (pShow == true) {
      jsiById ("divLoading").style.visibility = "visible";
      jsiById ("wrapperLoading").style.visibility = "visible";
   }
   else {
      jsiById ("divLoading").style.visibility = "hidden";
      jsiById ("wrapperLoading").style.visibility = "hidden";
   }
}

function jsiBackgroundEnable (pEnable) {

   if (pEnable) {
      jsiById ("divLoading").style.visibility = "hidden";
      jsiById ("wrapperLoading").style.visibility = "hidden";
   }
   else {
      jsiById ("divLoading").style.visibility = "visible";
      jsiById ("wrapperLoading").style.visibility = "hidden";
   }
}

function jsiLoadingImageForDiv (pElementId, pShow) {
var divElement;

   if (pShow == true) {
      // create division & image for 'wait loading message'
      divElement = jsiCreateElement ("div", pElementId + "Loading", "", jsiById (pElementId) );
      divElement.style.backgroundColor = "black";
      divElement.style.opacity = '0.4';
      divElement.style.filter  = 'alpha(opacity=40)';
      divElement.style.zIndex = 1000;
      divElement.style.top = 0;
      divElement.style.left = 0;
      divElement.style.width  = "100%";
      divElement.style.height = "100%";

      wrapperElement = jsiCreateElement ("div", pElementId + "wrapperLoading", "", divElement);
      wrapperElement.style.left = ((divElement.clientWidth - 64) / 2) + "px";
      wrapperElement.style.top  = "10px";

      imgElement = jsiCreateElement ("img", pElementId + "imgLoading", "", wrapperElement);
      imgElement.src = "img/all/wait.gif";
      imgElement.style.width  = "64px";
      imgElement.style.height = "64px";
      imgElement.style.position = "fixed";
      divElement.style.zIndex = 1001;
  }
  else jsiRemoveElement (pElementId + "Loading");

}

function jsiFlashPlayerIsInstalled () {

   // IE için kontrol
   if (window.ActiveXObject) {
      var control = null;
      try {
          control = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
      } catch (e) {
                  return false;
        }
      if (control) return true;
   }
   // NS ve FF için kontrol
   else {
        for (i=0; i<navigator.plugins.length; i++) {
            if (navigator.plugins[i].name.indexOf("Flash") > 0) return true;
        }
   }

   return false;

}

function jsiServerLog (pType, pId1, pId2, pParam) {
var currentElement;  // created element

   jsiRemoveElement ("logFrame");

   currentElement = document.createElement ("iframe");
   document.body.appendChild (currentElement);
   currentElement.style.visibility = "hidden";
   currentElement.setAttribute ("id", "logFrame");
   currentElement.setAttribute ("src", "/log.jsp?type="+pType+"&id1="+pId1+"&id2="+pId2+"&param="+pParam);

   // window.setTimeout("jsiRemoveElement ('logFrame');", 5000);

}

function jsiSetFocus(pId) {

   document.getElementById(pId).focus();

}

function jsiGetCSSProperty (pElement, pProperty) {

   if (pElement.currentStyle)
      var strValue = pElement.currentStyle[pProperty];
   else if (window.getComputedStyle)
      var strValue = document.defaultView.getComputedStyle(pElement,null).getPropertyValue(pProperty);
   return parseInt (strValue);

}

function jsiWait (pMiliSeconds) {

   for (var i=0; i<pMiliSeconds; i++) {
       for (var j=0; j<10000; j++) {
       }
   }

}

function jsiGetCSSRule (pClass, pStyle) {
var i, j, ss, styleValue;

// FF & NS
if (document.styleSheets[0].cssRules) {
   for (i=0; i<document.styleSheets[0].cssRules.length; i++) {
       ss = document.styleSheets[0].cssRules[i];
       // search thru import css files
       if (ss.styleSheet != null) {
          ss = ss.styleSheet;
          for (j=0; j<ss.cssRules.length; j++) {
              // search thru selector to find the requested clas name
              if (ss.cssRules[j].selectorText.indexOf (pClass) > 0) {
                 // if has a value return it, otherwise keep going on to find another class selector with same name
                 if (ss.cssRules[j].style[pStyle] != "") {
                 	  styleValue =  ss.cssRules[j].style[pStyle];
                    if (pStyle != "backgroundImage")
                    	    return (styleValue);
                    else return (styleValue.replace ("url(", "").replace (")", "").replace ("\"", "").replace ("\"", ""));
                 }
              }
          }
       }
   }
}

// IE
if (document.styleSheets[0].rules) {
   for (i=0; i<document.styleSheets[0].imports.length; i++) {
       ss = document.styleSheets[0].imports[i];
       for (j=0; j<ss.rules.length; j++) {
           // search thru selector to find the requested class name
           if (ss.rules[j].selectorText.indexOf(pClass) > 0) {
              // if has a value return it, otherwise keep going on to find another class selector with same name
              if (ss.rules[j].style[pStyle] != "") {
                 styleValue = ss.rules[j].style[pStyle];
                 if (pStyle != "backgroundImage")
                      return (styleValue);
                 else return (styleValue.replace ("url(", "").replace (")", "").replace ("\"", "").replace ("\"", ""));
              }
           }
       }
   }
}

return ("");

}

function jsiResetAutoLogout () {

   //jsiClearTimeoutById(0);
   // 5 dk sonraya logout set eder....
   logoutCountdownTime = new Date().getTime();
   showTimeLeft();
   // ekranda herhangi bir yer click'lenince tooltip gizlenir..
   // bu herhangi bir buton yada benzer bir obje click'lenince ilgili objeye ait tooltipin kaybolmasını da sağlar....
   if (tooltipElement) jsiHideTooltip (tooltipElement);
}

function showTimeLeft () {
var curTime = new Date().getTime(),
    diff;

  if (Session_LoginStatus == "OK") {
     if (jsiById ("timeleft")) {
        diff = Session_AutoLogout - (Math.floor((curTime - logoutCountdownTime) / 1000));
        if (diff <= 0) {
        	  document.location="/logout.jsp?mess=autologout";
        }
        else {
             jsiById ("timeleft").innerHTML = parseInt(diff / 60) + ":" + ("0" + (diff % 60)).right(2);
             window.setTimeout("showTimeLeft()", 500);
        }
     }
  }

}

function jsiLogout () {
document.location="/logout.jsp";
}

function jsiRemovePunctuation (pSentence) {

  pSentence = pSentence.replace (".", " ");
  pSentence = pSentence.replace (",", " ");
  pSentence = pSentence.replace ("-", " ");
  pSentence = pSentence.replace (";", " ");
  pSentence = pSentence.replace (":", " ");
  pSentence = pSentence.replace ("&", " ");
  pSentence = pSentence.replace ("?", " ");
  pSentence = pSentence.replace ("*", " ");
  pSentence = pSentence.replace ("     ", " ");
  pSentence = pSentence.replace ("    ", " ");
  pSentence = pSentence.replace ("   ", " ");
  pSentence = pSentence.replace ("  ", " ");
  return (pSentence);
  
}

function jsiRemoveAbbreviation (pSentence) {

  pSentence = pSentence.replace ("i'd",       "i would");
  pSentence = pSentence.replace ("he'd",      "he would");
  pSentence = pSentence.replace ("she'd",     "she would");
  pSentence = pSentence.replace ("we'd",      "we would");
  pSentence = pSentence.replace ("you'd",     "you would");
  pSentence = pSentence.replace ("they'd",    "they would");
  pSentence = pSentence.replace ("i'm",       "i am");
  pSentence = pSentence.replace ("you're",    "you're");
  pSentence = pSentence.replace ("he's",      "he is");
  pSentence = pSentence.replace ("she's",     "she is");
  pSentence = pSentence.replace ("we're",     "we are");
  pSentence = pSentence.replace ("you're",    "you are");
  pSentence = pSentence.replace ("they're",   "they are");
  pSentence = pSentence.replace ("it's",      "it is");
  pSentence = pSentence.replace ("can't",     "cannot");
  pSentence = pSentence.replace ("couldn't",  "could not");
  pSentence = pSentence.replace ("haven't",   "have not");
  pSentence = pSentence.replace ("hadn't",    "had not");
  pSentence = pSentence.replace ("hasn't",    "has not");
  pSentence = pSentence.replace ("didn't",    "did not");
  pSentence = pSentence.replace ("won't",     "will not");
  pSentence = pSentence.replace ("shouldn't", "should not");
  pSentence = pSentence.replace ("don't",     "do not");
  pSentence = pSentence.replace ("doesn't",   "does not");
  pSentence = pSentence.replace ("didn't",    "did not");
  pSentence = pSentence.replace ("what's",    "what is");
  pSentence = pSentence.replace ("isn't",     "is not");
  pSentence = pSentence.replace ("wasn't",    "was not");
  pSentence = pSentence.replace ("wouldn't",  "would not");
  pSentence = pSentence.replace ("mustn't",   "must not");
  pSentence = pSentence.replace ("i'll",      "i will");
  pSentence = pSentence.replace ("you'll",    "you will");
  pSentence = pSentence.replace ("i've",      "i have");
  pSentence = pSentence.replace ("weren't",   "were not");
  pSentence = pSentence.replace ("where's",   "where is");
  pSentence = pSentence.replace ("how's",     "how is");
  pSentence = pSentence.replace ("who's",     "who is");
  pSentence = pSentence.replace ("aren't",    "are not");
  pSentence = pSentence.replace ("that's",    "that is");

  return (pSentence);
  
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

String.prototype.left = function (n) {
    if (n <= 0) return "";
    else if (n > this.length)
              return this;
         else return this.substring(0,n);
}
String.prototype.right = function (n) {
    if (n <= 0) return "";
    else if (n > this.length)
            return this;
         else {
              var iLen = this.length;
              return this.substring(iLen, iLen - n);
         }
}

function jsiLoadDataFromServer (pProcessId, pSource, pParameters, pTime, pDiv, pFunctionCB) {
   // pProcessId  - show which timeoutId will be used
   // pSource     - jsp file to be run
   // pParameters - optional parameters to be passed to jsp file
   // pTime       - seconds to control if data is loaded
   // pDiv        - Id of division that the data to be used, function shows a loading image in this div
   // pFunctionCB - function to be called whhe the data is loaded, an array of loadded data is passed to this function

   jsiLoadingImageForDiv (pDiv, true);
   jsiRemoveElement ("reportFrame" + pProcessId);

   // create an dynamic iframe in the document and run the jsp with passed parameters
   currentElement = document.createElement ("iframe");
   document.body.appendChild (currentElement);
   currentElement.style.visibility = "hidden";
   currentElement.setAttribute ("id", "reportFrame" + pProcessId);
   if (pParameters != "") currentElement.setAttribute ("src", pSource + "?" + pParameters);
      else                currentElement.setAttribute ("src", pSource);

   jsiClearTimeoutById (pProcessId);
   // store the callback function which will be called after data is loaded
   window ['jsiTimeCBF[' + pProcessId + ']'] = pFunctionCB;
   // wait for data to be loaeded
   window ['jsiTimeId [' + pProcessId + ']'] = window.setTimeout ("jsiLoadDataFromServerWait (" + pProcessId + ", '" + pDiv + "')", pTime);

}

function jsiLoadDataFromServerWait (pProcessId, pDiv) {
var nodes,
    loadedData = new Array();

   // wait while data is loaded
   if (jsiById("reportFrame" + pProcessId) == null) {
      window.setTimeout("jsiLoadDataFromServerWait (" + pProcessId + ", '" + pDiv + "')", 200);      return;
   }

   // get the document of the dynamic frame
   tmpFrame = jsiById("reportFrame" + pProcessId).contentWindow.document;

   // wait while data is loaded
   if (tmpFrame.getElementById("dataLoaded") == null) {
      window.setTimeout("jsiLoadDataFromServerWait (" + pProcessId + ", '" + pDiv + "')", 200);      return;
   }

   // get all rows -- the data must be in a div with id "reportData"
   //              -- and rows must be in a <row></row> tags
   nodes = tmpFrame.getElementById("reportData").getElementsByTagName("div");

   // get columns for each row -- columns must be seperated by #-# characters
   for (i=0; i<nodes.length; i++) {
       loadedData[i] = nodes[i].innerHTML.split("#-#");
   }

   jsiLoadingImageForDiv (pDiv, false);
   // ??? jsiRemoveElement ("reportFrame" + pProcessId);
   // data is loaded, if callback function is defined call the CBF function 
   if (window ['jsiTimeCBF[' + pProcessId + ']']) window ['jsiTimeCBF[' + pProcessId + ']'] (loadedData);

}

function jsiConvertDigitToText (pNumber) {
var numbers=pNumber+'';
var strVal='';
var intVal=parseInt(numbers);
var lessThan20=true;

   if (intVal < 20) return jsiGetDigitsUntil20 (numbers);

   if (intVal < 100) {
      strVal  = jsiTwoDigitText (numbers[0]);
      strVal += jsiGetDigitsUntil20 (numbers[1]);
      return strVal;
   }

   if (intVal < 1000) {
   	strVal = jsiGetDigitsUntil20 (numbers[0]) + 'hundred';
      intVal = parseInt(numbers[1] + numbers [2], 10);
      if (intVal >= 20) {
         strVal += jsiTwoDigitText (numbers[1]);
         strVal += jsiGetDigitsUntil20 (numbers[2]);
      }
      else strVal += jsiGetDigitsUntil20 (intVal);
      return strVal;
   }

   return '(numbers > 999 are not supported yet)';
  
}

function jsiGetDigitsUntil20 (pDigit) {
var digitArray = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
return digitArray[parseInt(pDigit,10)];
}

function jsiTwoDigitText (pDigit) {
var digitArray = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
return digitArray[parseInt(pDigit,10)];
}

function jsiChangeNumbersToTextInString (pString) {
var i, j, intVal;

   for (i=0; i<pString.length; i++) {
   	 intVal = parseInt(pString.right(pString.length - i),10);
   	 if (intVal > 0) {
   	 	 pString = pString.replace (intVal+'', jsiConvertDigitToText (intVal) );
   	 }
   }
   return pString;

}

function InitDragDrop() {
document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;
}

function OnMouseDown(e) {
   // IE is retarded and doesn't pass the event object
   if (e == null) e = window.event;
   // IE uses srcElement, others use target
   var target = e.target != null ? e.target : e.srcElement;
   // for IE, left click == 1
   // for Firefox, left click == 0
   if ((e.button == 1 && window.event != null || e.button == 0) && target.className.indexOf('draggable') >= 0) {
   	 // grab the mouse position
   	 _startX = e.clientX;
   	 _startY = e.clientY;
   	 // grab the clicked element's position
   	 _offsetX = jsiToNumber(target.style.left);
   	 _offsetY = jsiToNumber(target.style.top);
   	 // bring the clicked element to the front while it is being dragged
   	 target.style.zIndex = 10000;
   	 // we need to access the element in OnMouseMove
   	 _dragElement = target;
   	 // tell our code to start moving the element with the mouse
   	 document.onmousemove = OnMouseMove;
   	 // cancel out any text selections
   	 document.body.focus();
   	 // prevent text selection in IE
   	 document.onselectstart = function () { return false; };
   	 // prevent IE from trying to drag an image
   	 target.ondragstart = function() { return false; };
   	 if (_postDragStartCB) _postDragStartCB (e);
   	 // prevent text selection (except IE)
   	 return false;
   }
}

function OnMouseMove(e) {
   if (e == null) var e = window.event;
   // this is the actual "drag code"
   _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
   _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
   jsiSetDragOver(_dragElement);
}

function OnMouseUp(e) {
var savedElement;

   if (_dragElement != null) {
      savedElement = _dragElement;

   	// we're done with these events until the next OnMouseDown
      jsiRemoveProperty (_dragElement, "z-index");
   	document.onmousemove = null;
   	document.onselectstart = null;
   	_dragElement.ondragstart = null;

   	// this is how we know we're not dragging
   	_dragElement = null;

      // if post function callback is defined call it with the element
      if (_postMouseUpCB) _postMouseUpCB (savedElement);
   }

}

function jsiToNumber(value) {
var n = parseInt(value);
return n == null || isNaN(n) ? 0 : n;
}

function jsiGetDroppedElement (pElement) {
var nodes,
    dragTop, dragLeft, dragBottom, dragRight,
    dropTop, dropLeft, dropBottom, dropRight,
    intersectWidht, intersectHeight, intersection,
    highestValue=0,
    droppedElement=null;

   nodes = document.getElementsByTagName("div");

   dragTop    = jsiGetOffsetTop (pElement);
   dragLeft   = jsiGetOffsetLeft (pElement);
   dragBottom = dragTop  + pElement.offsetHeight;
   dragRight  = dragLeft + pElement.offsetWidth;

   // get dropable elements
   for (i=0; i<nodes.length; i++) {
   	 if (nodes[i].className.indexOf('dropable') >= 0 ) {
          dropTop    = jsiGetOffsetTop (nodes[i]);
          dropLeft   = jsiGetOffsetLeft (nodes[i]);
          dropBottom = dropTop  + nodes[i].offsetHeight;
          dropRight  = dropLeft + nodes[i].offsetWidth;

          intersectWidth  = (dragTop   < dropTop)  ? dragBottom - dropTop  : dropBottom - dragTop;
          intersectHeight = (dragLeft  < dropLeft) ? dragRight  - dropLeft : dropRight  - dragLeft;
          if (intersectWidth > 0 && intersectHeight > 0) intersection = intersectWidth * intersectHeight;
             else intersection = 0;

    	    if (intersection > highestValue) {
    	    	 highestValue = intersection;
    	    	 droppedElement = nodes[i];
    	    }
   	 }
   }

   return droppedElement;
   
}

function jsiSetDragOver(pElement) {
var nodes;
var curElement=jsiGetDroppedElement (pElement);


   nodes = document.getElementsByTagName("div");

   // get dropable elements
   for (i=0; i<nodes.length; i++) {
   	 if (nodes[i].className.indexOf('dropable') >= 0 ) {
   	 	 // if element is current droppable element
   	 	 if (nodes[i] == curElement) {
   	 	 	 // if element has not dragover class, add it
    	 	    if (curElement.className.indexOf('dragover') < 0 ) jsiSetClass (curElement, "dragover");
   	 	 }
   	 	 // if element is not current droppable element
   	 	 else {
   	 	 	 // if element has dragover class, delete it
    	 	    if (nodes[i].className.indexOf('dragover') > 0 ) jsiDelClass (nodes[i], "dragover");
   	 	 }
   	 }
   }

}

function jsiGetStyle (pElementId,pStyle)
{
	var x = $(pElementId);
	if (x.currentStyle)
		var y = x.currentStyle[pStyle];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(pStyle);
	return y;
}

function jsiGetStyleInt (pElementId,pStyle)
{
	return jsiToNumber (jsiGetStyle (pElementId,pStyle) );
}

function jsiRGBColor(color_string)
{
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }
    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

}

function jsiCamelize (string) {
var oStringList = string.split('-');

   if (oStringList.length == 1) return oStringList[0];
   var camelizedString = string.indexOf('-') == 0
       ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
       : oStringList[0];

   for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
   }
   return camelizedString;
}

function jsiDisableSelection (target) {

   if (typeof target.onselectstart != "undefined") //IE route
      target.onselectstart = function () { return false; };
   else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
           target.style.MozUserSelect="none";
        else //All other route (ie: Opera)
	        target.onmousedown = function () { return false; };
   target.style.cursor = "default";

}

function jsiPlaySound (pId, pFile) {

   if ( $("div" + pFile) == null) jsiLoadSound (pId, pFile, 1);
      else jsiFlashPlayer(pFile).play();

}

function jsiLoadSound (pAudioId, pFile, pAuto) {
// pAuto could be 0 or 1 indicating false or true respectively
var soundElement,
    divElement;

   if ( $("allSound") == null) {
      soundElement = jsiCreateElement ("div", "allSound", "sound", document.body);
      soundElement.style.top = "-100px";
   }
   else soundElement = $("allSound");

   jsiRemoveElement ("div" + pAudioId);
   divElement = jsiCreateElement ("div", "div" + pAudioId, "divSound", soundElement);

   // if browser is IE
   if (jsiIEVersion () > 0) {
      divElement.innerHTML = 
        '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
        '   codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +
        '   width="150"' +
        '   height="37"' +
        '   id="' + pAudioId + '"' +
        '   align="">' +
        '   <param name=movie value="' + Session_StaticServer + '/niftyplayer.swf?file=' + Session_StaticServer + Session_PathSound + "/" + pFile + '&as=' + pAuto + '">' +
        '   <param name=quality value=high>' +
        '   <embed src="' + Session_StaticServer + '/niftyplayer.swf?file=' + Session_StaticServer + Session_PathSound + "/" + pFile + '&as=' + pAuto + '"' +
        '     quality=high' +
        '     width="150"' +
        '     height="37"' +
        '     name="' + pAudioId + 'emb"' +
        '     type="application/x-shockwave-flash"' +
        '     swLiveConnect="true"' +
        '     pluginspage="http://www.macromedia.com/go/getflashplayer">' +
        '   </embed>' +
        '</object>';
   }
   // if browser is not IE
   else {
   divElement.innerHTML = 
      '<OBJECT' +
      '	WIDTH="250"' +
      '	HEIGHT="50"' +
      '	CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"' +
      '	ID=' + pAudioId + '>' +
      '	<PARAM NAME="MOVIE" VALUE="' + Session_StaticServer + '/niftyplayer.swf?file=' + Session_StaticServer + Session_PathSound + "/" + pFile + '&as=' + pAuto + '">' +
      '	<PARAM NAME="LOOP" VALUE="false">' +
      '	<PARAM NAME="QUALITY" VALUE="high">' +
      '	<EMBED' +
      '     type="application/x-shockwave-flash"' + 
      '		NAME="' + pAudioId + '"' +
      '		src="' + Session_StaticServer + '/niftyplayer.swf?file=' + Session_StaticServer + Session_PathSound + "/" + pFile + '&as=' + pAuto + '"' + 
      '		WIDTH="250"' +
      '		HEIGHT="50"' +
      '		LOOP="false"' +
      '		QUALITY="high"' +
      '	</EMBED>' +
      '</OBJECT>';
   }

}

// Script for NiftyPlayer 1.7, by tvst from varal.org
// Released under the MIT License: http://www.opensource.org/licenses/mit-license.php

var jsiFlashHelper =
{

   /*
	movieIsLoaded : function (theMovie)
	{
		if (typeof(theMovie) != "undefined") return theMovie.PercentLoaded() == 100;
		else return
		false;
  },
  */

	getMovie : function (movieName)
	{
  	if (navigator.appName.indexOf ("Microsoft") !=-1)
  	       return window  [movieName];
	  else return document[movieName];
	}
};

function jsiFlashPlayer(name)
{
	this.obj = jsiFlashHelper.getMovie(name);

	// if (!jsiFlashHelper.movieIsLoaded(this.obj)) return;

	this.play = function () {
		if (soundPlay) this.obj.TCallLabel('/','play');
	};

	this.stop = function () {
		if (soundPlay) this.obj.TCallLabel('/','stop');
	};

	this.pause = function () {
		this.obj.TCallLabel('/','pause');
	};

	this.playToggle = function () {
		this.obj.TCallLabel('/','playToggle');
	};

	this.reset = function () {
		this.obj.TCallLabel('/','reset');
	};

	this.load = function (url) {
		this.obj.SetVariable('currentSong', url);
		this.obj.TCallLabel('/','load');
	};

	this.loadAndPlay = function (url) {
		this.load(url);
		this.play();
	};

	this.getState = function () {
		var ps = this.obj.GetVariable('playingState');
		var ls = this.obj.GetVariable('loadingState');

		// returns
		//   'empty' if no file is loaded
		//   'loading' if file is loading
		//   'playing' if user has pressed play AND file has loaded
		//   'stopped' if not empty and file is stopped
		//   'paused' if file is paused
		//   'finished' if file has finished playing
		//   'error' if an error occurred
		if (ps == 'playing')
			if (ls == 'loaded') return ps;
			else return ls;

		if (ps == 'stopped')
			if (ls == 'empty') return ls;
			if (ls == 'error') return ls;
			else return ps;

		return ps;

	};

	this.getPlayingState = function () {
		// returns 'playing', 'paused', 'stopped' or 'finished'
		return this.obj.GetVariable('playingState');
	};

	this.getLoadingState = function () {
		// returns 'empty', 'loading', 'loaded' or 'error'
		return this.obj.GetVariable('loadingState');
	};

	this.registerEvent = function (eventName, action) {
		// eventName is a string with one of the following values: onPlay, onStop, onPause, onError, onSongOver, onBufferingComplete, onBufferingStarted
		// action is a string with the javascript code to run.
		//
		// example: niftyplayer('niftyPlayer1').registerEvent('onPlay', 'alert("playing!")');

		this.obj.SetVariable(eventName, action);
	};

	return this;
}

function soundSet (pSound) {
var parElement,
    offElement;

   parElement = $('soundControl');
   offElement = $('soundStatus');
   if (pSound) {
      jsiSetClass (offElement, "soundOn");
      jsiDelClass (offElement, "soundOff");
      parElement.setAttribute ("title", "click to turn off game-sound");
      soundPlay = true;
   }
   else {
        jsiSetClass (offElement, "soundOff");
        jsiDelClass (offElement, "soundOn");
        parElement.setAttribute ("title", "click to turn on game-sound");
        soundPlay = false;
   }     
}

function jsiRemoveProperty (pElement, pProperty) {

   if (jsiIEVersion () > 0 && pProperty == "opacity") pProperty = "filter";

   if (pElement && pElement != null)
      if (pElement.style.removeProperty)
           pElement.style.removeProperty  (pProperty);
      else pElement.style.removeAttribute (jsiCamelize(pProperty));

}

function jsiReplace (pText, pOld, pNew) {
var newText;

   newText = pText;
   while (newText != newText.replace (pOld, pNew)) {
         newText = newText.replace (pOld, pNew);
   }
   return newText;
 
}

function jsiMouseOver (pId) {
if ($(pId).className.indexOf('mouseover') < 0) jsiSetClass ($(pId), 'mouseover');
}

function jsiMouseOut (pId) {
if ($(pId).className.indexOf('mouseover') >= 0) jsiDelClass ($(pId), 'mouseover');
}

document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
}; 

///////////////////////////////
///// LETTERSET FUNCTIONS /////
///////////////////////////////

function jsiLetterSet (pElementId, pText, pLetterSetNo, pBackground, pProperty, pShow, pCursor)
{
   // pLetterSetNo is number of the letters stored in /img/all/letter
   // pBackground is the number of the letters stored in /img/all/letter/background
   // pProperty is something like "size:75px;letter:50px;padding:12px;"
   //    size is the overall size of letter with background, considered as background-size
   //    letter is the size of the letter
   //    padding is the number of both left & top padding
   // pShow --> 0 - create but do not show
   //           1 - create & show --> background & letter
   //           2 - create & show --> only background

   //
   // attributes
   //

   this.id = pElementId;
   this.element = $(pElementId);
   this.wrapper;
   this.text = pText;
   this.letterSet = pLetterSetNo;
   this.backGround = pBackground;
   this.property = pProperty;
   this.show = pShow;
   this.size;
   this.letterSize;
   this.padding;
   this.index;
   this.cursor = pCursor;  // if true cursor image is created for each character....

   //
   // functions
   //

   this.createLetter   = jsiLetterSet_CreateLetter;
   this.setCurrent     = jsiLetterSet_SetCurrent;
   this.getCurrent     = jsiLetterSet_GetCurrent;
   this.disableCurrent = jsiLetterSet_DisableCurrent;
   this.getWord        = jsiLetterSet_GetWord;

   //
   // Constructor
   //
   
   jsiRemoveElement (this.id + "wrapper");
   this.wrapper = jsiCreateElement ("div", this.id + "wrapper", "", this.element);

   // extract individual properties
   var listProperties = this.property.split(";");
   for (var i=0; i<listProperties.length; i++) {
   	 listElements = listProperties[i].split(":");
   	 if (listElements [0] == "size")    this.size       = listElements [1];
   	 if (listElements [0] == "letter")  this.letterSize = listElements [1];
   	 if (listElements [0] == "padding") this.padding    = listElements [1];
   }

   // if pfrom is given, it is not null, set the proporty to the given value
   if (this.show && pText != null && pText != "") {
      for (var i=0; i<this.text.length; i++)
          this.createLetter (i, this.text[i], this.show);
   }

   this.element.setAttribute ("current", "0");
   this.element.setAttribute ("top", this.size);
   this.element.setAttribute ("cursor", "disabled");

}

function jsiLetterSet_CreateLetter (pIndex, pLetter, pShow) {
var parentElement, curElement, letterSizeName;

   if ($(this.id + pIndex) == null) {
      parentElement = jsiCreateElement ("div", this.id + pIndex, "letter_wrapper", this.wrapper);
      parentElement.style.height = (parseInt (this.size) + 32) + "px";
      parentElement.style.width = this.size;

      if (pLetter != " ") {
         if (this.backGround != "") {
            curElement = jsiCreateElement ("img", this.id + pIndex + "back", "letter_bg", parentElement);
            curElement.src = "img/all/letter/background/" + this.backGround + ".png";
            if (pShow == 0) curElement.style.visibility = "hidden";
            curElement.style.width  = this.size;
            curElement.style.height = this.size;
            jsiAddEvent (curElement,  "click", function () { jsiLetterSet_DoSetCurrent (this.id); } );
         }

         curElement = jsiCreateElement ("img", this.id + pIndex + "char", "letter_img", parentElement);
         if (pShow == 0 || pShow == 2) curElement.style.visibility = "hidden";
         letterSizeName = "50";
         if (this.letterSize >= 100) letterSizeName = "100";
         if (this.letterSize >= 150) letterSizeName = "150";
         if (pLetter[0] == '0' || pLetter[0] == '1' || pLetter[0] == '2' || pLetter[0] == '3' || pLetter[0] == '4' || pLetter[0] == '5' || pLetter[0] == '6' || pLetter[0] == '7' || pLetter[0] == '8' || pLetter[0] == '9')
              curElement.src = "img/all/number/" + this.letterSet + "/" + pLetter + "_" + letterSizeName + ".png";
         else curElement.src = "img/all/letter/" + this.letterSet + "/" + pLetter.toUpperCase() + "_" + letterSizeName + ".png";
         curElement.style.width  = this.letterSize;
         curElement.style.height = this.letterSize;
         curElement.style.left   = this.padding;
         curElement.style.top    = this.padding;
         jsiAddEvent (curElement,  "click", function () { jsiLetterSet_DoSetCurrent (this.id); } );

         if (this.cursor) {
            curElement = jsiCreateElement ("img", this.id + pIndex + "cursor", "letter_current", parentElement);
            curElement.style.visibility = "hidden";
            curElement.src = "img/business/arrow_current.png";
            curElement.style.width  = "32px";
            curElement.style.height = "32px";
            curElement.style.left   = ((parseInt (this.size) - 32) / 2) + "px";
            curElement.style.top    = this.size;
            curElement.setAttribute ("char", pLetter);
         }
      }   
   }
   else {
        jsiRemoveElement (this.id + pIndex + "char");
        if (pLetter != " ") {
           if (this.backGround != "") $(this.id + pIndex + "back").style.zIndex = "100";
           if (pShow == 0 || pShow == 2) curElement.style.visibility = "hidden";
           parentElement = $(this.id + pIndex);
           curElement = jsiCreateElement ("img", this.id + pIndex + "char", "letter_img", parentElement);
           letterSizeName = "50";
           if (this.letterSize >= 100) letterSizeName = "100";
           if (this.letterSize >= 150) letterSizeName = "150";
           if (pLetter[0] == '0' || pLetter[0] == '1' || pLetter[0] == '2' || pLetter[0] == '3' || pLetter[0] == '4' || pLetter[0] == '5' || pLetter[0] == '6' || pLetter[0] == '7' || pLetter[0] == '8' || pLetter[0] == '9')
                curElement.src = "img/all/number/" + this.letterSet + "/" + pLetter + "_" + letterSizeName + ".png";
           else curElement.src = "img/all/letter/" + this.letterSet + "/" + pLetter.toUpperCase() + "_" + letterSizeName + ".png";
           curElement.style.width  = this.letterSize;
           curElement.style.height = this.letterSize;
           curElement.style.left   = this.padding;
           curElement.style.top    = this.padding;
           jsiAddEvent (curElement,  "click", function () { jsiLetterSet_DoSetCurrent (this.id); } );
           jsiRemoveProperty ($(this.id + pIndex + "back"), "z-index");
           curElement.setAttribute ("char", pLetter);
       }
   }

}

function jsiLetterSet_SetCurrent (pIndex) {

   this.element.setAttribute ("cursor", "enabled");
   if (pIndex >= this.text.length) pIndex = 0;
   if (pIndex <                 0) pIndex = this.text.length - 1;

   // eğer kelime arası boşluk ise sonraki karaktere git
   if ( $(this.id + pIndex + "back") == null) {
      if (parseInt (this.element.getAttribute ("current")) < pIndex)
           pIndex = pIndex + 1;
      else pIndex = pIndex - 1;
   }

   jsiLetterSet_DoSetCurrent (this.id + pIndex + "back");

}

function jsiLetterSet_GetCurrent () {

   return parseInt (this.element.getAttribute ("current"));

}

function jsiLetterSet_DoSetCurrent (pId) {
var curElement, parentElement, curIndex, preIndex;

   if ($(pId) == null) return;

   if (parseInt(pId.right(6)) > 0) {
      curIndex = parseInt(pId.right(6));
      parentElement = $( pId.substring (0, pId.length - 6) );
      }
   else {
   	  curIndex = parseInt(pId.right(5));
        parentElement = $( pId.substring (0, pId.length - 5) );
   }
   preIndex = parentElement.getAttribute ("current");

   if (parentElement.getAttribute ("cursor") == "disabled") return;

   // hide previous cursor
   $(parentElement.id + preIndex + "cursor").style.visibility = "hidden";
   // save current index
   parentElement.setAttribute ("current", curIndex);
   // show current cursor
   $(parentElement.id + curIndex + "cursor").style.visibility = "visible";
   // animate cursor up & down 
   $(parentElement.id + curIndex + "cursor").style.top = parentElement.getAttribute ("top");
   jsiLetterSet_CurrentAnimation (parentElement.id + curIndex + "cursor", 1, 1);

}

function jsiLetterSet_CurrentAnimation (pId, pIteration, pStep) {
var curElement;

   $(pId).style.top = parseInt ($(pId).style.top) + pStep + "px";
 	pIteration += pStep;

   if (pIteration > 3) { pIteration = 3; pStep = -1; }
   if (pIteration < 0) { pIteration = 0; pStep = +1; }

   jsiClearTimeoutById (9);
   jsiTimeId [9] = window.setTimeout ("jsiLetterSet_CurrentAnimation ('" + pId + "', " + pIteration + ", " + pStep + ");", 200);

}

function jsiLetterSet_GetWord () {
var word = "", character="";

  for (var i=0; i<this.text.length; i++) {
  	   if ($("spellHiddenWord" + i + "char") == null) 
  	      word += " ";
      else {
      	  if ($("spellHiddenWord" + i + "char").getAttribute ("char") == null)
       	     word += " ";
      	  else word += $("spellHiddenWord" + i + "char").getAttribute ("char");
     }
  }

  return word;

}

function jsiLetterSet_DisableCurrent () {

   this.element.setAttribute ("cursor", "disabled");
   $(this.id + this.getCurrent () + "cursor").style.visibility = "hidden";
   jsiClearTimeoutById (9);

}

/////////////////////////
/// TOOLTIP FUNCTIONS ///
/////////////////////////

/* when loading a page jsiInit looks forwrd for tooltips and events automatically
 * if element is created dynamically, this procedure must be called to attach events
 */
function jsiAddTooltip (pId) {
jsiAddEvent ($(pId), "mouseover", function () { jsiShowTooltip (this); } );
jsiAddEvent ($(pId), "mouseout",  function () { jsiHideTooltip (this); } );
}

function jsiShowTooltip (pElement) {
var properties = pElement.getAttribute("jsiTooltip").split(";");
var parameters,
    parPosition,
    parCloseBox,
    parFadeIn,
    parFadeOut,
    parText,
    parWait,
    i,
    tipIndex,
    elementLeft,
    elementTop,
    elementWidth,
    elementHeight,
    tooltipWidth,
    tooltipHeight;

   // şimdili IE de göstme çünkü otomtik genişlik, yükseklik ayarlama çalışmıyor...
   if (jsiIEVersion () > 0 && jsiIEVersion () < 9) return;

   // set default values for parameters
   parCloseBox = "false";
   parFadeIn = "100";
   parFadeOut = "250";
   parWait = 0;

   // get parameters from the elements jsiTooltip attribute
   for (i=0; i<properties.length; i++) {
   	 parameters = properties[i].split(":");
   	 if (parameters[0].toLowerCase() == "position") parPosition = parameters[1].toLowerCase();
   	 if (parameters[0].toLowerCase() == "closebox") parCloseBox = parameters[1].toLowerCase();
   	 if (parameters[0].toLowerCase() == "fadein")   parFadeIn   = parameters[1].toLowerCase();
   	 if (parameters[0].toLowerCase() == "fadeout")  parFadeOut  = parameters[1].toLowerCase();
   	 if (parameters[0].toLowerCase() == "text")     parText     = jsiReplace (parameters[1], "#colon#", ":");
   	 if (parameters[0].toLowerCase() == "wait")     parWait     = parameters[1];
   }

   // put the text (can be html code) in to the tooltip
   if (parText) {
      if (parText[0] == "#") {
      	// get the html content from the database
      	tipIndex = jsiGetTooltipIndex (pElement, parText);
      	if (tipIndex >= 0) {
      		if (tooltips [tipIndex][2]) $("divTooltipContent").innerHTML = tooltips [tipIndex][2];
     	   }
      }
      else {
           $("divTooltipContent").innerHTML = parText;
      }
   }

   jsiLocateTooltip (pElement);

   // closebox parameter
   if (parCloseBox == "false") $("divTooltipClose").style.visibility = "hidden";

   // fadein parameter
   if (tooltipHideAnimation) Animator.stop (tooltipHideAnimation);
  	tooltipShowAnimation = Animator.animate ("divTooltip", "opacity", 0, 1, "", 100, parFadeIn, false, null, parWait);

   $("divTooltip").style.visibility = "visible";

}

function jsiLocateTooltip (pElement) {
var properties = pElement.getAttribute("jsiTooltip").split(";");
var parameters,
    parWidth, parHeight,
    i,
    tooltipWidth, tooltipHeight,
    elementLeft, elementTop, elementWidth, elementHeight,
    newLeft, newTop, newWidth, newHeight,
    oldLeft, oldTop, oldWidth, oldHeight,
    newClass;

   for (i=0; i<properties.length; i++) {
   	 parameters = properties[i].split(":");
   	 if (parameters[0].toLowerCase() == "position") parPosition = parameters[1].toLowerCase();
   	 if (parameters[0].toLowerCase() == "width")    parWidth    = parameters[1];
   	 if (parameters[0].toLowerCase() == "height")   parHeight   = parameters[1];
   }

   oldWidth = jsiGetStyleInt ("divTooltip", "width");
   oldHeight = jsiGetStyleInt ("divTooltip", "height");
   jsiRemoveProperty ($("divTooltip"), "width");
   jsiRemoveProperty ($("divTooltip"), "height");
   $("divTooltip").style.width  = "1000px";
   $("divTooltip").style.height = "500px";

   if (parWidth)  newWidth  = parWidth;
      else        newWidth  = (jsiGetStyleInt ("divTooltipContent", "width")  + 30);
   if (parHeight) newHeight = parHeight;
      else        newHeight = (jsiGetStyleInt ("divTooltipContent", "height") + 30);

   if (TooltipWidthAnimation  >= 0) Animator.stop (TooltipWidthAnimation);
   if (TooltipHeightAnimation >= 0) Animator.stop (TooltipHeightAnimation);
   TooltipWidthAnimation  = Animator.animate ("divTooltip", "width",   oldWidth,  newWidth,  "px", 50, 200, true);
   TooltipHeightAnimation = Animator.animate ("divTooltip", "height",  oldHeight, newHeight, "px", 50, 200, true);

   elementTop    = jsiGetOffsetTop  (pElement);
   elementLeft   = jsiGetOffsetLeft (pElement);
   elementWidth  = jsiTotalWidth (pElement.id);
   elementHeight = jsiTotalHeight (pElement.id);
   tooltipWidth  = newWidth;
   tooltipHeight = newHeight;

   // first position the tooltip according to the object and position specified
   if (parPosition == "bottomright") {
      newClass = "topleft";
      newLeft = (elementLeft + (elementWidth / 2) - 40);
      newTop  = (elementTop  + elementHeight + 15);
   }
   if (parPosition == "bottomleft") {
      newClass = "topright";
      newLeft = (elementLeft - tooltipWidth + (elementWidth / 2) + 40);
      newTop  = (elementTop  + elementHeight + 15);
   }
   if (parPosition == "topright") {
      newClass = "bottomright";
      newLeft = (elementLeft - tooltipWidth + (elementWidth / 2) + 50);
      newTop  = (elementTop  - tooltipHeight - elementHeight + 15);
   }
   if (parPosition == "topleft") {
      newClass = "bottomleft";
      newLeft = (elementLeft + (elementWidth / 2) - 40);
      newTop  = (elementTop  - tooltipHeight - 20);
   }
   if (parPosition == "righttop") {
      newClass = "lefttop";
      newLeft = (elementLeft + elementWidth + 15);
      newTop  = (elementTop  + (elementHeight / 2) - 30);
   }
   if (parPosition == "rightbottom") {
      newClass = "leftbottom";
      newLeft = (elementLeft + elementWidth  + 15);
      newTop  = (elementTop  - tooltipHeight + (elementHeight / 2) + 30);
   }
   if (parPosition == "lefttop") {
      newClass = "righttop";
      newLeft = (elementLeft - tooltipWidth - 20);
      newTop  = (elementTop  + (elementHeight / 2) - 30);
   }
   if (parPosition == "leftbottom") {
      newClass = "rightbottom";
      newLeft = (elementLeft - tooltipWidth - 20);
      newTop  = (elementTop  - tooltipHeight + (elementHeight / 2) - 30);
   }

 	jsiDelClass ($("divTooltipArrow"), jsiGetClass($("divTooltipArrow")) );
   jsiSetClass ($("divTooltipArrow"), newClass);
   if (TooltipTopAnimation  >= 0) Animator.stop (TooltipTopAnimation);
   if (TooltipLeftAnimation >= 0) Animator.stop (TooltipLeftAnimation);
   oldLeft = jsiGetStyleInt ("divTooltip", "left");
   oldTop  = jsiGetStyleInt ("divTooltip", "top");
   if (oldLeft == 0) oldLeft = newLeft;
   if (oldTop  == 0) oldTop  = newTop;
   TooltipLeftAnimation = Animator.animate ("divTooltip", "left",  oldLeft, newLeft, "px", 50, 200, true);
   TooltipTopAnimation  = Animator.animate ("divTooltip", "top",   oldTop,  newTop,  "px", 50, 200, true);

}

function jsiHideTooltip (pElement) {
var properties = pElement.getAttribute("jsiTooltip").split(";");
var parameters,
    parFadeOut,
    i;

   // şimdili IE de göstme çünkü otomtik genişlik, yükseklik ayarlama çalışmıyor...
   if (jsiIEVersion () > 0 && jsiIEVersion () < 9) return;

   // stop the show tooltip animation
   if (tooltipShowAnimation) Animator.stop (tooltipShowAnimation);

   // tooltip is not already displayed, this can happen if wait time is specified
   if ($("divTooltip").style.visibility == "hidden") return;

   for (i=0; i<properties.length; i++) {
   	 parameters = properties[i].split(":");
   	 if (parameters[0].toLowerCase() == "fadeout") parFadeOut = parameters[1].toLowerCase();
   }

   // fadein parameter
   if (parFadeOut != "") tooltipHideAnimation = Animator.animate ("divTooltip", "opacity", null, 0, "", 100, parFadeOut, false, jsiHideTooltipCB); 
      else               jsiHideTooltipCB ();

}

function jsiHideTooltipCB () {
$("divTooltip").style.visibility = "hidden";
}

function jsiGetTooltipIndex (pElement, pText) {
var pValues = pText.split ("#");
var i;

   // yeni eklenecek bir tooltip ise son indexe yükle...
   tooltipIndex = tooltips.length;
   
   // daha önce yüklendi mi bir bak bakalım...
   for (i=0; i<tooltips.length; i++) {
       if (pValues[1] == tooltips [i][0] && pValues[2] == tooltips [i][1])
          // daha önce yüklenebildi ise ...
          if (tooltips [i][2] != "$not_loaded$") return i;
          // daha önce yüklemeye çalıştı ama yükleyemedi ise ... bi daha dene...
          else tooltipIndex = i;
   }

  // tooltip is not loaded previously, so load it
  //$("divTooltipContent").style.width  = "64px";
  //$("divTooltipContent").style.height = "64px";
  $("divTooltipContent").innerHTML = "<img src='img/all/wait.gif' style='64px; height:64px;'>";
  $("divTooltip").style.width  = (jsiGetStyleInt ("divTooltipContent", "width")  + 30) + "px";
  $("divTooltip").style.height = (jsiGetStyleInt ("divTooltipContent", "height") + 30) + "px";
  tooltipElement = pElement;
  
  jsiLoadTooltip (pValues[1], pValues[2]);

  return -1;

}

function jsiLoadTooltip (pPage, pName) {

   tooltips [tooltipIndex] = new Array ();
   tooltips [tooltipIndex][0] = pPage;
   tooltips [tooltipIndex][1] = pName;
   tooltips [tooltipIndex][2] = "$not_loaded$";

   jsiLoadDataFromServer (0, 'q_tooltip.jsp', 'page=' + pPage + '&name=' + pName, 500, '', jsiLoadTooltipCB);

}

function jsiLoadTooltipCB (pData) {

   tooltips [tooltipIndex][2] = pData[0][0];
   tooltips [tooltipIndex][3] = pData[0][1];
   tooltips [tooltipIndex][4] = pData[0][2];
   
   $("divTooltipContent").innerHTML = pData[0][0];
   jsiLocateTooltip (tooltipElement);

}

