/*--------------------------------------------
 *  (c) 2007 CrossBrowserAjax, version 1.10
 *  Type: Compressed
 *--------------------------------------------*/
var http_request = false;
var http_get_request = false;
var tb_last_reply = 0;
var tbDivHMTL = new Array();
var tbLastRowID = new Array();

function cbaDOM(){this.removeElement=function(_element){_element.parentNode.removeChild(_element);};this.createElement=function(_parent,_type,_property,_text){var el=document.createElement(_type);for(var k in _property){var keys=k.split('.');if(keys.length==2){el[keys[0]][keys[1]]=_property[k];}else{el[k]=_property[k];}}if(_text!='')el.innerHTML=_text;_parent.appendChild(el);return el;};this.createScript=function(_parent,_id,_request){var span=this.createElement(_parent,'span',{'style.display':'none','id':_id},'%<s'+'cript></'+'script>');setTimeout(function(){var _script=span.getElementsByTagName('script')[0];_script.type='text/javascript';_script.src=_request;},5);}}function cbaCache(buffer_size,length_ct){this._rct=function(_request,_length){var control=0;var start=Math.floor(_request.length/_length);if(start<1)start=1;for(var i=_request.length;i>0;i-=start){control+='                                  !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~???S??Z???s??zY ???ค?ฆง?ฉ?ซฌญฎ?ฐฑ???ตถท???ป????AAAAAA?CEEEEIIII?NOOOOO?OUUUUY??aaaaaa?ceeeeiiii?nooooo?ouuuuy?y'.indexOf(_request.charAt(i));}return control;};this._search=function(_request){var _hash=this._rct(_request,this._length_ct);for(i in this._cache){if(this._cache[i][0]==_hash&&this._cache[i][1]==_request){this._search_buffer=this._data_cache[i];return true;}}return false;};this._add=function(_request,_data){if(this._cache_index>=this._buffer_size){this._cache_index=0;}var _hash=this._rct(_request,this._length_ct);this._cache[this._cache_index]=[_hash,_request];this._data_cache[this._cache_index]=_data;this._cache_index++;};this._init=function(buffer_size,length_ct){this._buffer_size=buffer_size;this._length_ct=length_ct;this._cache=new Array();this._data_cache=new Array();this._cache_index=0;this._search_buffer=null;};this._init(buffer_size,length_ct);}function cbaRequest(){this._init=function(){this._handler_error=true;if(this._handler_error){window.onerror=this.cbaJsError;}this._parent_id_name='_cba_parent_id';this._url_id='_cba_request_id';this._id_prefix='_cba_pack_';this.dom=new cbaDOM();this._parent_element=this.createParentElement();this._requests=new Array();this._caching_enabled=true;if(this._caching_enabled){this._buffer_size=25;this._length_ct=100;this.cache=new cbaCache(this._buffer_size,this._length_ct);}};this.cbaJsError=function(_message,_url,_line){var _file="File: "+_url+" :: "+_line+"\n";var _title="There was an error on this page.\n--------------------------\n";var _error=_title;_error+="Error: "+_message+"\n";_error+=_file;if(_message.indexOf('unterminated string literal')+_message.indexOf('missing ;')+_message.indexOf('Syntax error')>-3){_error+='--------------------------\nRecommendation:\n   Check response from the server.\n   He may return incorrect JavaScrip.';}alert(_error);};this.createParentElement=function(){if(document.getElementById(this._parent_id_name)){return document.getElementById(this._parent_id_name);}else{return this.dom.createElement(document.body,'div',{'id':this._parent_id_name},'');}};this.query=function(_url,_callback){if(arguments.length>2){var _use_cache=arguments[2];}else{var _use_cache=true;};if(_use_cache&&(this.cache&&this.cache._search(_url))){this.answer=this.cache._search_buffer;if(_callback instanceof Function)_callback();}else{var _id=this._requests.push({'callback':_callback,'request':_url})-1;if(_url.indexOf('?')==-1){_url+='?';}else{_url+='&';};_url+=this._url_id+'='+_id;this.dom.createScript(this._parent_element,this._id_prefix+_id,_url);}};this.ready=function(_id,_result){this.answer=_result;if(this.cache)this.cache._add(this._requests[_id].request,_result);if(this._requests[_id].callback instanceof Function)this._requests[_id].callback();if(document.getElementById(this._id_prefix+_id)){this.dom.removeElement(document.getElementById(this._id_prefix+_id));}delete(this._requests[_id]);};this._init(arguments);}var _cba=null;function cbaUpdateElement(_doc_id,_url){var _loading_text=(arguments[2])?arguments[2]:null;var _caching=(arguments.length>3)?arguments[3]:true;var _template=(arguments[4])?arguments[4]:'%1';var _error_template=(arguments[5])?arguments[5]:null;var _user_method=(arguments[6])?arguments[6]:null;if(_loading_text)document.getElementById(_doc_id).innerHTML=_loading_text;if(!_cba)_cba=new cbaRequest();_cba.query(_url,function(){if((_error_template)&&_cba.answer==_error_template[0]){document.getElementById(_doc_id).innerHTML=_error_template[1];}else{if(typeof(_cba.answer)=='object'){var _result=_template;for(key in _cba.answer){_result=_result.replace('%'+key+'%',_cba.answer[key]);}document.getElementById(_doc_id).innerHTML=_result;}else{document.getElementById(_doc_id).innerHTML=_template.replace('%1',_cba.answer);}};if(_user_method&&_user_method instanceof Function)_user_method();},_caching);}

function tbcharlimit(elem, divID) {
	var charsleft = 140 - elem.value.length;
	var divH = document.getElementById(divID); 
	if ( charsleft < 0 ) {
		divH.innerHTML = '<b><font color=red>' + charsleft + '</font></b>';		
	} else {
		divH.innerHTML = '<b>' + charsleft + '</b>';
	}
}

function tweet(modID, rowID, shortURL) {
	var userName = trim(document.getElementById("tbusername_" + modID + "_" + rowID).value);
	var password = trim(document.getElementById("tbpassword_" + modID + "_" + rowID).value); 
	var status = trim(document.getElementById("tbstatus_" + modID + "_" + rowID).value); 
	var replyto = "";
	if ( rowID > 0 ) { replyto = trim(document.getElementById("tbreplyto_" + modID + "_" + rowID).value); }
	var remember = document.getElementById("tbremember_" + modID + "_" + rowID).checked;
	
	if ( !shortURL && status.length > 140  ) {
		alert("Max 140 characters are allowed. Please try to shorten your message!");
		return;
	}

	if ( userName.length > 0 && password.length > 0 ) {

		if ( remember ) {
			tbcreateCookie('tbu',userName,365);
			tbcreateCookie('tbp',password,365);
		} else { tberaseCookies(); }

		if ( status.length > 0 ) {
			document.getElementById('tweetboxdiv_' + modID).style.display="none";
			document.getElementById('tweetboxdivload_' + modID).style.display="block";
			var poststr = 	"task=tweet" +
					"&u=" + encodeURIComponent(userName) +
					"&p=" + encodeURIComponent(password) +
					"&m=" + encodeURIComponent(status) +
					"&modid=" + modID +
					"&rt=" + encodeURIComponent(replyto);
					
			makePOSTRequest('modules/mod_ajaxtweet/helpers/ajax.php', poststr); 
			
		} else {
			alert("Please enter a text to Tweet!");
		}
	} else {
		alert("Please specify your Twitter username and password!");
	}
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}


function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            	http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
}

function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            result = http_request.responseText;  

	    var modID = 0;
	    var posID = result.indexOf('<MODID>');
	    var posIDEnd=result.indexOf('</MODID>');
	    if ( posID >=0 && posIDEnd > posID ) {
	    	modID = result.substring(posID+7,posIDEnd);
	    	
	    }

	    if ( modID > 0 ) {
	    	    document.getElementById('tweetboxdiv_' + modID).style.display="block";
	    	    document.getElementById('tweetboxdivload_' + modID).style.display="none";
	    	    var rowID = tbLastRowID[modID];
		    var posErr=result.indexOf('<ERR>');
		    var posErrEnd=result.indexOf('</ERR>');
		    if ( posErr >=0 && posErrEnd > 5 ) {            
			errMsg = result.substring(posErr+5,posErrEnd);
			if ( errMsg.indexOf('password') > 0 ) {
				tberaseCookies();
			}
		    	var posMsg=result.indexOf('<MSG>');
		    	var posMsgEnd=result.indexOf('</MSG>');
			if ( posMsg >=0 && posMsgEnd > 5 ) { 
				var status = result.substring(posMsg+5,posMsgEnd);
				var statusH = document.getElementById("tbstatus_" + modID + "_" + rowID);
				statusH.value = status;
				tbcharlimit(statusH, 'tweetboxchars_" + modID + "_" + rowID +"');
			}
			alert(errMsg);
			return;
		    }            

		    var tweets = "";
		    var posRes=result.indexOf('<TWEETS>');
		    var posResEnd=result.indexOf('</TWEETS>');
		    if ( posRes >=0 && posResEnd > 8 ) {
			tweets = result.substring(posRes+8,posResEnd);
		    } 
		    document.getElementById('tweetboxdiv_' + modID).innerHTML = tweets; 		    		    
		    tbsetTweetForm(modID);
		    
	    } else {
	    	alert("Something went wrong...Please refresh the page.");
	    	
	    }
         }
      }
}




function tbOver(el,modID, rowID) {
	el.className = "tbover";
	document.getElementById("tweetbox_" + modID + "_reply_" + rowID).style.display="block";
}

function tbOut(el,modID, rowID, cName) {
	el.className = cName;
	
	var currDISP = document.getElementById("tweetbox_" + modID + "_frm_" + rowID).style.display;
	if ( currDISP == "none" ) {
		document.getElementById("tweetbox_" + modID + "_reply_" + rowID).style.display="none";	
	}
}

function tbreplyClick(modID,rowID,author,statusRows,shortURL) {
	var currDISP = document.getElementById("tweetbox_" + modID + "_frm_" + rowID).style.display;
	var newDISP = "none";
	var lblSTr = "";
	var frmStr = "";
	var bottomDISP = "block";
	var lenLabel = 140-author.length-2;
	var replyLabel = tbReplylbl;
	var uname = tbreadCookie('tbu');
	var pwd = tbreadCookie('tbp');
	var rememberCheck = "";
	if ( uname != "" && pwd != "" ) {
		rememberCheck = " checked";
	}
	if ( currDISP == "none" ) {
		newDISP = "block";
		tbresetRows(modID,rowID);
		lblStr = tbUserlbl + " :<br>" + tbPasslbl + " :<br><br><div id=\"tweetboxchars_" + modID + "_" + rowID + "\"><b>" + lenLabel + "</b></div>";
		frmStr = "<input type=\"hidden\" id=\"tbreplyto_" + modID + "_" + rowID + "\" value=\"" + author + "\"><input type=\"text\" name=\"username\" id=\"tbusername_" + modID + "_" + rowID + "\" style=\"width: 75%\" value=\"" + uname + "\"><br><input type=\"password\" name=\"password\" id=\"tbpassword_" + modID + "_" + rowID + "\" style=\"width: 75%\" value=\"" + pwd + "\"><br><textarea name=\"tbstatus_" + modID + "_" + rowID + "\" id=\"tbstatus_" + modID + "_" + rowID + "\" rows=" + statusRows + " cols=10 onKeyUp=\"tbcharlimit(this, 'tweetboxchars_" + modID + "_" + rowID +"');\" style=\"width: 95%\">@" + author + " </textarea><br><input type=\"button\" value=\"" + tbReplylbl + "\" onClick=\"tweet(" + modID + "," + rowID + "," + shortURL + ")\">&nbsp;&nbsp;<input type=\"checkbox\" id=\"tbremember_" + modID + "_" + rowID + "\"" + rememberCheck + "> " + tbRememberlbl;
		bottomDISP = "none";
		replyLabel = tbHidelbl;
	}

	document.getElementById("tweetbox_" + modID + "_frm_" + rowID).style.display = newDISP;
	if ( document.getElementById("tbfrmleft_" + modID + "_" + rowID).innerHTML == "" ) {
		document.getElementById("tbfrmleft_" + modID + "_" + rowID).innerHTML = lblStr;
		document.getElementById("tbfrmmain_" + modID + "_" + rowID).innerHTML = frmStr;
	}
	var bottomFrm = document.getElementById("tbtweetlbl_" + modID);
	if ( !bottomFrm || ( bottomFrm && bottomFrm..style.display == "none" ) ) {
		document.getElementById("tbbottomfrm_" + modID).style.display = bottomDISP;
	}
		
	document.getElementById("tbreplyLbl_" + modID + "_" + rowID).innerHTML = replyLabel;
}

function tbresetRows(modID,rowID) {
	var currRowID = rowID-1;
	var theTable = document.getElementById("tweetbox_" + modID + "_tbl");
	for( var x = 0; x < theTable.tBodies[0].rows.length; x++ ) {
		if ( x != currRowID ) {
			var hideID = x+1;
			document.getElementById("tweetbox_" + modID + "_frm_" + hideID ).style.display = "none";
			document.getElementById("tweetbox_" + modID + "_reply_" + hideID).style.display="none";
			document.getElementById("tbreplyLbl_" + modID + "_" + hideID).innerHTML = tbReplylbl;
		}
	}

}

function tbshowForm(modID) {
	document.getElementById("tbbottomfrm_" + modID).style.display = "block";
	document.getElementById("tbtweetlbl_" + modID).style.display = "none";
}

function tbcreateCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function tbreadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return "";
}

function tberaseCookie(name) {
	tbcreateCookie(name,"",-1);
}

function tbsetTweetForm(modID) {
	var u = tbreadCookie('tbu');
	var p = tbreadCookie('tbp');
	if ( u != "" && p != "" ) {		
		document.getElementById("tbremember_" + modID + "_0").checked = true;
	}
	document.getElementById("tbusername_" + modID + "_0").value = u;
	document.getElementById("tbpassword_" + modID + "_0").value = p;
}

function tberaseCookies() {
	tberaseCookie('tbu');
	tberaseCookie('tbp');
}


