/***********************************************
* gAjax RSS Pausing Scroller- (c) Dynamic Drive (www.dynamicdrive.com)
* Requires "gfeedfetcher.js" class
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/


//var xmlHttp;
var country="france";
var geocoder=null;
var map;
var render="json";

function load()
{
    if (GBrowserIsCompatible()) 
		{
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(48.8582, 2.2938), 3);
				var mapControl = new GMapTypeControl();
				map.addControl(mapControl);
				map.addControl(new GLargeMapControl());
				map.disableDoubleClickZoom();
				
				geocoder = new GClientGeocoder();
				
				GEvent.addListener(map, "dblclick", function(overlay, point)
				{
				    // set dbclick coordinate as centre of map
						//alert (point.toString());
						map.panTo(point);
						// Reverse geocoding removed
						//getRGeocode(map, point.toString());
						//alert (address);
        });
    }
}

function getSimpleCountryName()
{
    var xmlHttp=getHTTPObject();
		var countryName;
		xmlHttp.onreadystatechange=function()
    {
        if(xmlHttp.readyState==4)
    		{
            countryName=xmlHttp.responseText;
						//countryName=trim(countryName);
						//alert("NAME: "+countryName);
            showAddress(countryName);
						displayLinks(countryName);
						//getRSS(countryName);
						displayRssCountry(countryName);
      	}
    }
		//var longCountryName=document.search.country_auto.value;
		var longCountryName=document.getElementById("country_auto").value;
		//alert("Country name HERE: "+longCountryName);
		// trim longCountryName for leading and trailling white spaces
		//longCountryName=trim(longCountryName);
		
		//alert ("long: "+longCountryName);
		
		var param=encodeURI("cgi-bin/getSimpleCountryName.cgi"+"?country_long="+longCountryName+"&sid="+Math.random());
  	xmlHttp.open("GET",param,true);
  	xmlHttp.send(null);
    
}

function displayRssCountry(countryName)
{
    var xmlHttp=getHTTPObject();

		var feed="";
		
		xmlHttp.onreadystatechange=function()
    {
		    if(xmlHttp.readyState==4)
				{
				    //feed=eval('(' + xmlHttp.responseText + ')');
						feed=eval('(' + xmlHttp.responseText + ')');
						
						//var div=document.getElementById("countryRss");
						
						//var kids = div.childNodes;    // Get the list of children
            //var numkids = kids.length;  // Figure out how many children there are
            //for(var i = numkids-1; i >= 0; i--) 
						//{  // Loop backward through the children
            //    var c = div.removeChild(kids[i]); 
		        //}
						// change if receiver is JSON
						
						if(render=="json")
						{
						    viewJSON_RSS_Object(feed);
						}
						else
						{
						    alert("Error, RSS not setup to JSON ojbect");
						}
						
				}
		}

    var param=encodeURI("cgi-bin/getFeedScript.cgi"+"?country="+countryName+"&render="+render+"&sid="+Math.random());
  	xmlHttp.open("GET",param,true);
  	xmlHttp.send(null);
}

function viewJSON_RSS_Object(feed)
{
    var tmp='';
    for (var i=0; i<feed.value.items.length; i++)
		{
        tmp+='<a href="'+feed.value.items[i].link+'">';
        tmp+=feed.value.items[i].title+'</a><br>';
        if (feed.value.items[i].description) 
				{
            tmp+=feed.value.items[i].description;
        }
        tmp+='<hr>';
		}
		
		_div=document.getElementById("newsList");
		_div.innerHTML=tmp;
}

function displayLinks(countryName)
{
    var xmlHttp=getHTTPObject();
    
		var link="";
		
		xmlHttp.onreadystatechange=function()
    {
		    if(xmlHttp.readyState==4)
				{
		        link=xmlHttp.responseText;
						// stick link in div tag
		//alert(link);
						var div=document.getElementById("links");
						
						var kids = div.childNodes;    // Get the list of children
            var numkids = kids.length;  // Figure out how many children there are
            for(var i = numkids-1; i >= 0; i--) 
						{  // Loop backward through the children
                var c = div.removeChild(kids[i]); 
		        }
						var table=document.createElement("table");
						table.setAttribute("id","cia_table");
						var tbody=document.createElement("tbody");
						var traw=document.createElement("tr");
						var tcell=document.createElement("td");
						
						traw.appendChild(tcell);
						tbody.appendChild(traw);
						table.appendChild(tbody);
						div.appendChild(table);
    				tcell.innerHTML = link;
				
						//alert(countryName);
		    }
		}
		//alert("OOO"+countryName+"OOO");
		
		param = encodeURI("cgi-bin/getLinks.cgi"+"?country="+countryName+"&sid="+Math.random());
  	xmlHttp.open("GET",param,true);
  	xmlHttp.send(null);
		
		//xmlHttp=null;
}

function showAddress(address) 
{
    if (geocoder) 
		{
        geocoder.getLatLng(address, function(point) 
				{
            if (!point) 
						{
                alert(">"+address+"<" + " not found");
            } 
						else 
						{
                map.panTo(point);
                var marker = new GMarker(point);
                map.addOverlay(marker);
                marker.openInfoWindowHtml(address);
            }
        });
    }
		//xmlHttp=null;
}

function getRGeocode(map, latLongStr)
{
				// get country code
				//var country;
		    var reversegeocoder = new GReverseGeocoder(map);
				GEvent.addListener(reversegeocoder, "load", function(placemark)
				{
				    country=regulariseCountry(placemark.address);
						if(country!=null)
						{
						    alert(country);
								newsfeed.emptyFeeds();
						    newsfeed.addFeed("BBC "+country, "http://newsapi.bbc.co.uk/feeds/search/news+sport/"+country);
								newsfeed.init() //Always call this last

						} 
				});
				//alert (latLongStr);
				var latLongArray=regularise(latLongStr);
				var x=0.0; var y=0.0;
				if(latLongArray.length==2)
				{
				    x=latLongArray[0]-0;
				    y=latLongArray[1]-0;
						//alert(x+" "+y);
				}
				//reversegeocoder.reverseGeocode(latLong);
				reversegeocoder.reverseGeocode(new GLatLng(x+0, y+0));
}

function regulariseCountry(address)
{
    var elements=address.split(/,/);
		if(elements.length>1)
		{
		    return elements[elements.length-1]
		}
		else return null;
}

function regularise(latLongStr)
{
    latLongStr=latLongStr.replace(/\(/g, "");
    latLongStr=latLongStr.replace(/\)/g, "");
		
		//alert(latLongStr);
		
		return latLongStr.split(/,/);
}

function getCountry(map)
{
    if(GBrowserIsCompatible())
		{
		    var geo=new GClientGeocoder();
				var code=geo().getBaseCountryCode();
				alert("country code: "+code);
		}
}

function doStuff()
{
		load();
}

function getHTTPObject()
{
    var xmlHttp;
		try
  	{  // Firefox, Opera 8.0+, Safari  
		    xmlHttp=new XMLHttpRequest();
		}
    catch (e)
    {  // Internet Explorer  
			  try
    	  {
			      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    
        }
        catch (e)
        {
				    try
      			{
						    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      
						}
    				catch (e)
      			{
						    alert("Your browser does not support AJAX!");      
								return false;      
						}    
        }
    }
		return xmlHttp;
}

function geoNews()
{
    var xmlHttp=getHTTPObject();
		

    var bbcNews;
		xmlHttp.onreadystatechange=function()
    {
        if(xmlHttp.readyState==4)
    		{
            bbcNews=xmlHttp.responseText;
        		alert (bbcNews);
      	}
    }
  	xmlHttp.open("GET","cgi-bin/relay.cgi",true);
		//xmlHttp.open("GET","../index.html",true);
  	xmlHttp.send(null);
		
}

function countryAutoFill()
{
    var xmlHttp=getHTTPObject();
		// not in use,\use scriptaculous instead
		
}