// JavaScript Document

//<![CDATA[

	var map;
    var gdir;
    var geocoder = null;
    var addressMarker;

    function initialize() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(48.232464, -101.295834), 13);
		map.enableScrollWheelZoom();
        geocoder = new GClientGeocoder();
      }
    }
	
	function showAddress(name, address, image, text, screen_name) {
		
		text = make_links(text);
		address = get_address(text, address);
		if(name != screen_name){ name = screen_name+" ("+name+")"; }
	
	  if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.panTo(point);
			  map.setCenter(point, 4);
			  
			  var new_icon = new GIcon()  
				new_icon.image = "includes/phpThumb/phpThumb.php?src="+image+"&w=24&fltr[]=bord|1|12|12|999999&f=png";
				new_icon.size = new GSize(24,24)  
				new_icon.iconAnchor = new GPoint(12,24)  
				new_icon.infoWindowAnchor = new GPoint(20,12)  
				
				var opt  
				opt = {}  
				
				opt.icon = new_icon 
				opt.draggable = false  
				opt.clickable = false  
				opt.dragCrossMove = true 
			  
              var marker = new GMarker(point, opt);
              map.addOverlay(marker);
              marker.openInfoWindowHtml("<div style='width:250px;'><a href='http://twitter.com/"+screen_name+"'><img src='"+image+"' style='float:left; margin-right:5px; margin-bottom:5px; border:1px solid #999999;'></a><div style='font-size:10px; padding-bottom:5px;'><a href='http://twitter.com/"+screen_name+"'>"+name+"</a></div>"+text+"</div><div style='font-size:10px; padding-top:5px;'>"+address+" - <a onclick=\"javascript:document.update_form.status_box.value='@"+screen_name+" '; new Effect.Appear('update_status');\">reply</a></div>");
			  
			  //marker.openInfoWindowHtml("<div style='width:250px;'><div style='font-size:10px; padding-bottom:10px;'>post by <a href='http://twitter.com/"+screen_name+"'>"+name+"</a></div>"+text+"</div>");
			  //marker.setImage("phpThumb/phpThumb.php?src="+image+"");
			  
            }
          }
        );
      }
    }
	
    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("We could not find that address. Please try something else! Don't forget your city and state.\n\n- My Tweet Map");
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	   else alert("An unknown error occurred.");
	}

	
	
//]]>



var username = "";
var password = "";

var current_post = 0;

function login(user, pass){

	username = user;
	password = pass;
	
	if(document.getElementById&&document.getElementsByTagName&&document.createElement){
        // load XML file
        sendRequest('includes/get_xml.php?username='+username+'&password='+password);
    }
	
	//document.getElementById('login').style.display = 'none';
	//Effect.Fade(document.getElementById('login'));
	Effect.Fade('login');
	Effect.Appear('click_update_status');
	
}



function change_post(id){
	
	showAddress(data2[id].getElementsByTagName('name')[0].firstChild.nodeValue, data2[id].getElementsByTagName('location')[0].firstChild.nodeValue, data2[id].getElementsByTagName('profile_image_url')[0].firstChild.nodeValue, data[id].getElementsByTagName('text')[0].firstChild.nodeValue, data2[id].getElementsByTagName('screen_name')[0].firstChild.nodeValue);
	
	current_post = id;

}




function make_links(text){
	
	if(text.search("http://") != -1)
	{
		
		text_2 = text+" ";
		
		while(text_2.search("http://") != -1)
		{
			pos_at = text_2.indexOf("http://");
			pos_space = text_2.substr(pos_at);
			pos_space = pos_space.indexOf(" ");
			
			found = text_2.substr(pos_at, pos_space);
			
			text = text.replace(found, "<a href='"+found+"' target='_blank'>"+found+"</a>");
			
			text_2 = text_2.substr(pos_at+7);
		
		}
	
	}
	
	if(text.search("@") != -1)
	{
		
		text_2 = text+" ";
		
		while(text_2.search("@") != -1)
		{
			pos_at = text_2.indexOf("@")+1;
			pos_space = text_2.substr(pos_at);
			pos_space = pos_space.indexOf(" ");
			
			found = text_2.substr(pos_at, pos_space);
			
			text = text.replace(found, "<a href='http://twitter.com/"+found+"' target='_blank'>"+found+"</a>");
			
			text_2 = text_2.substr(pos_at+1);
		
		}
	
	}
	
	return text;

}




function get_address(text, address){
	
	if(text.search("l:") != -1)
	{
		
		text_2 = text+" ";

		pos_at = text_2.indexOf("l:")+2;
		pos_space = text_2.substr(pos_at);
		pos_space = pos_space.indexOf(" ");
		
		address = text_2.substr(pos_at, pos_space);
		address = address.replace("+", " ");
		address = address.replace("_", " ");

	}
	
	return address;

}




function update_status(status){
	
	while(status.search("'") != -1 || status.search('"') != -1)
	{
		status = status.replace("'", "-*-");
		status = status.replace('"', "*-*");
	}
	
	var opt = {
    // Use POST
    method: 'post',
    // Send this lovely data
    postBody: escape('status='+status),
    // Handle successful response
    onSuccess: function(t) {
        //alert(t.responseText);
		Effect.Appear('successful');
		Effect.Fade('update_status');
		Effect.Fade('successful');
		document.update_form.status_box.value = "";
    },
    // Handle 404
    on404: function(t) {
        alert('Error 404: location "' + t.statusText + '" was not found.');
    },
    // Handle other errors
    onFailure: function(t) {
        alert('Error ' + t.status + ' -- ' + t.statusText);
    }
	}
	
	new Ajax.Request('update_status.php?status='+status+'&username='+username+'&password='+password, opt);
	
}





// initialize XMLHttpRequest object
var xmlobj=null;
var data=new Array();

// send http request
function sendRequest(doc){
    // check for existing requests
    if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){
        xmlobj.abort();
    }
    try{
        // instantiate object for Mozilla, Nestcape, etc.
        xmlobj=new XMLHttpRequest();
    }
    catch(e){
        try{
            // instantiate object for Internet Explorer
            xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e){
            // Ajax is not supported by the browser
            xmlobj=null;
            return false;
        }
    }
    // assign state handler
    xmlobj.onreadystatechange=stateChecker;
    // open socket connection
    xmlobj.open('GET',doc,true);
    // send GET request
    xmlobj.send(null);
}

var data="";
var data2="";

// check request status
function stateChecker(){
    // if request is completed
    if(xmlobj.readyState==4){
        // if status == 200 display text file
        if(xmlobj.status==200){
            // read XML data
            data=xmlobj.responseXML.getElementsByTagName('status');
			data2=xmlobj.responseXML.getElementsByTagName('user');
			
 // display XML data
            displayData();
        }
        else{
            alert('Failed to get response :'+ xmlobj.statusText);
        }
    }
}

var show_all="no";

// display data at a given time interval
function displayData(){
  		
		// display the most recent post
		if(current_post == 0)
		{
			change_post(0);
		}
		
	if(show_all=="yes"){ display_extra = "block"; }
	else { display_extra = "none"; }
	
	var friends = "<table cellspacing='0' cellpadding='2' border='0'>";
	for(var i=0;i<data.length;i++){
		
		text = data[i].getElementsByTagName('text')[0].firstChild.nodeValue;
		//text = text.replace("*-*", "`");
		//text=text.replace(/\'/g,'\\\'');
		//text = addslashes(text);
		
		
		if(i==10){ friends += "</table><div id='extra_friends' style='display:"+display_extra+"'><table cellspacing='0' cellpadding='2' border='0'>"; }
		
		friends += "<tr onclick=\"change_post('"+i+"');\"><td><img src=\""+data[i].getElementsByTagName('profile_image_url')[0].firstChild.nodeValue+"\" height=\"20\"></td><td><a>"+data[i].getElementsByTagName('text')[0].firstChild.nodeValue.substring(0,15)+"...</a></td></tr>";
		
	}
	friends += "</table>";
	if(i>=10){
		friends += "</div>";
		if(show_all!="yes"){ friends += "<div align='center'><a onclick='javascript:Effect.SlideDown(\"extra_friends\"); show_all=\"yes\"; this.style.display=\"none\";'>More</a></div>"; }
	}
	
	document.getElementById('list_friends').innerHTML = friends;
	
    // update headlines each 1 minute
    setTimeout("sendRequest('includes/get_xml.php?username="+username+"&password="+password+"')",60*1000);
}

window.onload=function(){
	// google stuff
	initialize();
}