$(document).ready(function() {	
	// show flashmsg in momolog for 8 seconds..
	$('#flashmsg').slideDown('normal',function (){
		$(this).fadeOut(6000);
	});
	
	 
	//$("#tweetbox").charCounter(140);	

	$('#tweetbox').keyup(function(){
      limitChars('tweetbox', 140, 'charcount');
   });
   
   $('#qbox').keyup(function(){
      limitChars('qbox', 125, 'charcountq');
   });
   
  
   
	  var options = { 
        //target:       '#dialog',   // target element(s) to be updated with server response 
       // beforeSubmit:  showRequest,  // pre-submit callback 
		 success:       showResponse,  // post-submit callback         
		 //clearForm: false,        // clear all form fields after successful submit 
       resetForm: true        // reset the form after successful submit 
 
     }; 
 	
    // bind form using 'ajaxForm' 
    $('.ajaxform').ajaxForm(options); 
    
     var widoptions = { 
       target:       '#widgetdisplay',   // target element(s) to be updated with server response 
       // beforeSubmit:  showRequest,  // pre-submit callback 
		 //success:       showwidget,  // post-submit callback         
		 //clearForm: false,        // clear all form fields after successful submit 
       resetForm: false        // reset the form after successful submit 
 		 //dataType: 'json'
     }; 

    $('.widgetform').ajaxForm(widoptions); 

   
    $('a.reply').click( function() {
    	var who = $(this).attr('rel');
    	$('#tweetform').show('fast')
		$('#tweetbox').val('@'+who+' ').focus();
		SetEnd($('#tweetbox'));
		setTimeout(function() {
			$('.tbox').focusEnd();
			},
		500);
		
		//setCaretToPos($('#tweetform'), 30);
		$('.tbox').focus();
		
    });
    
        $('select#modifier,select#loc').change( function () { 
      dialog('One moment');
    	do_url($(this).attr('rel'),$(this).val());    
    	
    });
    
      
    if($('#streamcontrol')) {
    	window.setInterval("getnew()", 15000);
	 }
		/* jquery search box autocompelte */
	// $(".autocomplete").autocomplete('/s/t/suggest');

		$(".autocomplete").autocomplete('/s/suggest', {
			width: 200,
			multiple: true,
			matchContains: true,
			delay: '300',
			multipleSeparator: ' ',
			formatItem: formatItem,
			formatResult: formatResult

		});
		
		$(".autocomplete_user").autocomplete('/s/users', {
			width: 200,
			multiple: false,
			matchContains: true,
			delay: '300',
			formatItem: formatItem,
			formatResult: formatResult

		});

    
    function formatItem(row) {
		return row[0];
	}
		function formatResult(row) {
		return row[0].replace(/(<.+?>)/gi, '');
	}
	
	$('#feedjump').change( function() {
		var where = $(this).val();
		if (where == 'ALL') {
			window.location = '/';
		} else {
			window.location = '/s/t/'+where;
		}
	});
	
});

function SetEnd (TB)
{
	if (TB.createTextRange)
	{
	var FieldRange = TB.createTextRange();
	FieldRange.moveStart('character', TB.value.length);
	FieldRange.collapse();
	FieldRange.select();
	}
}


function limitChars(textid, limit, infodiv)
{
   var text = $('#'+textid).val();  
   var textlength = text.length;
   if(textlength > limit)
   {
     // $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
      $('#'+textid).val(text.substr(0,limit));
      return false;
   }
   else
   {
      $('#' + infodiv).html('<span class="chars">'+ (limit - textlength) +'</span>/<span class="max">'+ limit +'</span>');
      return true;
   }
}
function trackChars(textid, limit, infodiv)
{
   var text = $('#'+textid).val();  
   var textlength = text.length;
   
   if (textlength < limit) {
		$('#' + infodiv).html('<span class="chars">'+ (textlength) +'</span> <span class="max">Characters</span>');
   } else {
    	$('#' + infodiv).html('<span class="green">'+ (textlength) +'</span> <span class="max green">Characters</span>');

   }
}

function do_url(position,what) {
		
    	/*var path = window.location.pathname;
    	var myArray = path.split('/');
		if (path == '/') {
			mods = [what];
		} else {
    		var mods = myArray[3].split('+');
			if (what == '--') {
				mods[position] = null;
			} else {
		  		mods[position] = what;
			}
		//alert(mods); 
		}
    	
    	
    	    	
    	for (i in mods) {
    		if (mods[i] != null) {
    			mpath += mods[i]+'+';
    		}
    	}
    	*/
    	var mpath = '/s/t/';
    	$('#streamcontrol select').each(function() {
    		var val = $(this).val();
    		if (position == 0 && val == "--") { 
    			var nval = '';
    		} else if (position > 0 && val == "--") {

    		} else {
    			var nval =  val;
				mpath += nval+'+';
    		}
    	});
    	mpath =  mpath.substring(0, mpath.length-1);

    	var go = window.location.protocol+'//'+location.host+mpath;
    	window.location.replace(go);
}

function isArray(obj) {

    return obj.constructor == Array;

}
function dialog(text) {
		$("#dialog").html(text).dialog({
    		modal: true,
    		title: "Loading..."
    		});
}
          
function showResponse(responseText, statusText) {
    	
    	$("#dialog").html(responseText).dialog({
    		modal: true,
    		title: statusText,
    		buttons: { 
    			"Close": function() { $(this).dialog("close"); }, 
    			"Refresh Page": function() { location.reload(true); }
    		}
    		});
} 

function showwidget(data) {
    alert(data);
} 
	 
function show_stream_under(what) {
	$('#stream_meta #'+what).slideToggle('fast');
	return false;
}



function get_latest_tweets() {
	 window.setInterval("getnew()", 15000);
    var id = $('ul.tweets li:first-child').attr("id");

}
function getnew(){
      var id = $('ul.tweets li:first-child').attr("id");
		var tag = $('#streamcontrol').attr('rel');
		if (id) {
      $.ajax({
        type: "GET",
        url: "/ajax/latesttweets/"+id+"/"+tag,

        success: function(html) {
     		//alert(oldhtml);
            if (html != "") {
              $('ul.tweets li').removeClass('newt');
              $('ul.tweets').prepend(html);
              $('ul.tweets li.hide').fadeIn('5000');
              $('ul.tweets li.hide').removeClass('hide');
            }
        }       
      });
      }
    }

jQuery.fn.extend({
 
	highlight: function(search, insensitive, klass){
		var regex = new RegExp('(<[^>]*>)|(\\b'+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +')', insensitive ? 'ig' : 'g');
		return this.html(this.html().replace(regex, function(a, b, c){
			return (a.charAt(0) == '<') ? a : '<strong class="'+ klass +'">' + c + '</strong>'; 
		}));
	}
 
});

$.fn.focusEnd=function(){
	return this.each(function(){
		var A=this;
		if(A.style.display!="none"){
			if($.browser.msie){
				A.focus();
				var B=A.createTextRange();
				B.collapse(false);
				B.select()
			} else{
				A.setSelectionRange(A.value.length,A.value.length);
				A.focus()
			}
		}
	})
};	