chat_working = false;

function submitenter(myfield,e)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  
  if (keycode == 13)
  {
   myfield.form.submit();
   return false;
  }
  else return true;
}
  
function findMouseInElem(elem, e)
{
  if (!e) var e = window.event;
  elem = $(elem);
  var screenpos = Position.page(elem);
  return { x: Event.pointerX(e) - screenpos[0], y: Event.pointerY(e) - screenpos[1] };
}

function pop_up(elem,str)
{
  var cum_xy = Position.cumulativeOffset(elem);
  var real_xy = Position.realOffset(elem);
  var x = cum_xy[0] - real_xy[0];
  var y = cum_xy[1]; // - real_xy[1];
  var dim = elem.getDimensions();
  var popup = $('popup');
  popup.style.left = (x + dim.width)+"px";
  popup.style.top = (y + dim.height)+"px";
  $('popup_text').innerHTML = str;
  popup.show();
}

function pop_down()
{
  $('popup').hide();
}

function magnify(elem, path)
{
  var cum_xy = Position.cumulativeOffset(elem);
  var real_xy = Position.realOffset(elem);
  var x = cum_xy[0] - real_xy[0] - 260;
  var y = cum_xy[1]; // - real_xy[1];
  var dim = elem.getDimensions();
  var div = $('magnify');
  div.style.backgroundImage = "url('" + path + "')";
  div.style.left = (x + dim.width)+"px";
  div.style.top = (y + dim.height)+"px";
  div.show();
}

function unmagnify()
{
  $('magnify').hide();
}

function isNickValid(nick)
{
  var reg = new RegExp("^[A-Za-z0-9_]+$");
  return reg.test(nick);
}

function isEmailValid(email)
{
  var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
  return (!reg1.test(email) && reg2.test(email));
}

function isPasswordValid(password)
{
  return password.length >= 4 && password.length <= 20;
}

function isLeapYear(year)
{
  return ( ((year)>0) && !((year)%4) && ( ((year)%100) || !((year)%400) ) );
}
  
// Returns # days in a given month
function monthDays(month,year)
{
  month = parseInt(month);
  year = parseInt(year);
  switch(month)
  {
    case 1: return 31;
    case 2: 
      if(year == 0 || isLeapYear(year)) 
        return 29; 
      else 
        return 28;
      break;
    case 3: return 31;
    case 4: return 30;
    case 5: return 31;
    case 6: return 30;
    case 7: return 31;
    case 8: return 31;
    case 9: return 30;
    case 10: return 31;
    case 11: return 30;
    case 12: return 31;
    default: return 31;
  }
}

function insertTextInto(fieldname, textToInsert)
{
  var myField = $(fieldname);
  // IE
  if (document.selection) 
  {
    myField.focus();

    // Text range at cursor position.
    sel = document.selection.createRange();
    // Replace range with text.
    sel.text = textToInsert;
  }
  // Mozilla/Firefox
  else if (myField.selectionStart || myField.selectionStart == '0') 
  {
    // Retrieve selection start and end.
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    // Insert text between substrings.
    myField.value = myField.value.substring(0, startPos)+ textToInsert + myField.value.substring(endPos, myField.value.length);
  }
  // No support.
  else 
  {
    myField.value += textToInsert;
  }
}

function sm(smiley)
{
  insertTextInto('message', smiley);
}

function getBubble(pe)
{
  var ajax = new Ajax.Request(
    "callback/getbubble.php",
    {method: 'post', evalScripts: true, parameters: "", onComplete: getBubble_Complete }
  );
}

function getBubble_Complete(xhr)
{
  if( xhr.responseText == "" ) return;
  var data; eval("data=" + xhr.responseText);
  $('bubble').hide();
  $('bubble_thumb').innerHTML = data.thumb;
  $('bubble_message').innerHTML = data.message;
  var offsetY =  window.pageYOffset
              || document.documentElement.scrollTop
              || document.body.scrollTop
              || 0;
  $('bubble').style.top = (offsetY + 20) + "px";
  $('bubble').style.left = "20px";
  Effect.Appear($('bubble'));
}

function submitChatEnter(myfield,e,chattee)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  
  if (keycode == 13)
  {
   sendChatMessage(chattee, myfield);
   return false;
  }
  else return true;
}

function makeChatSmiley(chattee, url, code)
{
  var img = Builder.node( "img", { src: url, style:'cursor:pointer', border:0, title: code } );
  img.onclick = function() { insertTextInto('chat_input_' + chattee, $(this).title); };
  return img;
}

function startchat(chattee)
{
  if( $('chat_' + chattee) != undefined) 
  {
    var chatmessages = $('chat_' + chattee).immediateDescendants()[1];
    return chatmessages;
  }
  var input = Builder.node( "input", { id:'chat_input_' + chattee, className: "input200", type: "text", maxlength: "200" }, [] );
  var throbber = Builder.node( "img", { id:'chat_throbber_' + chattee, src:'img/throbber_small.gif', border:0 } );
  var alink = Builder.node( "a", { id: 'chat_send_' + chattee, href: "#" }, [ ">>" ] );
  var aclose = Builder.node( "a", { href: "#" }, [
    Builder.node( "img", { src: "img/icons/close.gif", border: 0 }, [] )
  ]);
  var chatmessages = Builder.node( "div", { className: "chatbox_messages" }, [] );
  
  var imgs = []; 
  imgs.push(makeChatSmiley( chattee, 'img/smileys/normalsmiley.gif', ':-)' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/normalsad.gif', ':-(' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/biggrin.gif', ':-D' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/tongueout.gif', ':-P' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/wink.gif', ';-)' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/kiss.gif', ':-*' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/angry.gif', '}:-0' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/cool.gif', '8-)' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/footinmouth.gif', ':-!' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/sharptear.gif', ':\'-(' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/nospeak.gif', ':-X' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/sidesmile.gif', ':-/' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/angel.gif', 'O:-)' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/boxysad.gif', ':-[' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/blush.gif', '[blush]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/conf.gif', '[conf]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/inlove.gif', '[inlove]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/adore.gif', '[adore]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/innocent.gif', '[innocent]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/smoke.gif', '[smoke]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/yes.gif', '(Y)' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/no.gif', '(N)' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/musicnote.gif', '[music]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/heart.gif', '[heart]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/rose.gif', '[rose]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/coffee.gif', '[coffee]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/dog.gif', '[dog]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/banana.gif', '[banana]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/banana2.gif', '[banana2]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/banana3.gif', '[banana3]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/banana4.gif', '[banana4]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/banana5.gif', '[banana5]' ));
  imgs.push(makeChatSmiley( chattee, 'img/smileys/beer.gif', '[beer]' ));
  //imgs.push(makeChatSmiley( chattee, 'img/smileys/beat.gif', '[beat]' ));
  
  var chatbox = Builder.node("div", { id: "chat_" + chattee, className: "chatbox" }, [
    Builder.node( "div", { className: "chatbox_caption" }, [ 
      Builder.node( "div", { style: "float:right; margin-top:5px; margin-right:3px;" }, [
        aclose
      ]),
      chattee
    ]),
    chatmessages,
    Builder.node( "div", { className: "chatbox_smileys" }, [
      imgs
    ]),
    Builder.node( "div", { className: "chatbox_input" }, [
      Builder.node( "div", { id: 'chat_throbber_' + chattee, style: "float:right; display:none;" }, [ throbber ] ),
      input, alink
    ] )
  ]);
  
  input.onkeypress = function(event) { return submitChatEnter(input, event, chattee); };
  alink.onclick = function() { sendChatMessage(chattee, input); };
  aclose.onclick = function() { $("chat_" + chattee).remove(); return false; };
  
  $('body').appendChild(chatbox);
  
  var offsetY =  window.pageYOffset
              || document.documentElement.scrollTop
              || document.body.scrollTop
              || 0;
              
  chatbox.style.left = "15px";
  chatbox.style.top = (offsetY + 15) + "px";
  
  new Draggable(chatbox, { handle: "chatbox_caption" } );
  
  return chatmessages;
}

function sendChatMessage(chattee, input)
{
  if (chat_working == true) return;
  
  $('chat_throbber_' + chattee).show();
  $('chat_send_' + chattee).hide();
  
  chat_working = true;
  var message = input.value;
  input.value = "";
  if( message == null || message == "" ) return;
  var ajax = new Ajax.Request(
    "callback/sendchat.php",
    {method: 'post', evalScripts: true, parameters: "receiver=" + chattee + "&message=" + encodeURIComponent(message), onComplete: function(xhr) { sendChatMessage_Complete(xhr, chattee); } }
  );
}

function sendChatMessage_Complete(xhr,chattee)
{
  if( xhr.responseText == null || xhr.responseText == "" ) return;
  var data; eval("data=" + xhr.responseText);
  var chatmessages = startchat(chattee);
  chatmessages.innerHTML = data.messages;
  $('chat_throbber_' + chattee).hide();
  $('chat_send_' + chattee).show();
  chat_working = false;
}

function getChat()
{
  var ajax = new Ajax.Request(
    "callback/getchat.php",
    {method: 'post', evalScripts: true, parameters: "", onComplete: getChat_Complete }
  );
}

function getChatForSender(sender)
{
  var ajax = new Ajax.Request(
    "callback/getchatforsender.php",
    {method: 'post', evalScripts: true, parameters: "sender=" + sender, onComplete: getChat_Complete }
  );
}

function getChat_Complete(xhr)
{
  if( xhr.responseText == null || xhr.responseText == "" ) return;
  var data; eval("data=" + xhr.responseText);
  var chatmessages = startchat(data.sender);
  chatmessages.innerHTML = data.messages;
}
