// ** DOCUMENT READY**
// *******************
	var login_state, timeline_refresh, refresh_timer;
	var rpp=20;  //default responses per page to 20...
	
	$(document).ready(function(){
	    var st;
		//getIGScripts();
		//set_gadget_height();
		
		//not on twitter?  hide the twitter specific elements
		if(api_url != "http://twitter.com"){ 
			$(".twitter_only").hide();
		}
	
	    $("#service_logon_message").html(service_name_short+" Logon");
			
		monitor_ajax_transactions();
		set_bindings();
		//clear the text area of junk
		$("#message_textarea").text("");

		//login_state=verify_credentials();
		if(username=get_cookie('username')){
			// get rid of encrypted password from old version
			if(get_cookie('password_e')=='true'){
                set_cookie("username", "", -1000);
                set_cookie("password", "", -1000);
				set_cookie('password_e', "", -1000); //unset password encrypted flag
				set_cookie("random_number", "", -1000);
			}
			if(password=get_cookie('password')){
				login_state="true";
			}
		}
		if(login_state=="true"){
			set_view("logged_in");
		}else{
			set_view("logged_out");
		}

		set_defaults();
	    
		if(login_state=="true"){
			st=get_cookie('selected_tab');
			$("#"+st).click();
		}
		
		activate_timeline_menu();
		$('ul.sf-menu').superfish({ 
            delay:       300,                            // one second delay on mouseout 
            animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
            speed:       'fast',                          // faster animation speed 
            autoArrows:  true,                           // disable generation of arrow mark-up 
            dropShadows: true                            // disable drop shadows 
        });
		
		adjust_size();
		
		//detect iphone and hide the bottom bar
		var agent=navigator.userAgent.toLowerCase();
		var is_iphone = (agent.indexOf('iphone')!=-1);
		if (is_iphone) { 
			$("#app_footer").hide();
		}
		//detect iphone and hide the bottom bar
		
	});
	//**DOCUMENT READY**
	//******************

//** SET_DEFAULTS
    function set_defaults(){
		
		$.ajaxSetup({timeout: 15000});
	
        var refresh_rate;
        if(get_cookie('refresh_rate')){
            refresh_rate=get_cookie('refresh_rate');
        }else{
            refresh_rate=3;
            set_cookie('refresh_rate', refresh_rate, 90);
        }
        if(!get_cookie('selected_tab')){
            set_cookie("selected_tab", "friends_timeline_tab", 90);
            set_cookie("other_tab", "other_public_timeline_tab");
        }
        if(get_cookie('pics')!="false"){
            set_cookie('pics', "true", 90);
        }
        if(get_cookie('timestamps')!="false"){
            set_cookie('timestamps', "true", 90);
        }
        if(!get_cookie('other_tab')){
            set_cookie('other_tab', 'other_public_timeline_tab', 90);
        }
        if(default_font_size=get_cookie('default_font_size')){
        	$(document.body).css("font-size", default_font_size+"px");
        }else{
        	set_cookie('default_font_size', "11", 90);
        } 
		if(get_cookie("show_controls")){
			show_controls=get_cookie("show_controls");
			if(show_controls=="false"){
				$("#control_area").slideUp();
				$("#toggle_spacer").show();
				//$("#timeline_tabs").slideUp();
			}else{
				$("#control_area").slideDown();
				$("#toggle_spacer").hide();
			}
		}else{
			set_cookie("show_controls", true, 90);
		}
		if(get_cookie("igoogle_gadget_height")){
			igoogle_gadget_height=get_cookie("igoogle_gadget_height");
		}else{
			set_cookie("igoogle_gadget_height", 350, 90);
			igoogle_gadget_height=350;
		}
		//set_gadget_height();
		if(!get_cookie("random_number")){
			var random_number=Math.floor(Math.random()*10000000);
			set_cookie("random_number", random_number, 90);
		}
    }
	
//** SET_BINDINGS
	function set_bindings(){
	
	//*SEARCH FUNCTIONS
	
	    $("#search_input_text").keydown(function(event){
			var e = event.keycode;
			if (e == null) { // ie
				keycode = event.keyCode;
			} else { // mozilla
				keycode = e.which;
			}
			if(keycode == 13){
				$("#search_button").click();
			}
        });
		
		$("#search_input_text").keyup(function(){
			var value = $(this).val();
			set_cookie("search_term", value, 999);
	    });
		
		$("#search_button").click(function(){
			var search_term = get_cookie("search_term");
			//$.jGrowl(search_term);
			search_term=search_term.replace(" ", "+");
			
			var result=get_search_timeline(search_term);
			//$.jGrowl("<pre>"+result+"</pre>");
			$("#search_target").html(result);
			addMessageControls();
			reset_app_footer();
		});
	
	//** CONTROL_AREA_TOGGLE show/hide
		$("#control_area_toggle").click(function(){
			$("#control_area").slideToggle();
			$("#toggle_spacer").toggle(); 
			//$("#timeline_tabs").slideToggle();
			var show_controls=get_cookie("show_controls");
			if(show_controls=="false"){
				set_cookie("show_controls", "true", 90);
			}else{
				set_cookie("show_controls", "false", 90);
			}
		});
		
	//** SETTINGS_BUTTON (COG) binding
        $("#settings_button").click(function(){
            var pics=get_cookie('pics');
            var timestamps=get_cookie('timestamps');
            var refresh_rate=get_cookie('refresh_rate');
            var default_font_size=get_cookie('default_font_size');
			var igoogle_gadget_height=get_cookie("igoogle_gadget_height");
            
            var dialog_info=$("#settings_div").html();
            var dialog_info_fixed=dialog_info.replace(/id="/gi, 'id="jgrowl_');
            //$.jGrowl.defaults.position="center";
            $.jGrowl(dialog_info_fixed, {
                header: 'Settings',
                sticky: true,
                close: function(e,m,o){
					clear_timeline();
                    timeline_update();
                    $(document.body).css("font-size", default_font_size+"px");
					adjust_size();
					//set_gadget_height();
                }
            });

            //$("#username_cell").text("("+pics+")");
            if(pics=="true"){
                $("#jGrowl .display_pics").attr("checked", true);
            }else{
                $("#jGrowl .display_pics").attr("checked", false);
            }
            if(timestamps=="true"){
                $("#jGrowl .display_timestamps").attr("checked", true);
            }else{
                $("#jGrowl .display_timestamps").attr("checked", false);
            }
            if(refresh_rate){
                $("#jGrowl .refresh_rate").val(refresh_rate);
            }else{
                refresh_rate=3;
                $("#jGrowl .refresh_rate").val(refresh_rate);
                set_cookie("refresh_rate", refresh_rate, 90);
            }
            if(default_font_size){
            	$("#jGrowl .font_size_selector").val(default_font_size);
            }
            if(igoogle_gadget_height){
				$("#jGrowl .igoogle_gadget_height_selector").val(igoogle_gadget_height);
			}
            
        //** SETTING SELECTIONS BINDINGS
            $("#jGrowl .display_pics").click(function(){
                var pics_setting=$("#jGrowl .display_pics").attr("checked");
                set_cookie("pics", pics_setting, 90);
            });
            $("#jGrowl .display_timestamps").click(function(){
                var timestamps_setting=$("#jGrowl .display_timestamps").attr("checked");
                set_cookie("timestamps", timestamps_setting, 90);
            });
            $("#jGrowl .refresh_rate").change(function(){
                refresh_rate = $("#jGrowl .refresh_rate").val();
                if(refresh_rate<1){
                    refresh_rate=3;
                }
                set_cookie("refresh_rate", refresh_rate, 90);
            });
            $("#jGrowl .font_size_selector").change(function(){
            	default_font_size=$("#jGrowl .font_size_selector").val();
            	set_cookie("default_font_size", default_font_size, 90);
            });         
            $("#jGrowl .igoogle_gadget_height_selector").change(function(){
            	igoogle_gadget_height=$("#jGrowl .igoogle_gadget_height_selector").val();
            	set_cookie("igoogle_gadget_height", igoogle_gadget_height, 90);
            });  			
            $("#jGrowl .logout_link").click(function(event){
                event.preventDefault();
                set_cookie("username", "", -1000);
                set_cookie("password", "", -1000);
				set_cookie('password_e', "", -1000); //unset password encrypted flag 
                set_cookie("selected_tab", "friends_timeline_tab", 90);
                set_cookie("other_tab", "other_public_timeline_tab", 90);
				set_cookie("random_number", "", -1000);
                document.location.reload();
            });
        });

	//** OTHER tab setup
		setup_other_tab();

	//** TABS create tabs and capture tab clicks
		activate_tabs();	

	//** LOGIN_BUTTON CLICK
		$("#login_button").click(function(event){
			event.preventDefault();
			var username,password,login_response;
			
			username=$("#input_username").val();
			password=$("#input_password").val();
			
			set_cookie('username', username, 90);
			set_cookie('password', password, 90);
			set_cookie('password_e', 'false', 90); //unset password encrypted flag 
            set_cookie('selected_tab', "friends_tab", 90);

			login_response=verify_credentials();
			$("#login_status").html(login_response);
			if(login_response=="true"){
				username_link='<a href="'+srv_url+'/'+username+'" target="_blank">'+username+'</a>';
				$("#username_cell").html(username_link);
				$("#message_textarea_error").html("").hide();
				set_view("logged_in");
			}else{
				//set_cookie("username", null, -1000);
				//set_cookie("password", null, -1000);
				set_view("logged_out");
				$("#login_status").html(login_response);
			}
		});

	//** SEND_BUTTON button click
		$("#send_button").click(function(event){
			event.preventDefault();
			var msg=urlencode($("#message_textarea").val());
			$.ajax({
   				type: "get",
   				url: "http://betwittered.com/api/",
   				data: "req=send_message&source=betwittered&msg="+msg+"&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password')),
				async: false,
   				success: function(data){
   					if(data==200){
   						$("#message_textarea").val("");
   						$("#countdown").html(140);
   						$("#countdown").css("color", '#aaaaaa');
   						timeline_update();                            
                    	$("#message_textarea_error").html("").hide();
					}else{
						$.jGrowl("Error sending. Try again. Twitter responed with error: "+data, {sticky:false});
					}
   				},
   				error: function(data){
   					$.jGrowl("Error sending: Betwittered.com is choking. Ack.", {sticky:false});
					//$("#message_textarea_error").html("error: "+data).show();
   				}
			});
			if(api_url.toLowerCase()=="http://twitter.com"){
				var rls=get_rate_limit_status();
				$("#rate_limit_status").html(rls);
			}
		});

	//** REPLY_BUTTON button click		
		$("#reply_button").click(function(event){
				event.preventDefault();
			var username=get_cookie("username");
			var password=get_cookie("password");
			var msg=urlencode($("#message_textarea").val());
			var in_reply_to_status_id=$("#reply_button").attr("in_reply_to_status_id");
			
			$.ajax({
   				type: "get",
   				url: "http://betwittered.com/api/",
   				data: "req=send_message&api_url="+
					source+"&msg="+msg+"&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password'))+"&in_reply_to_status_id="+in_reply_to_status_id,
				async: false,
   				success: function(data){
   					$("#message_textarea").val("");
   					$("#countdown").html(140);
   					$("#countdown").css("color", '#aaaaaa');
   					timeline_update();                            
                    $("#message_textarea_error").html("").hide();
					$("#send_button").show();
					$("#reply_button").hide().attr("in_reply_to_status_id", "");
					if(!data==200){
						$.jGrowl("Error sending: "+data, {sticky:false});
					}
					//$.jGrowl("("+data+")");
   				},
   				error: function(data){
					$.jGrowl("Error sending: Could not contact Betwittered.com"+data, {sticky:false});
   					//$("#message_textarea_error").html("error: "+data).show();
					$("#send_button").show();
					$("#reply_button").hide().attr("in_reply_to_status_id", "");
   				}
			});
			if(api_url.toLowerCase()=="http://twitter.com"){
				var rls=get_rate_limit_status();
				$("#rate_limit_status").html(rls);
			}
		});	
		
    //** COUNTDOWN monitors textarea and updates "characters left" count
        $("#message_textarea").keyup(function(){
			
			var value = $(this).val();
			var patt=new RegExp("^@\\S+\\s");
			
			$("#countdown").html(140 - value.length);
			if (value.length > 130) {
				$("#countdown").css("color", '#d40d12');
			} else if (value.length > 120) {
				$("#countdown").css("color", '#5c0002');
			} else {
				$("#countdown").css("color", '#aaaaaa');
			}
			
			//$.jGrowl(patt.test(value)+": "+$("#reply_button").attr("in_reply_to_status_id"));
			if (patt.test(value)==true){
				$("#send_button").hide();
				$("#reply_button").show();
			}else{ 
				$("#reply_button").hide().attr("in_reply_to_status_id", "");
				$("#send_button").show();
			}
        });
	
	//** DOCUMENT RESIZED monitor for doc resizing
		$(window).resize(function(){
			adjust_size();
		});
		
	//** PREVIOUS_PAGE
		$("#previous_page").click(function(){
			clearInterval(timeline_refresh);
			var page_number=$("#page_number").text();
			page_number=parseInt(page_number);
			if(page_number > 1){
				page_number -= 1;
				$("#page_number").text(page_number);
				// CLEAR THE LAST MESSAGE ID, THE TARGET TABLE, AND THE MESSAGE COUNT
				clear_timeline();
                timeline_update(page_number);
			}
            var refresh_rate;
            if(refresh_rate=get_cookie('refresh_rate')){
                //OK!
            }else{
                refresh_rate = 3;
            }
			timeline_refresh=setInterval('timeline_update()', (refresh_rate*60000));
		});

	//** NEXT_PAGE
		$("#next_page").click(function(){
			clearInterval(timeline_refresh);
			var page_number=$("#page_number").text();
			page_number=parseInt(page_number);
			page_number+=1;
			$("#page_number").text(page_number);
            timeline_update(page_number);
			// CLEAR THE LAST MESSAGE ID, THE TARGET TABLE, AND THE MESSAGE COUNT
            clear_timeline()
			var refresh_rate;
            if(refresh_rate=get_cookie('refresh_rate')){
                //OK!
            }else{
                refresh_rate = 3;
            }
			timeline_refresh=setInterval('timeline_update()', (refresh_rate*60000));
		});
	}
//** SET_BINDINGS END

//** RESET_APP_FOOTER
	function reset_app_footer(){
		//$("#timeline_tabs_container").css("width", "10%");
		//$("#timeline_tabs_container").css("width", "100%");
		//$("#timeline_tabs_container").css("left", "0px");
		//$("#timeline_tabs_container").css("right", "0px");
	}
	
//** GET_SEARCH_TIMELINE
	function get_search_timeline(search_term){
		$.ajax({
			type: "get",
			cache: false,
			url: "api.php",
			data: "request=get_search_timeline&search_term="+escape(search_term)+"&srv_url="+escape(srv_url),
			async: false,
			success: function(data){
				response=data;
			},
			error: function(data){
				//$("#refresh_button_img").attr("src", "images/arrow_refresh.png");
				response=data;
			}
		});
		//$.jGrowl("<pre>"+response+"</pre>");
		return(response);
	}

//**  SET_GADGET_HEIGHT
	function set_gadget_height(){
		//$.jGrowl("(set_gadget_height)");
		var igoogle_gadget_height=350;
		if(get_cookie("igoogle_gadget_height")){
			igoogle_gadget_height=get_cookie("igoogle_gadget_height");
		} else {
			igoogle_gadget_height=350;
			set_cookie("igoogle_gadget_height", igoogle_gadget_height, 90);
		}
		if(igoogle_gadget_height==0){
			_IG_AdjustIFrameHeight();
		}else{
			_IG_AdjustIFrameHeight(igoogle_gadget_height);
		}
	}

//** ADJUST_SIZE all gadget window size adjustments HERE! 
	// (not the igoogle gadget iFrame size.  code separated for cross platform purposes)
	function adjust_size(){

		var gadgetWidth = ($("#topbar").attr("offsetWidth"));
		//$("#send_button").val("("+gadgetWidth+")");
		if (gadgetWidth <=220){
			$("#timeline_tabs").hide();
			$("#feedback_button").hide();
			$("#timeline_menu").show();
			$("#other_selections").hide();
		}else if (gadgetWidth > 220){
			$("#timeline_tabs").show();
			$("#feedback_button").show();
			$("#timeline_menu").hide();
			$("#other_selections").show();
		}
		if (gadgetWidth <=190){
			$("#app_name").hide();
			$("#send_button").val("snd");
		}else if (gadgetWidth > 190){
			$("#app_name").show();
			$("#send_button").val("Send");
		}
		ad_width = $("#ad_block").attr("offsetWidth");
		if (ad_width > (gadgetWidth-5)){
			ad_width=gadgetWidth-5;
			$("#ad_block").attr("width", ad_width);
		}
		st=get_cookie("selected_tab");
		if (st=="other_tab"){
			st=get_cookie("other_tab");
		}
		switch (st){
			case "friends_timeline_tab":
				$("#timeline_menu_title").html("Friends &#8595;");
				break;			
			case "replies_tab":
				$("#timeline_menu_title").html("Replies &#8595;");
				break;
			case "direct_messages_tab":
				$("#timeline_menu_title").html("Directs &#8595;");
				break;
			case "other_public_timeline_tab":
				$("#timeline_menu_title").html("Public &#8595;");
				break;
			case "other_favorites_tab":
				$("#timeline_menu_title").html("Favorites &#8595;");
				break;
			case "other_archive_tab":
				$("#timeline_menu_title").html("Archive &#8595;");
				break;
			// SEARCH_ADDED
			case "other_search_tab":
				$("#timeline_menu_title").html("Search &#8595;");
				break;
			/* SEARCH_ADDED
			case "other_custom_search_tab":
				$("#timeline_menu_title").html("Custom &#8595;");
				break;
			*/
			case "other_trends_tab":
				$("#timeline_menu_title").html("Trends &#8595;");
				break;
			default:
				$("#timeline_menu_title").html("Borked &#8595;");
		}
			
	}

//** URLENCODE turn a chunk of characters into a UTF8 compliant urlencoded string
	function urlencode( str ) {
	    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
	    var ret = str.toString();
	    
	    var replacer = function(search, replace, str) {
	        var tmp_arr = [];
	        tmp_arr = str.split(search);
	        return tmp_arr.join(replace);
	    };
	    
	    // The histogram is identical to the one in urldecode.
	    histogram['!']   = '%21';
	    histogram['%20'] = '+';
	    
	    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
	    ret = encodeURIComponent(ret);
	    
	    for (search in histogram) {
	        replace = histogram[search];
	        ret = replacer(search, replace, ret) // Custom replace. No regexing
	    }
	    
	    // Uppercase for full PHP compatibility
	    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
	        return "%"+m2.toUpperCase();
	    });
	    
	    return ret;
	}
   
//** SETUP_OTHER_TAB - configure the "other" tab and it's "sub menu"
	function setup_other_tab(){
		$("#other_selections > a").click(function(event){
			event.preventDefault();
			//set the tab URI to the URI of the chosen sub-tab
			//set the other_tab cookie to refer to its current uri setting
			//highlight the link that set the tab
			ot=$(this).attr("id");
            $("#other_selections > a").css("color", "#aaaaaa");
            $("#other_selections > a").css("background", "#e0e0e0 url(images/e0e0e0_40x100_textures_02_glass_80.png) 0 50% repeat-x");
            $(this).css("background", "#8ab9ff url(images/8ab9ff_40x100_textures_02_glass_50.png) 0 50% repeat-x");
			//$(this).css("background", "#d8d8d8 url(images/d8d8d8_40x100_textures_02_glass_90.png) 0 50% repeat-x");
			$(this).css("color", "#000000"); //"#2694e8");
            ot_uri=$("#"+ot).attr("uri");
			$("#other_tab").attr("uri", ot_uri);
			// if "search" tab is clicked show "search" target, hide "other" target
			if(ot=="other_search_tab" || ot=="other_trends_tab"){
				set_search_view("visible");
				return;
			}else{
				set_search_view("hidden");
			}
			set_cookie("selected_tab", "other_tab", 999);
            set_cookie("other_tab_previous", get_cookie("other_tab"), 999);
			set_cookie("other_tab", ot, 999);
			// looking at settings?  otherwise click the tab...
			$("#other_tab").click();
            //$("#"+ot).click();
		});
	}

//** SET_SEARCH_VIEW
	function set_search_view(visibility){
		if (visibility=="hidden"){
			$("#other_target").show();
			$("#search_target_wrapper").hide();
			set_cookie("search_tab", "hidden", 999);
		}
		if (visibility=="visible"){
			adjust_size();
			$("#other_target").hide();
			$("#search_target_wrapper").show();
			set_cookie("search_tab", "visible", 999);
		}
	}
	function set_other_view(ot){
		$("#other_favorites_tab_target").hide();
		$("#other_public_timeline_tab_target").hide();
		$("#other_archive_tab_target").hide();
		$("#"+ot+"_target").show();
	}
	
//** ACTIVATE_TIMELINE_MENU and bind click functions
	function activate_timeline_menu(){
		var menu_items = $("#timeline_menu a");
		menu_items.click(function(event){
			set_search_view("hidden");
			switch ($(this).attr("id")){
				case "friends_timeline_mi":
					$("#friends_timeline_tab").click();
					$("#timeline_menu_title").html("Friends &#8595;");
					break;
				case "replies_timeline_mi":
					$("#replies_tab").click();
					$("#timeline_menu_title").html("Replies &#8595;");
					break;
				case "directs_timeline_mi":
					$("#timeline_menu_title").html("Directs &#8595;");
					$("#direct_messages_tab").click();
					break;
				case "public_timeline_mi":
					$("#timeline_menu_title").html("Public &#8595;");
					$("#other_public_timeline_tab").click();
					break;
				case "favorites_timeline_mi":
					$("#timeline_menu_title").html("Favorites &#8595;");
					$("#other_favorites_tab").click();
					break;
				case "archive_timeline_mi":
					$("#timeline_menu_title").html("Archive &#8595;");
					$("#other_archive_tab").click();
					break;
				case "search_timeline_mi":
					$("#timeline_menu_title").html("Search &#8595;");
					$("#other_tab").click();
					$("#other_search_tab").click();
					break;
				case "trends_timeline_mi":
					$("#timeline_menu_title").html("Trends &#8595;");
					$("#other_tab").click();
					$("#other_trends_tab").click();
					break;
				/* <!-- SEARCH_ADDED
				case "custom_search_timeline_mi":
					$("#timeline_menu_title").html("Custom &#8595;");
					$("#other_custom_search_tab").click();
					break;
				*/
				default:
					// no action! 
			}
		});
	}

//** ACTIVATE_TABS and bind click functions
	function activate_tabs(){
		var tabs=$("#timeline_tabs_container > ul").tabs();
		$(".ui-tabs-nav-item > a").click(function(event){
			set_search_view("hidden");
			clearInterval(timeline_refresh);
			var st=$(this).attr("id");
			set_cookie("selected_tab", st, 90);
			// looking at the "other" tab? make the active sub-tab look active
			if(ot=get_cookie('other_tab')){
                // cookie exists, no action needed
			}else{
				ot="other_public_timeline_tab";
			}
			if((st=="other_tab")){
                $("#other_selections > a").css("color", "#aaaaaa");
                $("#other_selections > a").css("background", "#e0e0e0 url(images/e0e0e0_40x100_textures_02_glass_80.png) 0 50% repeat-x");
                $("#"+ot).css("color", "#2694e8");
                $("#"+ot).css("background", "#d8d8d8 url(images/d8d8d8_40x100_textures_02_glass_90.png) 0 50% repeat-x");
				//hide search target div and show the regular other target div
				set_search_view("hidden");
                // open the right tab, now.  make sure search and settings
                // get closed approriately or you end up with multiples opened
                //set_cookie('selected_tab', ot, 90);
				set_other_view(ot);
			}
			//$("#send_button").val(target+":"+timeline);
            $("#page_number").text(1);
            var refresh_rate;
            if(refresh_rate=get_cookie('refresh_rate')){
                //OK!
            }else{
                refresh_rate = 3;
            }
			timeline_update();
			timeline_refresh=setInterval('timeline_update()', (refresh_rate*60000));
            //$("#username_cell").html(refresh_rate);
		});
	}
//** MONITOR_AJAX_TRANSACTIONS - start/stop refresh icon
	function monitor_ajax_transactions(){
		$(".refresh_status").ajaxStart(function(){
			$(this).attr("src", "images/throbber.gif");
			refresh_timer = setTimeout('$(this).attr("src", "images/arrow_refresh.png");',15000);
		});
		$(".refresh_status").ajaxStop(function(){
			$(this).attr("src", "images/arrow_refresh.png");
			adjust_size();
		});
		$(".refresh_status").ajaxError(function(){
			$(this).attr("src", "images/arrow_refresh.png");
			adjust_size();
		});
	}
	
//** SET_VIEW - this is either logged_in or logged_out
	function set_view(view){
		if(view=="logged_in"){
			username=get_cookie("username");
			var username_link='';
			if(srv_url=="http://twitter.com"){
				username_link='<a href="'+srv_url+'/home" title="Twitter Home" target="_blank">'+username+'</a>';
			}else{
				username_link='<a href="'+srv_url+'/'+username+'" title="Home" target="_blank">'+username+'</a>';
			}
			$("#username_cell").html(username_link);
			var app_link='<a id="app_home" href="http://32hours.com" target="_blank">'+app_name+'</a>'
			$("#app_name").html(app_link);
			//$("#main_menu").prepend("<div>"+username_link+"</div>");
			$("#message_textarea_error").html("").hide();
			$(".logged_out_block").hide();
			$(".logged_in_block").slideDown();
			//had the user been viewing a specific tab?
			if(st=get_cookie('selected_tab')){
				//select the tab!
				//$("#"+st).click();
				// if "other" was selected, also restore the sub-selection
				if (st=="other_tab"){
					if(ot=get_cookie('other_tab')){
						$("#"+ot).click();
						// OK!
					}else{
						// Not OK!
						ot="other_public_timeline_tab";
						$("#"+ot).click();
					}
				}
				$("#"+st).click();
			}else{
				set_cookie('selected_tab', "friends_timeline_tab", 90);
				st=get_cookie('selected_tab');
				$("#"+st).click();
			}
		}else{			//logged out
			set_cookie('cookie_verify', "true", 90);
			var cv=get_cookie('cookie_verify');
			if(cv=='true'){
				// do nuttin.  it's OK.
				//$("#service_logon_message").html("");
			}else{
				$("#service_logon_message").html("Cookie error: Is your browser allowing cookies from http://betwittered.com ?");
			}	
			$("#username_cell").html("<a href='http://32hours.com' target='top'>BeTwittered</a>");
			$("#app_name").html("<a href='http://32hours.com' target='top'>32Hours.com</a>");
			$(".logged_in_block").hide();
			$(".logged_out_block").slideDown();
		}
	}

//** VERIFY_CREDENTIALS		
	function verify_credentials(){
		var response;
		$.ajax({
				type: "get",
				cache: false,
				url: "http://betwittered.com/api/",
				data: "req=verify_credentials&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password')),
				async: false,
				success: function(data){
					response=data;
				},
				error: function(data){
					//$("#refresh_button_img").attr("src", "images/arrow_refresh.png");
					response=data;
				}
		});
		return(response);
	}
	
	//** VERIFY_CREDENTIALS		
	function delete_message(msg_id){
		var response;
		$.ajax({
				type: "get",
				cache: false,
				url: "http://betwittered.com/api/",
				data: "req=delete_message&message_id="+msg_id+"&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password')),
				async: false,
				dataType: 'json',
				success: function(data){
					response=data;
				},
				error: function(data){
					//$("#refresh_button_img").attr("src", "images/arrow_refresh.png");
					response=data;
				}
		});
		//alert(response);
		return(response);
	}

//** GET_RATE_LIMIT_STATUS
	function get_rate_limit_status(){
		
		var response="none";
		$.ajax({
			type: "get",
			url: "http://betwittered.com/api/",
			data: "req=rate_limit_status&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password')),
			async: false,
			dataType: 'json',
			success: function(data){
				response=data;
			},
			error: function(data){
				response=data;
			}
		});
		//json_response=eval('(' + response + ')');
		if(remaining=response.remaining_hits){
			// OK
		}else{
			remaining="-";
		}
		if(limit=response.hourly_limit){
			// OK
		}else{
			limit="-";
		}
		return(remaining+"/"+limit);

		return("-");
	}	
//* CLEAR_TIMELINE _ NEW
	function clear_timeline(timeline){
		if(timeline){ // set the tab to be cleared
			tab=timeline;
		}else{  // timeline was not passed to this function, clear the current timeline
			// get ST or OT setting to figure out the current tab
			if(st=get_cookie('selected_tab')){
				// OK!
			}else{
				st="friends_timeline_tab";
			}

			if(st=="other_tab"){
					target="#other_target";
				if(ot=get_cookie('other_tab')){
					// OK
				}else{
					ot="other_public_timeline_tab";
				}
				timeline=$("#"+ot).attr("uri");
				// set "tab" for use as target timeline
				tab=ot;
			}else{	
				// set "tab" for use as target timeline
				tab=st;
			}
		}

		// OK, we have the tab, now clear the status_count attr,the since_id attr, and the timeline table
		$("#"+tab).attr("since_id",1);
		$("#"+tab).attr("status_count",1);
		$("#"+tab+"_target > *").remove();

	}
	
//* CLEAR_TIMELINE
	function clear_timeline_old(){
		// get ST or OT setting to figure out the current tab
		if(st=get_cookie('selected_tab')){
			// OK!
		}else{
			st="friends_timeline_tab";
		}

		if(st=="other_tab"){
				target="#other_target";
			if(ot=get_cookie('other_tab')){
				// OK
			}else{
				ot="other_public_timeline_tab";
			}
			timeline=$("#"+ot).attr("uri");
			// set "tab" for use as target timeline
			tab=ot;
		}else{	
			// set "tab" for use as target timeline
			tab=st;
		}
		// OK, we have the tab, now clear the status_count attr,the since_id attr, and the timeline table
		$("#"+tab).attr("since_id",1);
		$("#"+tab).attr("status_count",1);
		$("#"+tab+"_target > *").remove();

	}
	
//** TIMELINE_UPDATE
	function timeline_update(page){
		
        if (page==null){
            page=1;
        }
		if(st=get_cookie('selected_tab')){
			// OK!
		}else{
			st="friends_timeline_tab";
		}
		target=$("#"+st).attr("href");
		timeline=$("#"+st).attr("uri");
		random_number=get_cookie("random_number");
		//$("#send_button").val(target+":"+timeline);				
		if(st=="other_tab"){
				target="#other_target";
            if(ot=get_cookie('other_tab')){
                // OK
            }else{
                ot="other_public_timeline_tab";
            }
			timeline=$("#"+ot).attr("uri");
			// set "tab" for use as target timeline
			tab=ot;
		}else{	
			// set "tab" for use as target timeline
			tab=st;
		}		
		
		//get the last message ID recieved,
		if($("#"+tab).attr("since_id")){
			since_id = $("#"+tab).attr("since_id");
		}else{
			$("#"+tab).attr("since_id",1);
			since_id = 1;
		}
		switch(tab){
			case "friends_tab":
				timeline="friends_timeline";
				break;
			case "replies_tab":
				timeline="mentions";
				break;
			case "direct_messages_tab":
				timeline="direct_messages";
				break;
			case "other_favorites_tab":
				timeline="favorites";
				break;			
			case "other_archive_tab":
				timeline="user_timeline";
				break;			
			default:
				timeline="public_timeline";
		}
		/* <!-- SEARCH_ADDED
		if(!search_text=get_cookie("search_text")) search_text="none";
		if(!search_timeline_text=get_cookie("search_timeline_text"))search_timeline_text="none";
		*/ 
		$.ajax({
			type: "get",
			url: "http://betwittered.com/api/",
			data: "req="+timeline+"&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password'))+"&since_id="+since_id+"&page="+page, 
			async: true,
			cache: false,
			dataType: 'json',
			success: function(data){
				// direct message timelines are formatted differently
				if(timeline.indexOf("direct")!=-1){
					decode_direct(data,tab);
				}else{
					decode_timeline(data,tab);
				}
				// now hide the controls
				$(".msg_controls").hide()
				//$(target).html(tweets);
				$("#page_number").text(page);
				
				// these redundant image source settings are to make up for monitor_ajax_requests losing track occasionally,
				$(this).attr("src", "images/arrow_refresh.png");
					
				// recalc relative time for each message
				recalc_relative_time();
				// add onmouseover effect to controls
				onmouseover_controls();

			},
			error: function(data){
				$.jGrowl("Could not contact http://betwittered.com", {sticky: false});
				$(this).attr("src", "images/arrow_refresh.png");

				// recalc relative time for each message
				recalc_relative_time();
			}
		});
		if(api_url.toLowerCase()=="http://twitter.com"){
			var rls=get_rate_limit_status();
			$("#rate_limit_status").html(rls);
		}
		// the app footer tends to "float" after an initial timeline refresh();
		reset_app_footer();
	}
//** ONMOUSEOVER_CONTROLS
    function onmouseover_controls(){
		$(".msg_control").hover(
            function(){
                $(this).css("border", "1px solid #cccccc");
            },
            function(){
                $(this).css("border", "1px solid transparent");
            }
        );
	}

//** MESSAGE FUNCTIONS (BUTTON CLICKS)
	function reply_click(recipient,msg_id){
		var show_controls=get_cookie("show_controls");
		$("#message_textarea").val("@"+recipient+" ").focus();
		// in_reply_to_status_id
		$("#reply_button").show().attr("in_reply_to_status_id", msg_id);
		$("#send_button").hide();
		$("#message_textarea").keyup();
		if(show_controls=="false"){
			$("#control_area_toggle").click();
		}
	 }
	function direct_click(recipient){
		var show_controls=get_cookie("show_controls");
		$("#message_textarea").val("d "+recipient+" ").focus();
		$("#message_textarea").keyup();
		if(show_controls=="false"){
			$("#control_area_toggle").click();
		}
	}
	function retweet_click(recipient,msg){
		msg=unescape(msg);
		var show_controls=get_cookie("show_controls");
		$("#message_textarea").val("RT @"+recipient+": "+msg).focus();
		$("#message_textarea").keyup();
		if(show_controls=="false"){
			$("#control_area_toggle").click();
		}
	}
	function favorite_click(msg_id){
		toggle_favorite(msg_id);
	}
	function delete_click(msg_id){
		// confirm delete request	
		if (!confirm("Are you sure you want to DELETE this message forever?")){
		  return false;
		}
		//if(delete_message(msg_id)==true){
		//	$("#msg_row_"+msg_id).remove();
		//}
		delete_message(msg_id);
		clear_timeline();
		timeline_update();
	}
	function more_info_click(msg_id,tab){
		if(tab=="other_tab"){
			thistab=get_cookie('other_tab');
		}else{
			thistab=tab;
		}
		more_info(msg_id,thistab);
	}
	
//** DECODE_TIMELINE
	function decode_timeline(data,tab){
		//get the last message ID recieved, and the total statuses in the timeline
		if($("#"+tab).attr("since_id")){
			since_id = $("#"+tab).attr("since_id");
		}else{
			$("#"+tab).attr("since_id",1);
			since_id = 1;
		}		
		//get the total statuses in the timeline
		if($("#"+tab).attr("status_count")){
			status_count = $("#"+tab).attr("status_count");
		}else{
			$("#"+tab).attr("status_count",0);
			status_count = 0;
		}
		retval = "";
		//for(var i=data.length-1; i>=0; i--) {
		//if(data==null||data=="")return true;
		for(i in data.reverse()){
			// check to make sure were not re-posting any old messages already in the timeline tab
			if(data[i]['id']<=since_id)break;
			
			
			favorited=data[i]['favorited'];
			fav_image="images/favorite_"+favorited+".gif";
			selected_tab=get_cookie('selected_tab');
			msg_controls="<span class='msg_controls' id='msg_controls_"+data[i].id+"'>";
			if(search_tab=get_cookie("search_tab")){
				if(search_tab!="visible"){
					msg_controls +='<a id="more_info_'+data[i]['id']+'" onclick="more_info_click('+data[i].id+',\''+tab+'\')" style="border: 1px solid transparent;" msg_func="more_info" class="msg_control" msg_id="'+data[i]['id']+'" title="More Info" tab="'+tab+'">'+
										'<img src="images/more_info.png" class="ctl_image"/>'+
									'</a> ';
				}
			}else{
				msg_controls +='<a id="more_info_'+data[i]['id']+'" onclick="more_info_click('+data[i].id+',\''+tab+'\')" style="border: 1px solid transparent;" msg_func="more_info" class="msg_control" msg_id="'+data[i]['id']+'" title="More Info" tab="'+tab+'">'+
									'<img src="images/more_info.png" class="ctl_image"/>'+
								'</a> ';
			}
			// no reply feature in the DM tab, and no reply to self!
			if(selected_tab!="direct_messages_tab"){
				if(data[i].user.screen_name!=get_cookie('username')){
					msg_controls  +='<a id="reply_to_'+data[i]['id']+'"  onclick="reply_click(\''+data[i].user.screen_name+'\','+data[i].id+')"style="border: 1px solid transparent;" msg_func="reply" class="msg_control" sender="'+data[i]['user']['screen_name']+'" msg_id="'+data[i]['id']+'" title="Send a reply">'+
										'<img src="images/reply.gif" class="ctl_image"/>'+
									'</a> ';
				}
			}
			// no replying to yourself!
			if(data[i].user.screen_name!=get_cookie('username')){
				msg_controls +='<a id="direct_to_'+data[i]['id']+'" onclick="direct_click(\''+data[i].user.screen_name+'\')" style="border: 1px solid transparent;" msg_func="direct" class="msg_control" sender="'+data[i]['user']['screen_name']+'" msg_id="'+data[i]['id']+'" title="Send a direct message">'+
					'<img src="images/direct.gif" class="ctl_image"/>'+
					'</a> ';
			}
			// no retweeting yourself! (you should be ashamed)
			if(data[i].user.screen_name!=get_cookie('username')){
				msg_controls +='<a id="retweet_'+data[i]['id']+'" onclick="retweet_click(\''+data[i].user.screen_name+'\',\''+escape(data[i].text)+'\')" style="border: 1px solid transparent;" msg_func="retweet" class="msg_control" sender="'+data[i]['user']['screen_name']+'" msg_id="'+data[i]['id']+'" title="Retweet message">'+
					'<img src="images/retweet.gif" class="ctl_image"/>'+
					'</a> ';
			}
			msg_controls +='<a id="favorite_'+data[i].id+'"  onclick="favorite_click('+data[i].id+')" style="border: 1px solid transparent;" favorited="'+favorited+'" msg_func="favorite" class="msg_control" sender="'+data[i].user.screen_name+'" msg_id="'+data[i].id+'" title="Favorite on/off">'+
				'<img class="favorite_image_'+data[i].id+'" src="'+fav_image+'" class="ctl_image"/>'+
				'</a>';
			// your message?  then add a delete button
			if(data[i].user.screen_name==get_cookie('username')){
				msg_controls +='  <a id="delete_'+data[i].id+'"  onclick="delete_click('+data[i].id+')" style="border: 1px solid transparent;" msg_func="favorite" class="msg_control" sender="'+data[i].user.screen_name+'" msg_id="'+data[i].id+'" title="Delete Message">'+
					'<img class="delete_image" src="images/delete.gif" class="ctl_image"/>'+
					'</a>';
			}
			msg_controls += '</span>';
			
			
			retval += '<tr class="message_row" id="message_row_'+data[i].id+'"onmouseover="$(\'#msg_controls_'+data[i].id+'\').show();$(\'#timestamp_'+data[i].id+'\').hide();" onmouseout="$(\'#msg_controls_'+data[i].id+'\').hide();$(\'#timestamp_'+data[i].id+'\').show();">';
						if(get_cookie('pics')=="true") retval += "<td><a target='_blank' href='http://twitter.com/"+data[i].user.screen_name+"' title='Go to "+data[i]['user']['screen_name']+"'>";
							if(get_cookie('pics')=="true") retval +="<img align='left' style='padding: 0em .25em .25em .0em; max-height:48px; max-width:48px;' src='"+data[i]['user']['profile_image_url']+"'/></a></td>";
						retval +="<td class='text_td' ><span id='tweet_text_d_"+data[i]['id']+"' class='tweet_text_d' favorited='"+data[i]['favorited']+"' msg_id='"+data[i]['id']+"' sender='"+data[i]['user']['screen_name']+"' tab='"+st+"'>";
						retval += "<div class='msgh'>"+
							"<span class='msgh_user_id'>"+
								"<a target='_blank' href='http://twitter.com/"+data[i]['user']['screen_name']+"' title='Go to "+data[i]['user']['screen_name']+"'  style='border: 1px solid transparent;'>"+data[i]['user']['screen_name']+"</a> "+
							"</span>";
								if(get_cookie('timestamps')=="true") retval+="<span class='timestamp' id='timestamp_"+data[i].id+"' time='"+data[i].created_at+"'>"+relativeTime(data[i]['created_at'])+" </span>";
								retval += msg_controls +
						"</div>"+
						"<span id='msg_text_"+data[i]['id']+"' class='message_text'>"+createLinks(data[i]['text'])+"</span>"+
						"</span>" +
						"</td>"+
						"</tr>";
			retval += '<tr id="'+tab+'_'+data[i]['id']+'" style="display:none;">';
			if(get_cookie('pics')=="true") retval += '<td><!-- cell under pic --></td>';

			retval +='<td  id="extended_user_info_'+tab+'_'+data[i]['id']+'" class="extended_user_info">';
			msg_url = 'http://twitter.com/'+data[i]['user']['screen_name']+'/statuses/'+data[i]['id'];
			if(data[i]['in_reply_to_status_id']!=null){
				reply_url= 'http://twitter.com/'+data[i]['in_reply_to_screen_name']+'/statuses/'+data[i]['in_reply_to_status_id'];
			}
			retval += '<div id="ext_target_info_'+tab+'_'+data[i]['id']+'" class="extended_user_info">Source: '+data[i]['source']+
						'<br/> Name: '+data[i]['user']['screen_name']+
						'<br/> URL: <a href="'+data[i]['user']['url']+'" target="_blank">'+data[i]['user']['url']+'</a>'+
						'<br/> Location: '+data[i]['user']['location']+
						'<br/> Description: '+data[i]['user']['description']+
						'<br/> Followers: '+data[i]['user']['followers_count']+
						'<br/> Msg ID: <a href="'+msg_url+'" target="_blank">'+data[i]['id']+'</a>';
			if(data[i]['in_reply_to_status_id']!=null){
				retval+='<br/> Reply to: <a href="'+reply_url+'" target="_blank">'+data[i]['in_reply_to_status_id']+'</a>';
			}
			retval+='</div>'+
					'<div id="ext_target_tweet_'+tab+'_'+data[i]['id']+'"></div>'+
					'<div id="ext_footer_'+tab+'_'+data[i]['id']+'">'+
						'<!--<img src="images/control_eject_blue.png" style="height: 1em;" onclick="userEject(\''+tab+'_'+data[i]['id']+'\'); return false;" alt="Less" title="Show Less"/>-->';
					'</div>'+
				'</td>'+
				'</tr>';
			$("#"+tab+"_target").prepend(retval);
			$("#message_row_"+data[i].id).hide().fadeIn('slow');
			retval = "";
			
			since_id=data[i]['id'];
			$("#"+tab).attr("since_id",since_id);
			
			status_count++;
			$("#"+tab).attr("status_count",status_count);
			
			if(status_count>=rpp){
				$("#"+tab+"_target .message_row:last").remove();
				status_count--;
				$("#"+tab).attr("status_count",status_count);
			}
		
		}
	}
// DECODE_DIRECT
	function decode_direct(data,tab){
		//get the last message ID recieved, and the total statuses in the timeline
		if($("#"+tab).attr("since_id")){
			since_id = $("#"+tab).attr("since_id");
		}else{
			$("#"+tab).attr("since_id",1);
			since_id = 1;
		}		
		//get the total statuses in the timeline
		if($("#"+tab).attr("status_count")){
			status_count = $("#"+tab).attr("status_count");
		}else{
			$("#"+tab).attr("status_count",0);
			status_count = 0;
		}
		retval = "";
		//for(var i=data.length-1; i>=0; i--) {
		if(!data)return true;
		for(i in data.reverse()){
			// check to make sure were not re-posting any old messages already in the timeline tab
			if(data[i]['id']<=since_id)break;
			
			
			//favorited=data[i].favorited;
			//fav_image="images/favorite_"+favorited+".gif";
			selected_tab=get_cookie('selected_tab');
			msg_controls="<span class='msg_controls' id='msg_controls_"+data[i].id+"'>";
			if(search_tab=get_cookie("search_tab")){
				if(search_tab!="visible"){
					msg_controls +='<a id="more_info_'+data[i]['id']+'" onclick="more_info_click('+data[i].id+',\''+tab+'\')" style="border: 1px solid transparent;" msg_func="more_info" class="msg_control" msg_id="'+data[i]['id']+'" title="More Info" tab="'+tab+'">'+
										'<img src="images/more_info.png" class="ctl_image"/>'+
									'</a> ';
				}
			}else{
				msg_controls +='<a id="more_info_'+data[i]['id']+'" onclick="more_info_click('+data[i].id+',\''+tab+'\')" style="border: 1px solid transparent;" msg_func="more_info" class="msg_control" msg_id="'+data[i]['id']+'" title="More Info" tab="'+tab+'">'+
									'<img src="images/more_info.png" class="ctl_image"/>'+
								'</a> ';
			}
			if(selected_tab!="direct_messages_tab"){
				msg_controls  +='<a id="reply_to_'+data[i]['id']+'"  onclick="reply_click(\''+data[i].sender.screen_name+'\','+data[i].id+')"style="border: 1px solid transparent;" msg_func="reply" class="msg_control" sender="'+data[i]['sender']['screen_name']+'" msg_id="'+data[i]['id']+'" title="Send a reply">'+
									'<img src="images/reply.gif" class="ctl_image"/>'+
								'</a> ';
			}
			msg_controls +='<a id="direct_to_'+data[i]['id']+'" onclick="direct_click(\''+data[i].sender.screen_name+'\')" style="border: 1px solid transparent;" msg_func="direct" class="msg_control" sender="'+data[i]['sender']['screen_name']+'" msg_id="'+data[i]['id']+'" title="Send a direct message">'+
				'<img src="images/direct.gif" class="ctl_image"/>'+
				'</a> ';
			//msg_controls +='<a id="retweet_'+data[i]['id']+'" onclick="retweet_click(\''+data[i].sender.screen_name+'\',\''+escape(data[i].text)+'\')" style="border: 1px solid transparent;" msg_func="retweet" class="msg_control" sender="'+data[i]['sender']['screen_name']+'" msg_id="'+data[i]['id']+'" title="Retweet message">'+
			//	'<img src="images/retweet.gif" class="ctl_image"/>'+
			//	'</a> ';
			//msg_controls +='<a id="favorite_'+data[i].id+'"  onclick="favorite_click('+data[i].id+')" style="border: 1px solid transparent;" favorited="'+favorited+'" msg_func="favorite" class="msg_control" sender="'+data[i].sender.screen_name+'" msg_id="'+data[i].id+'" title="Favorite on/off">'+
			//	'<img class="favorite_image_'+data[i].id+'" src="'+fav_image+'" class="ctl_image"/>'+
			//	'</a>';
			msg_controls += '</span>';
			
			
			retval += '<tr class="message_row" onmouseover="$(\'#msg_controls_'+data[i].id+'\').show();$(\'#timestamp_'+data[i].id+'\').hide();" onmouseout="$(\'#msg_controls_'+data[i].id+'\').hide();$(\'#timestamp_'+data[i].id+'\').show();">';
						if(get_cookie('pics')=="true") retval += "<td><a target='_blank' href='http://twitter.com/"+data[i].sender.screen_name+"' title='Go to "+data[i]['sender']['screen_name']+"'>";
							if(get_cookie('pics')=="true") retval += "<img align='left' style='padding: 0em .25em .25em .0em; max-height:48px; max-width:48px;' src='"+data[i]['sender']['profile_image_url']+"'/></a></td>";
						retval += "<td class='text_td' ><span id='tweet_text_d_"+data[i]['id']+"' class='tweet_text_d' favorited='"+data[i]['favorited']+"' msg_id='"+data[i]['id']+"' sender='"+data[i]['sender']['screen_name']+"' tab='"+st+"'>"+
						"<div class='msgh'>"+
							"<span class='msgh_user_id'>"+
								"<a target='_blank' href='http://twitter.com/"+data[i]['sender']['screen_name']+"' title='Go to "+data[i]['sender']['screen_name']+"'  style='border: 1px solid transparent;'>"+data[i]['sender']['screen_name']+"</a> "+
							"</span>";
								if(get_cookie('timestamps')=="true") retval += "<span class='timestamp' id='timestamp_"+data[i].id+"' time='"+data[i].created_at+"'>"+relativeTime(data[i]['created_at'])+" </span>";
								retval += msg_controls +
						"</div>"+
						"<span id='msg_text_"+data[i]['id']+"' class='message_text'>"+createLinks(data[i]['text'])+"</span>"+
						"</span>" +
						"</td>"+
						"</tr>";
			retval += '<tr id="'+tab+'_'+data[i]['id']+'" style="display:none;">';
			if(get_cookie('pics')=="true") retval += '<td><!-- cell under pic --></td>';

			retval +='<td  id="extended_user_info_'+tab+'_'+data[i]['id']+'" class="extended_user_info">';
			msg_url = 'http://twitter.com/'+data[i]['sender']['screen_name']+'/statuses/'+data[i]['id'];
			if(data[i]['in_reply_to_status_id']!=null){
				reply_url= 'http://twitter.com/'+data[i]['in_reply_to_screen_name']+'/statuses/'+data[i]['in_reply_to_status_id'];
			}
			retval += '<div id="ext_target_info_'+tab+'_'+data[i]['id']+'" class="extended_user_info">Source: '+data[i]['source']+
						'<br/> Name: '+data[i]['sender']['screen_name']+
						'<br/> URL: <a href="'+data[i]['sender']['url']+'" target="_blank">'+data[i]['sender']['url']+'</a>'+
						'<br/> Location: '+data[i]['sender']['location']+
						'<br/> Description: '+data[i]['sender']['description']+
						'<br/> Followers: '+data[i]['sender']['followers_count']+
						'<br/> Msg ID: <a href="'+msg_url+'" target="_blank">'+data[i]['id']+'</a>';
			if(data[i]['in_reply_to_status_id']!=null){
				retval+='<br/> Reply to: <a href="'+reply_url+'" target="_blank">'+data[i]['in_reply_to_status_id']+'</a>';
			}
			retval+='</div>'+
					'<div id="ext_target_tweet_'+tab+'_'+data[i]['id']+'"></div>'+
					'<div id="ext_footer_'+tab+'_'+data[i]['id']+'">'+
						'<!--<img src="images/control_eject_blue.png" style="height: 1em;" onclick="userEject(\''+tab+'_'+data[i]['id']+'\'); return false;" alt="Less" title="Show Less"/>-->';
					'</div>'+
				'</td>'+
				'</tr>';
			$("#"+tab+"_target").prepend(retval);
			retval = "";
			
			since_id=data[i]['id'];
			$("#"+tab).attr("since_id",since_id);
			
			status_count++;
			$("#"+tab).attr("status_count",status_count);
			
			if(status_count>=rpp){
				$("#"+tab+"_target .message_row:last").remove();
				status_count--;
				$("#"+tab).attr("status_count",status_count);
			}
		
		}
	}
	
// CREATELINKS
	function createLinks(messageText){
			// create links of URLs
		var pattern = /(((ht|f)tp(s?))\:\/\/{1}[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/ig;
		urlArray = messageText.match(pattern);
		var linkVal = "";
		if(urlArray){
			$.each(urlArray, function(key, val){
				if(val.length>20){
					linkVal =val.slice(0,16);
					linkVal+="...";
				}else{
					linkVal=val;
				}
				messageText=messageText.replace(val, "<a href=\""+val+"\" target=\"_blank\" title=\""+val+"\">"+linkVal+"</a>");
			});
		}
		//create links of @ references
		pattern = /@{1}[-a-zA-Z0-9%_\+~&\/\/=]+/ig;				
		atArray = messageText.match(pattern);
		if(atArray){
			$.each(atArray, function(key, val){
				shortVal = val.replace(/@/,"");
				messageText=messageText.replace(val, "<a href=\"http://twitter.com/"+shortVal+"\" target=\"_blank\"  title=\"http://twitter.com/"+shortVal+"\">"+val+"</a>");
			});
		}
		//create links of # references
		pattern = /#{1}[-a-zA-Z0-9%_\+~&\/\/=]+/ig;				
		hashArray = messageText.match(pattern);
		if(hashArray){
			$.each(hashArray, function(key, val){
				//shortVal = val.replace(/#/,"");
				messageText=messageText.replace(val, "<a href=\"http://search.twitter.com/search?q="+encodeURIComponent(val)+"\" target=\"_blank\" title=\"Search Twitter for "+val+"\">"+val+"</a>");
			});
		}
		return(messageText);
	}

//** TOGGLE FAVORITE STATUS
    function toggle_favorite(msg_id){
		
		favorite_status=$("#favorite_"+msg_id).attr("favorited");
		if(favorite_status=="true"){
			action="destroy";
		}else{
			action="create";
		}
				
		$.ajax({
			type: "get",
			url: "http://betwittered.com/api/",
			data: "req=toggle_favorite&msg_id="+msg_id+"&status="+action+"&username="+get_cookie('username')+"&password="+urlencode(get_cookie('password')),
			async: true,
			success: function(data){
				//if(data!=200){
					//alert("Twitter replied with error: "+data);
				//}else{
					if(favorite_status=="false"){
						favorited="true";
					}else{
						favorited="false";
					}
					$(".favorite_image_"+msg_id).attr("src", "images/favorite_"+favorited+".gif");
					$("#favorite_"+msg_id).attr("favorited", favorited);
					$(this).attr("src", "images/arrow_refresh.png");
				//}
				//clear_timeline("favorites");
				//timeline_update();
			},
			error: function(data){
				//$("#refresh_button_img").attr("src", "images/arrow_refresh.png");
            	$("#message_textarea_error").text("Could not contact http://betwittered.com").show();
				$(this).attr("src", "images/arrow_refresh.png");
				
			}
		});
		if(api_url.toLowerCase()=="http://twitter.com"){
			var rls=get_rate_limit_status();
			$("#rate_limit_status").html(rls);
		}
	}

//** SET_COOKIE
	function set_cookie(c_name,value,expiredays){
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
	}

//** GET_COOKIE
	function get_cookie(c_name){
		if (document.cookie.length>0){
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		return "";
	}

//** MORE_INFO
	function more_info(id,tab){
		// this function hides/shows user info element by ID.
		
		element=$("#"+id);
		tweet_element=$("#ext_target_tweet_"+id);
		info_element=$("#ext_target_info_"+id);
        dialog_info=$("#extended_user_info_"+tab+"_"+id).html();
		
		//$.jGrowl("("+id+")"+tab, {sticky:true});
        $.jGrowl(dialog_info, {sticky: true});
    }
	
//**GET URLPARAMS get a parameter from the current URL
	function getUrlParm(name){
		var name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		
		if( results == null ){
			return "";
		}else{
			return results[1];
		}
	}
	
	function get_trends(){
		$.ajax({
			url: "http://search.twitter.com/trends.json",
			type: "GET",
			dataType: "jsonp", //for web
			//dataType: "json", //for AIR
			success: function(data){
				parseTrends(data);
				//$.jGrowl("Refreshed!");
				//$(".refreshStatus").text("success");
			},
			timeout: function(){
				$.jGrowl("Error connecting to BeTwittered.com");
			}
		});
	}
	
	function parseTrends(data){
		var trendsResponse = new Array();
		var name="";
		var i=0;
		
		$("#other_target").text(""); //blank out the feed output area.
		$.each(data, function(respKey, respVal){
			if(respKey=="trends"){
				//$("#feed").append("Trends: <br>");
				$.each(respVal, function(key, val){
					$.each(val, function(trendKey, trendVal){
						//trendVal = unescape(trendVal);
						//$("#feedRaw").append(trendKey+": "+trendVal+"<br>");
						if(trendKey=="name"){
							name=trendVal;
						}else{
							i++;
							//$("#feed").append("<a href=\""+trendVal+"\" rel=\""+i+"\">"+name+"</a><br>");
							$("#other_target").append("<li><a href=\""+trendVal+"\" rel=\""+i+"\" target=\"_blank\">#"+i+" "+name+"</a></li>");
						}
					});
					
				});
			}
			if(respKey=="as_of"){
				$(".asOf").html(respVal);
			}
		});
	}
	
	function recalc_relative_time(){
		$(".timestamp").each(function(){
			time=$(this).attr("time");
			reltime=relativeTime(time);
			$(this).text(reltime);
		});
		//alert("RECALC'D AT "+new Date());
	}

	function RRRRRRRRRRrelativeTime(time_value) {
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		if(delta < 60) {
			return 'under a minute ago';
		} else if(delta < 120) {
			return 'about a minute ago';
		} else if(delta < (45*60)) {
			return (parseInt(delta / 60)).toString() + ' minutes ago';
		} else if(delta < (90*60)) {
			return 'about an hour ago';
		} else if(delta < (24*60*60)) {
			if (parseInt(delta / 3600)==1) return 'about an hour ago';
			return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
		} else if(delta < (48*60*60)) {
			return 'a day ago';
		} else {
			return (parseInt(delta / 86400)).toString() + ' days ago';
		}
	}
	
	function relativeTime(time_value) {
		var values = time_value.split(" ");
		time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		delta = delta + (relative_to.getTimezoneOffset() * 60);

		if (delta < 60) {
			return 'Under a minute ago';

		} else if(delta < 120) {
			return 'About a minute ago';

		} else if(delta < (60*60)) {
			return (parseInt(delta / 60)).toString() + ' minutes ago';

		} else if(delta < (120*60)) {
			return 'About an hour ago';

		} else if(delta < (24*60*60)) {
			return 'About ' + (parseInt(delta / 3600)).toString() + ' hours ago';

		} else if(delta < (48*60*60)) {
			return '1 day ago';

		} else {
			return (parseInt(delta / 86400)).toString() + ' days ago';

		}
	}
	
////////////////////  IG specifics
function getParameters(url) {
	var lib_string_regex = new RegExp('libs=([^&]*)', 'g');
	var lib_string = lib_string_regex.exec(url);
	var libs = lib_string[1].split(',');

	return libs;
}

function getIGScripts() {
	var params = getParameters(window.location.href);
	var scriptURL = "";
	//$.jGrowl("(getIGScripts)");
	for(i in params) {
		scriptURL = "http://www.google.com/ig/f/" + params[i];
		$.getScript(scriptURL);
		//$.jGrowl("("+scriptURL+")", {sticky:true});
	}
}
