/////////////////////////////////
//           ajax im           //
//    AJAX Instant Messenger   //      
//    (c) 2005 Joshua Gross    //
// http://unwieldy.net/ajaxim/ //
//  Do not remove this notice  //
/////////////////////////////////

var user;
var pass;
var isAway=0;
var curSelected='';
var pingTimer;
var showOfflineBuddies=0;

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
//if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
//  xmlhttp = new XMLHttpRequest();
//}

try  {
    xmlhttp	=  window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err) {
   alert(err);
}


window.onunload = function() {
  // if(user.length > 0) logout()
}

function login() {
  // var username = document.getElementById('username').value;
  // var password = document.getElementById('password').value;
   var username = "wit";
   var password = "111111";
  
   
   xmlhttp.open('POST',"opu/ajax_im.php",false);
   xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

   xmlhttp.send("call=login&from="+username+"&pwd="+hex_md5(password));
	username=xmlhttp.responseText;
  
      user = username; pass = hex_md5(password);

	  
      setTimeout("winList['bl'].makeActive()", 100);

       winList['bl'].close();
	  setTimeout("ping(1)",500);
   //}
}

function logout() {
   xmlhttp.open('POST',"opu/ajax_im.php",false);
   xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

   xmlhttp.send("call=logout&from="+user+"&pwd="+pass);

   user = ''; pass = '';
   document.getElementById('showLogin').style.display = 'inline';
   document.getElementById('logout').style.display = 'none';
   document.getElementById('openNewIM').style.display = 'none';
   document.getElementById('changePwd').style.display = 'none';
   document.getElementById('awayMsgWin').style.display = 'none';
   showOfflineBuddies = 0;
   document.getElementById('showOfflineBuddies').value='Show Offline Buddies';
 try {
   window.location=window.location;
 } catch(e) { }

   clearTimeout(pingTimer);
}



function ping( getBuddyList ) {
   xmlhttp.open('POST',"opu/ajax_im.php",false);
   xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

   xmlhttp.send("call=ping&from="+user+"&pwd="+pass+"&away="+isAway);
   
   try { var xmlResponse = xmlhttp.responseXML.documentElement; } catch(e) { }
   
   
   if(xmlhttp.readyState == 4) {
   try {
      if(xmlhttp.responseText == 'not_logged_in') {
         
		 logout();
         return;
      }

   if(xmlResponse.getElementsByTagName('numMessages')[0].firstChild.data > 0) {
      var numMsgs = xmlResponse.getElementsByTagName('numMessages')[0].firstChild.data;
      for(i=0; i<numMsgs; i++) {
         var from = xmlResponse.getElementsByTagName('from')[i].firstChild.data;
         var data = xmlResponse.getElementsByTagName('data')[i].firstChild.data;

         if(!document.getElementById(from+"_im")) {
            createIMWindow(from, from);
            winList[from].open();
         }

         Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
         h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m; s = (s.length > 1) ? s : "0"+s;
         var curIM = document.getElementById(from+"_rcvd");
         curIM.innerHTML = curIM.innerHTML + "<span class=\"timestamp\">(" + h + ":" + m + ":" + s + ")</span> <b class=\"userB\">" + from + ":</b> " + data + "<br>\n";
         curIM.scrollTop = curIM.scrollHeight - curIM.clientHeight;
         if(curIM.innerHTML.toLowerCase().indexOf(user.toLowerCase()+':</b> (auto-reply:)') == -1 && isAway == 1) {
            document.getElementById(from+"_sendBox").value = '(Auto-Reply:) '+document.getElementById('awayMsg').innerHTML;
            sendMessage(from);
         } else {
            if(winCtrl.active != winList[from]) Effect.Pulsate(from+"_titleBar");
         }
      }
   }

   if(getBuddyList == 1) {
      var kill_bl = getElementsByCondition(function(el){if(el.className=='view'){destroyIMWindow(el.id);return el}});
      var numBuddies = xmlResponse.getElementsByTagName('numBuddies')[0].firstChild.data;
      for(i=0; i<numBuddies; i++) {
         var buddy = xmlResponse.getElementsByTagName('user')[i];
         addBuddyToList(buddy.firstChild.data);
         if(buddy.getAttribute('status') == 'offline') {
            document.getElementById(buddy.firstChild.data+"_blItem").style.display='none';
            document.getElementById(buddy.firstChild.data+"_blImg").src = "opu/images/offline.png"  
         } else if(buddy.getAttribute('status') == 'away') {
            document.getElementById(buddy.firstChild.data+"_blImg").src = "opu/images/away.png" 
         }             
      }
   } else {
      var numBuddies = xmlResponse.getElementsByTagName('numBuddies')[0].firstChild.data;
      for(i=0; i<numBuddies; i++) {
         var buddy = xmlResponse.getElementsByTagName('user')[i];
         if(buddy.getAttribute('status') == 'offline') {
            if(showOfflineBuddies==0) {
               document.getElementById(buddy.firstChild.data+"_blItem").style.display='none';
            } else {
               document.getElementById(buddy.firstChild.data+"_blItem").style.display='block';
            }
            document.getElementById(buddy.firstChild.data+"_blImg").src = "opu/images/offline.png";
         } else if(buddy.getAttribute('status') == 'away') {
            document.getElementById(buddy.firstChild.data+"_blItem").style.display='block';
            document.getElementById(buddy.firstChild.data+"_blImg").src = "opu/images/away.png";            
         } else {
            document.getElementById(buddy.firstChild.data+"_blItem").style.display='block';
            document.getElementById(buddy.firstChild.data+"_blImg").src = "opu/images/online.png";
         }
      }
   }
   }
   catch(e) {
   }
   }

   pingTimer = setTimeout("ping(0)",5500);
}

function sendMessage( winName ) {
  if(xmlhttp.readyState != 2 && xmlhttp.readyState != 3) {
      xmlhttp.open('POST',"opu/ajax_im.php",false);
      xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

      xmlhttp.send("call=send&from="+user+"&pwd="+pass+"&recipient="+winName+"&msg="+encodeURIComponent(document.getElementById(winName+"_sendBox").value.replace(/&/g, "<amp>")));

      if(xmlhttp.responseText == 'sent') {
         var sentText = document.getElementById(winName+"_sendBox").value;
         document.getElementById(winName+"_sendBox").value = '';
         var rcvdBox = document.getElementById(winName+"_rcvd")
         Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds());
         h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m; s = (s.length > 1) ? s : "0"+s;
         rcvdBox.innerHTML = rcvdBox.innerHTML + "<span class=\"timestamp\">(" + h + ":" + m + ":" + s + ")</span> <b class=\"userA\">" + user + ":</b> " + sentText + "<br>\n" 
         rcvdBox.scrollTop = rcvdBox.scrollHeight - rcvdBox.clientHeight;
      } else if(xmlhttp.responseText == 'not_online') {
         var rcvdBox = document.getElementById(winName+"_rcvd")
         rcvdBox.innerHTML = rcvdBox.innerHTML + '<span style="color:#FF0000"><b>Ошибка: Пользователь не в сети.</b></span><br>';
         rcvdBox.scrollTop = rcvdBox.scrollHeight - document.getElementById(winName+"_im").clientHeight;
      } else if(xmlhttp.responseText == 'not_logged_in') {
         logout();
      } else {
         alert('An error occured while sending your message.');
      }
      document.getElementById(winName+"_sendBox").focus();
  }
}

function newIMWindow() {
   if(document.getElementById('sendto').value.replace(/^\s*|\s*$/g,"").length > 0) {
      var toWhom = document.getElementById('sendto').value;

      if(!document.getElementById(toWhom+'_im')) {
         createIMWindow(toWhom, toWhom);
      }
      document.getElementById('sendto').value = '';
      winList[toWhom].open();
      document.getElementById(toWhom+"_sendBox").focus();
      winList['newIM'].close();
   } else {
      alert('Please enter a proper username.');
   }
}

function createIMWindow( name, title ) {
   var newIM = document.createElement('div');
   newIM.style.display = 'block';
   newIM.id = name+"_im";
   newIM.className = 'window';
   newIM.style.left = Math.round(Math.random()*(browserWidth()-360))+'px';
   newIM.style.top  = Math.round(Math.random()*(browserHeight()-400))+'px';
   newIM.style.width= '310px';

   var titlebar = document.createElement('div');
   newIM.appendChild(titlebar);
   titlebar.className = "titleBar";
   titlebar.innerHTML = '<span class="titleBarText" id="'+name+'_titleBar">'+title+'</span><img class="titleBarButtons" alt="" src="opu/images/buttons.gif" usemap="#'+name+'_map" /><map id="'+name+'_map" name="'+name+'_map"><area shape="rect" coords="0,0,15,13"  href="" alt="" title="Minimize" onclick="this.parentWindow.minimize();return false;" /><area shape="rect" coords="16,0,31,13" href="" alt="" title="Restore" onclick="this.parentWindow.restore();return false;" /><area shape="rect" coords="34,0,49,13" href="" alt="" title="Close" onclick="this.parentWindow.close();destroyIMWindow('+"'"+name+"_im'"+');return false;" /></map>';

   var clientArea = document.createElement('div');
   newIM.appendChild(clientArea);
   clientArea.className = "clientArea";
   clientArea.setAttribute("style", "height:335px;text-align:center;");

   var rcvdMsgs = document.createElement('div');
   clientArea.appendChild(rcvdMsgs);
   rcvdMsgs.className = "rcvdMessages";
   rcvdMsgs.id = name+"_rcvd";

   clientArea.innerHTML = clientArea.innerHTML + "\n" + '<textarea id="'+name+'_sendBox" onkeypress="keyHandler(event,'+"'"+name+"'"+');"></textarea>';

   clientArea.innerHTML = clientArea.innerHTML + "\n" + '<br /><input type="submit" value="ОТПРАВИТЬ" onclick="sendMessage('+"'"+name+"'"+');return false;" />';
   
   ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
   document.body.insertBefore(newIM);
  }else{
   document.body.insertBefore(newIM,document.body.nextSibling);
  };
  winList[name] = new Window(newIM);
}

function keyHandler( e, name ) {
   var asc = document.all ? event.keyCode : e.which;
   
   if(asc == 13) {
      sendMessage(name);
   }
   return asc != 13;
}

function destroyIMWindow( name ) {
   var toKill = document.getElementById(name);
   toKill.parentNode.removeChild(toKill);
}

function addBuddyToList( username ) {
   var buddyList = document.getElementById('buddylist');

   buddyList.innerHTML = buddyList.innerHTML + '<li id="'+username+'_blItem" class="view buddyli" onselectstart="return false;" onclick="'+"if(curSelected.length>0){var old=document.getElementById(curSelected+'_blItem');old.style.background='#fff';old.style.color='#333';};this.style.background='#47649a';this.style.color='#fff';curSelected='"+username+"';"+'" ondblclick="if(curSelected.length>0){if(!document.getElementById(curSelected+\'_im\')){createIMWindow(curSelected, curSelected);winList[curSelected].open();document.getElementById(curSelected+\'_sendBox\').focus();};};return false;"><img src="opu/images/online.png" width="10" height="10" alt="" id="'+username+'_blImg">&nbsp;'+username+'</li>';

   refreshDrag();
}

function deleteBuddyFromList( username ) {
   var buddyToRmv = document.getElementById(username+"_blItem");
   buddyToRmv.parentNode.removeChild(buddyToRmv);
   curSelected='';
   saveBuddyList();
}

function addNewBuddyToList( username ) {
   var buddyList = document.getElementById('buddylist');

   if(serializeList(buddyList).indexOf(username+',')==-1) {
      buddyList.innerHTML = buddyList.innerHTML + '<li id="'+username+'_blItem" class="view" onselectstart="return false;" onclick="'+"if(curSelected.length>0){document.getElementById(curSelected+'_blItem').style.background='#fff';};document.getElementById('"+username+"_blItem').style.background='#ccc';curSelected='"+username+"';"+'" ondblclick="if(curSelected.length>0){createIMWindow(curSelected, curSelected);winList[curSelected].open();document.getElementById(curSelected+\'_sendBox\').focus();};return false;"><img src="opu/images/offline.png" width="5" height="5" alt="" id="'+username+'_blImg">&nbsp;'+username+'</li>';

      refreshDrag();
      winList['addNewBuddy'].close();
      document.getElementById('newBuddyUsername').value = '';
      saveBuddyList();
   } else {
      alert('That username is already on your buddy list!');
   }
}


// FUNCTIONS BORROWED FROM "tool-man" JS CLASSES (http://tool-man.org) //
function serializeList( list ) {
   var items = list.getElementsByTagName("li")
   var array = new Array()
   for (var i = 0, n = items.length; i < n; i++) {
      var item = items[i]
      array.push(_identifier(item))
      }
   return array.join(',')
}

function _identifier( item ) {
   var identifier

   identifier = trim(item.getAttribute("id"))
   if (identifier != null && identifier.length > 0) return identifier;
	
   identifier = trim(item.getAttribute("itemID"))
   if (identifier != null && identifier.length > 0) return identifier;
		
   return trim(item.innerHTML)
}
// END BORROWED FUNCTIONS //

function trim( text ) {
   if(text==null) return null;
   return text.replace(/^[ \t]+|[ \t]+$/g, "");
}


function setStatus(status) {
   if(status==1) { // away
      isAway=1;
      document.getElementById('awayMsg').innerHTML = document.getElementById('setAwayMsgText').value;
      document.getElementById('setAwayMsgText').value='';
      document.getElementById('imaway').style.display = 'none';
      document.getElementById('changemsg').style.display = 'inline';
      document.getElementById('imback').style.display = 'inline';
   } else { // back
      isAway=0;
      winList['awayWindow'].close();
      document.getElementById('imaway').style.display = 'inline';
      document.getElementById('imback').style.display = 'none';
      document.getElementById('changemsg').style.display = 'none';
      document.getElementById('setAwayMsgText').value = document.getElementById('awayMsg').innerHTML;
      document.getElementById('awayMsg').innerHTML = '';
   }
}

function browserWidth() {
   if (self.innerWidth) {
	return self.innerWidth;
   } else if (document.documentElement && document.documentElement.clientWidth) {
	return document.documentElement.clientWidth;
   } else if (document.body) {
	return document.body.clientWidth;
   }
   return 630;
}

function browserHeight() {
   if (self.innerWidth) {
	return self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientWidth) {
	return document.documentElement.clientHeight;
   } else if (document.body) {
	return document.body.clientHeight;
   }
   return 470;
}

function randomNumber( max ) {
   var ranNum= Math.round(Math.random()*max);
   return ranNum;
}

function checkEmailAddr( email ) {
   var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   if (filter.test(email)) return true;
   else return false;
}

function getElementsByCondition( condition, container ) {
   container = container||document
   var all = container.all||container.getElementsByTagName('*')
   var arr = []
   for(var k=0;k<all.length;k++) {
      var elm = all[k]
      if(condition(elm,k))
         arr[arr.length] = elm
   }
   return arr
}

function getElementsByClass(node,searchClass,tag) {
   var classElements = new Array();
   var els = node.getElementsByTagName(tag); // use "*" for all elements
   var elsLen = els.length;
   var pattern = new RegEx("\\b"+searchClass+"\\b");
   for (i = 0, j = 0; i < elsLen; i++) {
      if ( pattern.test(els[i].className) ) {
         classElements[j] = els[i];
         j++;
      }
   }
   return classElements;
}

String.prototype.isAlphaNumeric = function () {return /^[a-z0-9_\d]+$/.test (this)}
