  // topic search vars
  var topicSearchSinceId = 0;
  var topicSearchFromEpochTime = 0;
  var topicSearchRefreshTime = 30000;
  var topicSearchLastCount = 0;
  var topicSearchAlertTimerId = 0;

  // mentions vars
  var mentionsAlertTimerId = 0;

  // account vars
  var accountRefreshTime = 60000;
  var accountNewMessageLastCount = 0; 

  function preFillMessage(m) {
      preFillMessage(m, false, 0, "", 1, 0, "", "");
  }

  function preFillMessage(m, s, touserid, tousername, tonetwork, toprofileurl, toprofileimageurl) {
	  preFillMessage(m, s, touserid, tousername, tonetwork, 0, toprofileurl, toprofileimageurl);
  }
  
  function preFillMessage(m, s, touserid, tousername, tonetwork, topicid, toprofileurl, toprofileimageurl) {
      m = unescape(m);
      m = unescapeHTML(m);
      
      if ( m.length > 140 ) {
    	  m = m.substring(0, 137) + "...";
      }
      
      $jx("#status").val(m);
      $jx("#status").focus();
      $jx("#touserid").val(touserid);
      $jx("#tousername").val(tousername);
      $jx("#tousernetwork").val(tonetwork);
      $jx("#toprofileurl").val(toprofileurl);
      $jx("#toprofileimageurl").val(toprofileimageurl);
      // do nothing with the topic id

      //alert("toprofileurl=" + toprofileurl + ",toprofileimageurl=" + toprofileimageurl);
      
      updatePostCharsLeft();
      
      if ( s == true ) {
          sendMessage();
      }
  }

  function sendMessage() {

      if ( sendingMessage == false ) {
    	if ( isconnected == 'true' ) {
    		sendingMessage = true;
    		$jx("#sendtweet").hide();
    	    $jx("#sendingtweet").fadeIn("fast");    		
    		
    		$jx("#status-update-form").submit();
    	}
    	else {
    		popupConnectPrompt();
    	}
      }
  }
  
  function updatePostCharsLeft() {
  	// limit chars straight away
      limitChars('status', 140, 'status-field-char-counter');  
  }

  
	function getNewMentions() {
		var mentionsCountUrl = unreadMentionsCountBaseUrl + "?nocache=" + new Date().getTime();
		
	    if ( isconnected == 'true' ) {

			$jx.get(mentionsCountUrl, function(data) {
				var newmentionscount = eval(data);
	
				if ( newmentionscount > 0 ) {
				 $jx("#new_mentions_count").text(" messages (" + newmentionscount + ")");
				}
				 
		      });
	
	        if ( mentionsAlertTimerId > 0 ) {
	        	clearTimeout( mentionsAlertTimerId );
	        }
	          
	    	// set the timeout to check the next lot of messages
	    	mentionsAlertTimerId = setTimeout( "getNewMentions()", 60000 );
	    }
	}

	function onMentionReply(m, touserid, tousername, tonetwork, topicid, toprofileurl, toprofileimageurl) {
      // load the popup
      showRecentMentions();

      // set the message
      preFillMentionMessage(m, false, touserid, tousername, tonetwork, topicid, toprofileurl, toprofileimageurl); 
	}

	function showRecentMentions() {
		
		$jx("#mentionreply").val("");
		$jx("#mentionsmessages").load(getMentionsBaseUrl + "?nocache=" + new Date().getTime());
		$jx("#new_mentions_count").text("");
		
		updateMentionsPostCharsLeft();
		
		loadPopup( "#popupMentions", 4, 50, 200 );
	}

	function hideRecentMentions() {
		$jx("#mentions").fadeOut("slow");
	}

    function preFillMentionMessage(m) {
        preFillMentionMessage(m, false, 0, "", 1, 0, "", "");
    }
    
    function preFillMentionMessage(m, s, touserid, tousername, tonetwork, topicid, toprofileurl, toprofileimageurl) {
        m = unescape(m);
        m = unescapeHTML(m);
       
        if ( m.length > 140 ) {
      	  m = m.substring(0, 137) + "...";
        }
        
        $jx("#mentionreply").val(m);
        $jx("#mentionreply").focus();
        $jx("#mentiontouserid").val(touserid);
        $jx("#mentiontousername").val(tousername);
        $jx("#mentiontousernetwork").val(tonetwork);
        $jx("#mentiontopicid").val(topicid);
        $jx("#mentiontoprofileurl").val(toprofileurl);
        $jx("#mentiontoprofileimageurl").val(toprofileimageurl);

        updateMentionsPostCharsLeft();
        
        if ( s == true ) {
            sendMentionMessage();
        }
    }
	
	function sendMentionMessage() {
	    $jx("#sendmentionreply").hide();
	    $jx("#sendingmentionreply").fadeIn("fast");
		      
	    $jx("#mentionForm").submit();
	}

	function ajaxBeforeSubmitMentionReply(formData, jqForm, options)  {
	      // nothing to do.
		  
		  return true; 
		}
		
		function ajaxSubmitMentionReplyError(request, textStatus, errorThrown)  {
		    // alert("error: ajaxSubmitTwitterNameError. request.responseText=" + request.responseText + ",textStatus=" + textStatus + ",errorThrown=" + errorThrown);
		}
		
		function ajaxSubmitMentionReplySuccess(responseText, statusText) {
		    // alert("success: statusText=" + statusText + ",responseText=" + responseText);
		    
		    $jx("#mentionreply").val("");
		    $jx("#sendmentionreply").fadeIn("fast");
		    $jx("#sendingmentionreply").hide();

		    // get the recent mentions in case you mentioned yourself, we want to see that 
		    // straight away	    
		    disablePopup();
		}	

		  function updateMentionsPostCharsLeft() {
			  	// limit chars straight away
			    limitChars('mentionreply', 140, 'mentions-status-field-char-counter');  
			  }
		
		
    function checkNewMessageCount() {
        var newMessagesCountUrl = 
        	newMessagesCountBaseUrl +
            "&_eventName=newmessagecount&sinceId=0" +
            "&fromTimeEpoch=" + topicSearchFromEpochTime +
            "&nocache=" + new Date().getTime();
        
        $jx.get(newMessagesCountUrl, function(data) {
            var model = eval(data);

            var newMessagesCount = model['newMessageCount'];
            var newMessageLastPostTimeEpoch = model['newMessageLastPostTimeEpoch'];
            
            if ( newMessagesCount > topicSearchLastCount && 
            	 newMessageLastPostTimeEpoch > topicSearchFromEpochTime ) 
            {
           	    // set the new figure
           	    
            	topicSearchLastCount = newMessagesCount; 
                $jx("#new_results_since_count").text(newMessagesCount);
                $jx("#newresultsnotification").show();
            }
             
          });

        topicSearchRefreshTime = topicSearchRefreshTime * 1.25;
        if ( topicSearchRefreshTime > 180000 ) {
        	topicSearchRefreshTime = 180000;
        }
        
        // set an interval
        setTimeout( "checkNewMessageCount()", topicSearchRefreshTime );
    }
    
    function onNewTwitterSearch(fromEpochTime) {
    	topicSearchFromEpochTime = fromEpochTime;

        // reset sliding
        topicSearchRefreshTime = 30000;
        topicSearchLastCount = 0;

        if ( topicSearchAlertTimerId > 0 ) {
        	clearTimeout( topicSearchAlertTimerId );
        }
  
        // reset the account refresh time
        var accountRefreshTime = 60000;
        
    	// set the timeout to check the next lot of messages
    	topicSearchAlertTimerId = setTimeout( "checkNewMessageCount()", topicSearchRefreshTime );
    	
    	// get new mentions as well
    	getNewMentions();
    }

    function checkNewAccountMessageCount() {
        var newAccountMessagesCountUrl = 
        	newAccountMessagesCountBaseUrl +
            "&nocache=" + new Date().getTime();
        
        $jx.get(newAccountMessagesCountUrl, function(data) {
            var newAccountMessagesCount = eval(data);

            if ( newAccountMessagesCount > accountNewMessageLastCount ) {
            	accountNewMessageLastCount = newAccountMessagesCount; 
            	
                $jx("#new_account_messages_since_count").text(newAccountMessagesCount);
                $jx("#newaccountmessagesnotification").show();
            }
             
          });

        accountRefreshTime = accountRefreshTime * 1.25;
        if ( accountRefreshTime > 180000 ) {
        	accountRefreshTime = 180000;
        }
        
        // set an interval
        setTimeout( "checkNewAccountMessageCount()", accountRefreshTime );
    }
    
    function unescapeHTML(unsubstr) {
        return unsubstr.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&').replace(/&quot;/g,'\"');
    }


    // popups
    
    function loadPopup(popupdivid, pStatus) {
  	  loadPopup(popupdivid, pStatus, 0, 250);
    }
    
    function loadPopup(popupdivid, pStatus, top, left){
        // loads popup only if it is disabled
        if(popupStatus==0){
            $jx("#backgroundPopup").css({
                "opacity": "0.7"
            });
            $jx("#backgroundPopup").fadeIn("slow");
            $jx(popupdivid).fadeIn("slow");
            popupStatus = pStatus;
            popupDiv = popupdivid;

            centerPopup(popupdivid, top, left);
        }
    }

    // centering popup
    function centerPopup(popupdivid, top, left){
        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $jx(popupdivid).height();
        var popupWidth = $jx(popupdivid).width();

        if ( top == 0 ) {
      	  top = windowHeight/2-popupHeight/2;  
        }
        
        // var left = 250;
        if ( left == 0 ) {
          left = (windowWidth-popupWidth)/2;
        }

        // alert("top=" + top + ",left=" + left + ",windowWidth=" + windowWidth + ",popupWidth=" + popupWidth);
        
        //centering
        $jx(popupdivid).css({
            "position": "absolute",
            "top": top,
            "left": left
        });
        //only need force for IE6
        
        $jx("#backgroundPopup").css({
            "height": windowHeight
        });
        
    }
    
    // disabling popup with jQuery magic!
    function disablePopup(){
        $jx("#backgroundPopup").fadeOut("slow");
        $jx(popupDiv).fadeOut("slow");
        popupStatus = 0;
        popupDiv = "";
    }    
    
    function limitChars(textid, limit, infodiv)
    {
      var text = $jx('#'+textid).val(); 
      var textlength = text.length;
      
      if(textlength > limit)
      {
          
          $jx('#' + infodiv).html(limit - textlength);
          // $jx('#' + infodiv).html('0');
    	  // $jx('#'+textid).val(text.substr(0,limit));
          
    	  // red alert, approaching maximum chars
    	  $jx('#' + infodiv).css("color","#CC0000");


          return false;
      }
      else
      {
        $jx('#' + infodiv).html((limit - textlength));
        $jx('#' + infodiv).css('color', '#CCCCCC');

        return true;
      }
    }
    
    function ajaxBeforeSubmitFacebookName(formData, jqForm, options)  {
        var form = jqForm[0]; 

        $jx('#facebooknamestatus').html();
        
        return true; 
      }
      
      function ajaxSubmitFacebookNameError(request, textStatus, errorThrown)  {
          // alert("error: ajaxSubmitFacebookNameError. request.responseText=" + request.responseText + ",textStatus=" + textStatus + ",errorThrown=" + errorThrown);
      }
      
      function ajaxSubmitFacebookNameSuccess(responseText, statusText) {
          // alert("success: statusText=" + statusText + ",responseText=" + responseText);
          
          if ( responseText != '1' ) {
              $jx('#facebooknamestatus').html("No Facebook account found. Please try another facebook account.");
              return;
          }

          $jx('#facebooknamebuttons').fadeOut("slow");
          $jx('#facebooknamestatus').html("Thanks, the facebook account has been saved. Now taking you back to the app...");

          // set timer
          timer=setTimeout('window.location.reload()',2000);
      }

 
    