var teh=new Object();
teh.focusBar=false;
teh.barUp=false;
teh.lastField=null;
teh.blurTimer=false;
teh.emotesUp=false;
teh.emoteDiv=null;
teh.fixedBarList=[];

teh.init = function (e)
{
  var elemList=[];
  var textareaList=document.getElementsByTagName("textarea");
  for(var i=0;i<textareaList.length;i++)
  {
    elemList.push(textareaList[i]);
  }
  var textList=document.getElementsByTagName("input");
  for(var i=0;i<textList.length;i++)
  {
    elem= textList[i];
    if(elem.type&&elem.type=="text")
    {
      elemList.push(elem);
    }
  }
  var regExp=/ (teh(_top|_left|_right|_bottom|_always|_never|_center|_focus|_noblock)+) /;
  while(elem=elemList.shift())
  {
    if(elem.className)
    {
      if(match=(" "+elem.className+" ").match(regExp))
      {
        teh.initElem(elem,match[1]);
      }
    }
  }
  addEvent(document.body,"mousedown",teh.doBodyOnMouseDown);
  addEvent(document.body,"mouseup",teh.doBodyOnMouseUp);
  addEvent(window,"load",teh.positionAllBars);
  addEvent(window,"resize",teh.positionAllBars);
//  addEvent(document.body,"resize",teh.positionAllBars);
  teh.buildEmoteDiv();
}

addOnDomLoadHandler(teh.init);

teh.doBodyOnMouseDown = function (e)
{
  teh.mouseDown=true;
}

teh.doBodyOnMouseUp = function (e)
{
  teh.mouseDown=false;
}

teh.initElem = function (elem,position)
{
  elem._teh=new Object;
  var c=elem._teh;  
  c.side='bottom';
  c.pos='center';
  c.when='focus';
  c.how='float';
  var parts=position.split(/_/);
  parts.shift();
  if(parts.length&&(parts[0].match(/^(top|bottom|left|right)$/)))
  {
    c.side=parts.shift();
  }
  if(parts.length&&(parts[0].match(/^(top|bottom|left|right|center)$/)))
  {
    c.pos=parts.shift();
  }
  if(parts.length&&(parts[0].match(/^(always|never|focus)$/)))
  {
    c.when=parts.shift();
  }
  if(parts.length&&(parts[0].match(/^(float|margin)$/)))
  {
    c.how=parts.shift();
  }
  if(c.when=="always")
  {
    var bar=teh.popUpBar(elem);
    teh.fixedBarList.push([bar,elem]);
  }
  addEvent(elem,"focus", teh.doOnFocus);
  addEvent(elem,"blur", teh.doOnBlur);
}

teh.popUpBar = function (what,div)
{
  var c=what._teh;
  var className="editpop ";
  var width='';
  // set vertical/horizontal
  if((c.side=='left')||(c.side=='right'))
  {
    className+="editpop_vert";
    width="30px";
  }
  else
  {
    className+="editpop_horiz";
    width="150px";
  }
  if(!div)
  {
    div=document.createElement("div");
    div.className=className;
    div.style.width=width;
    div.innerHTML="<button type=\"button\" title=\"Bold\"onclick=\"teh.wrapSelection('**','**');\"><b>B</b></button><button type=\"button\" title=\"Italic\" onclick=\"teh.wrapSelection('//','//');\"><i>I</i></button><button type=\"button\" title=\"Underline\" onclick=\"teh.wrapSelection('__','__');\"><u>U</u></button><button type=\"button\" title=\"Strikethrough\" onclick=\"teh.wrapSelection('==','==');\"><del>S</del></button><button type=\"button\" title=\"Insert Emoticon\" onclick=\"teh.popUpEmotes(event);\"><img src=\""+baseUrl+"/Assets/icons/emoticons/happy.gif\"></button>";
    div.style.visibility="hidden";
    document.body.appendChild(div);
  }
  else
  {
    div.style.width=width;
    div.className=className;
  }
  teh.positionBar(div,what);
  // set margin FINISH
  div.style.visibility="visible";
  return(div);
}

teh.positionAllBars = function ()
{
  if(teh.barUp)  teh.positionBar(teh.focusBar,teh.lastField);
  for(var i=0;i<teh.fixedBarList.length;i++)
  {
    teh.positionBar(teh.fixedBarList[i][0],teh.fixedBarList[i][1]);
  }
}

teh.positionBar = function (div,relTo)
{
  var popExtent=getNodeExtent(div);
  var extent=getNodeExtent(relTo);
  c=relTo._teh;
  div.style.top='';
  div.style.bottom='';
  div.style.right='';
  div.style.left='';
  switch(c.side)
  {
    case "top":
      div.style.top=(extent.y-5-popExtent.height)+"px";
      break;
    case "bottom":
      div.style.top=(extent.y+extent.height+4)+"px";
      break;
    case "left":
      div.style.left=(extent.x-popExtent.width-5)+"px";
      break;
    case "right":
      div.style.left=(extent.x+extent.width+4)+"px";
      break;
  }
  switch(c.pos)
  {
    case "top":
      div.style.top=extent.y+"px";
      break;
    case "bottom":
      div.style.top=(extent.y+extent.height-popExtent.height)+"px";
      break;
    case "left":
      div.style.left=extent.x+"px";
      break;
    case "right":
      div.style.left=(extent.x+extent.width-popExtent.width)+"px";
      break;
    case "center":
      if((c.side=="left")||(c.side=="right"))
      {
        div.style.top=(extent.y+Math.floor((extent.height-popExtent.height)/2))+"px";
      }
      else
      {
        div.style.left=(extent.x+Math.floor((extent.width-popExtent.width)/2))+"px";
      }
  }
}

teh.doOnFocus = function (e)
{
  if(teh.blurTimer)
  {
    if(this!=teh.lastField)
    {
      teh.popDownBar();
      teh.popDownEmotes();
    }
    clearTimeout(teh.blurTimer);
    teh.blurTimer=false;
  }
  teh.lastField=this;
  if(this._teh.when=='focus')
  {
    teh.barUp=true;
    teh.focusBar=teh.popUpBar(this,teh.focusBar);
  }
  teh.positionAllBars();
}

teh.doOnBlur = function (e)
{
  teh.blurTimer=setTimeout(teh.blurTimerFunc,100);
}

teh.blurTimerFunc = function (e)
{
  if(teh.mouseDown)
  {
    teh.blurTimer=setTimeout(teh.blurTimerFunc,100);
  }
  else
  {
    teh.blurTimer=false;
    teh.popDownBar();
    teh.popDownEmotes();
    teh.lastField=false;
  }
}

teh.popDownBar = function ()
{
  if(teh.focusBar)
  {
    teh.barUp=false;
    teh.focusBar.style.visibility="hidden";
  }
}

teh.getSelected = function (field)
{
  if(document.selection)
  {
    return(document.selection.createRange().text);
  }
  else if(field.selectionStart||field.selectionEnd)
  {
    return(field.value.substring(field.selectionStart, field.selectionEnd));
  }
  else
  {
    return '';
  }
}

teh.setSelected = function (field,value,endSelect)
{
  if(!endSelect) endSelect=0;
  if(document.selection)
  {
    field.focus();
    var range=document.selection.createRange();
    range.text=value;
    if(range.collapse)
    {
      switch(endSelect)
      {
        case -1:
	  range.move("character",-value.length);
	  range.select();
	  break;
        case -2:
          range.collapse(false);
	  range.select();
	  break;
        case 0:
	  break;
        default:
	  range.move("character",endSelect-value.length);
          range.select();
	  break;
      }
    }
    else
    {
      alert("range.collapse not defined!");
    }
  }
  else if(typeof(field.selectionStart=='Integer'))
  {
    var initStart=field.selectionStart;
    var pretext = field.value.substring(0, field.selectionStart);
    var posttext = field.value.substring(field.selectionEnd, field.value.length);
    field.value=pretext + value + posttext;
    if(field.setSelectionRange)
    {
      field.focus();  
      switch(endSelect)
      {
        case -1:
          field.setSelectionRange(initStart,initStart);
	  break;
        case -2:
          field.setSelectionRange(initStart+value.length,initStart+value.length);
	  break;
        case 0:
          field.setSelectionRange(initStart,initStart+value.length);
          break;
        default:
          field.setSelectionRange(initStart+endSelect,initStart+endSelect);
	  break;
      }
    }
  }
}

teh.insertAtSelection = function (field,value)
{
  var target=getElem(field);
  teh.setSelected(target,value,0);
}

teh.wrapSelection = function (prefix,suffix)
{
  var target=teh.lastField;
  if((!target)||!target.tagName||((target.tagName!='TEXTAREA')&&!((target.tagName=='INPUT')&&(target.type=='text'))))
  {
    return;
  }
  var selectionText=teh.getSelected(target);
  if(selectionText=='')
  {
    teh.setSelected(target,prefix+suffix,suffix.length);
  }
  else
  {
    var trimRegExp=/^(\s*)(.*?([\n\r]+.+?)*)(\s*)$/;
    var matches=trimRegExp.exec(selectionText);
    var text=matches[2];
    if((text.slice(0,2)==prefix)&&(text.slice(-suffix.length)==suffix))
    {
        teh.setSelected(target,matches[1]+matches[2].slice(prefix.length,-suffix.length)+matches[4],0);
    }
    else
    {
        teh.setSelected(target,matches[1] + prefix + matches[2] + suffix + matches[4],0);
    }
  }
}

teh.emoteList=[
[':)',"happy.gif","Smile"],
[':(',"sad.gif","Sad"],
[';)',"winking.gif","Wink"],
[':D',"biggrin.gif","Big Grin"],
[';;)',"battingeyelashes.gif","Batting Eyelashes"],
['>:D<',"bighug.gif","Hugs"],
[':-/',"confused.gif","Confused"],
[':x',"lovestruck.gif","Love"],
[':&quot;>',"blushing.gif","Blushing"],
[':p',"tongue.gif","Tongue"],
[':-*',"kiss.gif","Kiss"],
['=((',"brokenheart.gif","Broken Heart"],
[':o',"surprise.gif","Surprise"],
['X(',"angry.gif","Angry"],
[':>',"smug.gif","Smug"],
['8)',"cool.gif","Cool"],
[':-S',"worried.gif","Worried"],
['#:-S',"whew!.gif","Whew!"],
['>:)',"devil.gif","Devil"],
[':((',"crying.gif","Crying"],
[':))',"laughing.gif","Laughing"],
[':|',"straightface.gif","Straight Face"],
['/:)',"raisedeyebrow.gif","Raised Eyebrow"],
['+))',"rollingonthefloor.gif","Rolling on the Floor Laughing"],
['O:-)',"angel.gif","Angel"],
[':-b',"nerd.gif","Nerd"],
['=;',"talktothehand.gif","Talk to the Hand"],
['i-)',"sleepy.gif","Sleepy"],
['8-|',"rollingeyes.gif","Rolling Eyes"],
['l-)',"loser.gif","Loser"],
[':-&',"sick.gif","Sick"],
[':-$',"donttellanyone.gif","Don't Tell"],
['[-(',"hmmmph.gif","Hmmmph"],
[':o)',"clown.gif","Clown"],
['8-}',"silly.gif","Silly"],
['<:-p',"party.gif","Party"],
['(:|',"yawn.gif","Yawn"],
['=P~',"drooling.gif","Drooling"],
[':-?',"thinking.gif","Thinking"],
['#-o',"doh.gif","D'oh!"],
['=D>',"applause.gif","Applause"],
[':-ss',"nailbiting.gif","Nail Biting"],
['@-)',"hypnotized.gif","Hypnotized"],
[':^o',"liar.gif","Liar"],
[':-w',"waiting.gif","Waiting"],
[':-<',"sigh.gif","Sigh"],
['>:p',"phbbbbt.gif","Phbbbbt!"],
['<):)',"cowboy.gif","Cowboy"],
[':@)',"pig.gif","Pig"],
['3:-O',"cow.gif","Cow"],
[':(|)',"monkey.gif","Monkey"],
['~:>',"chicken.gif","Chicken"],
['@};-',"rose.gif","Rose"],
['%%-',"goodluck.gif","Good Luck"],
['**==',"flag.gif","Flag"],
['(~~)',"pumpkin.gif","Pumpkin"],
['~O)',"coffee.gif","Coffee"],
['*-:)',"idea.gif","Idea"],
['8-X',"skull.gif","Skull"],
['=:)',"bug.gif","Bug"],
['>-)',"alien.gif","Alien"],
[':-|',"frustrated.gif","Frustrated"],
['[-o<',"praying.gif","Praying"],
['$-)',"moneyeyes.gif","Money Eyes"],
[':-&amp',"whistling.gif","Whistling"],
['b-(',"feelingbeatup.gif","Beat Up"],
[':)>-',"peacesign.gif","Peace Sign"],
['[-x',"shameonyou.gif","Shame on You"],
["\\\\:D/","dancing.gif","Dancing"],
['>:/',"bringiton.gif","Bring it on"],
[';))',"heehee.gif","Hee Hee"],
['(%)',"yinyang.gif","Yin Yang"],
[':-@',"talkingtheearoff.gif","Talking the Ear off"],
['^:)^',"notworthy.gif","I'm not Worthy"],
[':-j',"justkidding.gif","Just Kidding"],
['(*)',"star.gif","Star"]
];

teh.emote = function (code)
{
  teh.popDownEmotes();
  var target=teh.lastField;
  if((!target)||!target.tagName||((target.tagName!='TEXTAREA')&&!((target.tagName=='INPUT')&&(target.type=='text'))))
  {
    return;
  }
  teh.setSelected(target," "+code+" ",-2);
}

teh.buildEmoteDiv = function ()
{
  if(!teh.emoteDiv)
  {
    teh.emoteDiv=document.createElement("div");
    teh.emoteDiv.id="emotePopUp";
    teh.emoteDiv.style.visibility="hidden";
    var innerHTML='';
    var emoteData;
    while(emoteData=teh.emoteList.shift())
    {
      var code=emoteData.shift();
      var gfx=emoteData.shift();
      var title=emoteData.shift();
      innerHTML+="<a href=\"javascript:teh.emote('"+code+"');\"><img src=\""+baseUrl+"/Assets/icons/emoticons/"+gfx+"\" title=\""+title+"\"></a>";
    }
    teh.emoteDiv.innerHTML=innerHTML;
    document.body.appendChild(teh.emoteDiv);
  }
}

teh.popUpEmotes = function (e)
{
  if(!teh.lastField)
  {
    return;
  }
  teh.lastField.focus();
  if(!teh.emoteDiv)
  {
    teh.buildEmoteDiv();
  }
  if(teh.emotesUp)
  {
    teh.popDownEmotes();
  }
  else
  {
    teh.emotesUp=true;
    var relPos=getNodeExtent(teh.lastField);
    var popSize=getNodeExtent(teh.emoteDiv);
    var left=relPos.x-Math.floor((popSize.width-relPos.width)/2);
    if(left<0) left=0;
    var top=relPos.y-Math.floor((popSize.height-relPos.height)/2);
    if(top<0) top=0;
    teh.emoteDiv.style.left=left+"px";
    teh.emoteDiv.style.top=top+"px";
    teh.emoteDiv.style.visibility="visible";
  }
}

teh.popDownEmotes = function ()
{
  if(teh.emotesUp)
  {
    teh.emotesUp=false;
    teh.emoteDiv.style.visibility="hidden";
  }
}
