dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ValidationTextBox");
document.write('<script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;key=' + getGoogleKey() + '\" type=\"text/javascript\"><\/script>');	
function StringBuffer() { 
	this.buffer = []; 
} 
StringBuffer.prototype.append = function append(string) { 
   this.buffer.push(string); 
   return this; 
}; 
StringBuffer.prototype.toString = function toString() { 
   return this.buffer.join(""); 
}; 
function updateGenericDialog(title, text) {	
	dijit.byId('genericDialog').titleNode.innerHTML = title;
	document.getElementById('dialogText').innerHTML = text;
}
function showDialog(id) {
	dijit.byId(id).show();
}	
function hideDialog(id) {
	dijit.byId(id).hide();
}
function getGoogleKey() {
	var host = window.location.hostname.toLowerCase();
	var localhost = 'ABQIAAAAu4KHeqjE1BMYXHw5RQ4llBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxRTkI_jEedrXUUZdwrDvP410deTVw'
	var production = 'ABQIAAAAu4KHeqjE1BMYXHw5RQ4llBQW2bLw8_FjkOTKbrXZGOtl7e430BSQi89OOhB8NHj1WfZJ5LHyLaG33g'
    var key = '';
	if (host.indexOf('localhost') != -1) {
            key = localhost;
    } else {
            key = production;
    }
	return key;
}
function customIcon(which) {
	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(36,36);
	baseIcon.shadowSize=new GSize(60,60);
	baseIcon.iconAnchor=new GPoint(16,32);
	baseIcon.infoWindowAnchor=new GPoint(16,0);
	if (which == 'location') {
		return new GIcon(baseIcon, "/images/location.png", null, "/images/location-shadow.png");
	}  else { //default
		return new GIcon(G_DEFAULT_ICON);
	}
}
var map;
function showMap(widgetName, useMapControl, useTypeControl) {
	//<![CDATA[	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(widgetName),{
                 mapTypes : [G_NORMAL_MAP,G_PHYSICAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP]
              });
		if (useMapControl) {
			map.addControl(new GSmallMapControl()); 
		}
		if (useTypeControl) {
			map.addControl(new GMapTypeControl());
		}
		//Geographical center of lower 48 US states - Lebonon, Kansas
		var centerPoint = new GLatLng(39.809, -98.555);
		map.setCenter(centerPoint, 4);
	} else {
		document.getElementById(widgetName).innerHTML = "<span style=\"text-align:center; font-weight: bold; color: #c00\";><img src=\"/images/exclimation.gif\"/>Sorry, Google Maps is not compatible with your browser.<br />Take a look at the <a href=\"http://maps.google.com/support/bin/answer.py?answer=16532\" style=\"color: blue\";>list of supported browsers</a>.</span>";
	}	
}
function plot(location) {
	if (map == null) {
		console.error('Map must be initialized.');
		return;
	}
	
	if (location != null && location.city != null) {
		var dataPoint = new GLatLng(location.city.latitude, location.city.longitude);
		map.setCenter(dataPoint, 13);
		var marker = new GMarker(dataPoint, customIcon('location'));
		map.addOverlay(marker);
		var locationSummaryHtml = getLocationSummaryHtml(location);
		marker.bindInfoWindowHtml(locationSummaryHtml ,{maxWidth:500, maxHeight:400});
		marker.openInfoWindowHtml(locationSummaryHtml, {maxWidth:500, maxHeight:400});
	}
}
function locateAndMap() {
	var title = 'One Moment Please...';
	var text = "<p align=\"center\"><img src=\"/images/waiting.gif\"\> <strong>Locating and mapping...</strong></p>";
	updateGenericDialog(title,text);
	showDialog('genericDialog');
	showMap('mapCanvas', true, true);
	dojo.xhrPost({
        url: "/locate.json",
        handleAs: "json",
        timeout: 30000, //Time in milliseconds
        handle: function(response, ioArgs){    
            if(response instanceof Error){
                title = 'An Error Has Occurred...';
                if(response.dojoType == "cancel"){ 
                	text = "<div class=\"alertError\">The request was canceled.</div>";
                }else if(response.dojoType == "timeout"){
               		text = "<div class=\"alertError\">Unable to locate in the allotted time, please try again.</div>";
                }else{ 
                  	text = "<div class=\"alertError\">An unexpected error occurred. Please try again.</div>";
                }
               updateGenericDialog(title,text);
               return;
            }else{
            	if (response.location.city == null) {
            		title = "Sorry...";
            		if (response.location.ip != null) {
            			text = "Unable to locate and map the IP " + response.location.ip + ".";
            		} else {
            		 	test = "Unable to locate and map your IP.";
            		}
            		updateGenericDialog(title,text);
            		return;
            	}
               	plot(response.location); 
               	hideDialog('genericDialog');
               	return;
            }
   	 	}
	});
}
function getLocationSummaryHtml(location) {
	if (location == null) {
		return;
	}
	var buf = new StringBuffer();
	if (location.ip != null) {
		buf.append("<p align=\"center\"><strong>The location of ");
		buf.append(location.ip);
		buf.append(" or its ISP</strong></p><br/>");
	}
	buf.append("<fieldset style=\"min-width:350px;\">");
	if (location.city != null && location.city.city != null) {
		buf.append("<label for=\"city\"><strong>City:</strong></label>");
		buf.append(location.city.city);
		buf.append("<br/>");
	}
	if (location.region != null && location.region.region != null) {
		buf.append("<label for=\"region\"><strong>Region:</strong></label>");
		buf.append(location.region.region);
		buf.append("<br/>");
	}
	if (location.country != null && location.country.country != null) {
		buf.append("<label for=\"country\"><strong>Country:</strong></label>");
		buf.append(location.country.country);
		buf.append("<br/>");
	}
	buf.append("</fieldset>");
	if (location.ip != null) {
		buf.append("<br/><p align=\"center\"><a style=\"text-align:center\" href=\"javascript:showLocationDialog('");
		buf.append(location.ip);
		buf.append("');\"><strong>Click Here for Full Location Detail</a></strong></p>");
	}	
	return buf.toString();		
}
function showLocationDialog(ip) {	
	var title = "One Moment Please...";
	var text = "<p align=\"center\"><img src=\"/images/waiting.gif\"\> <strong>Retrieving location details for " + ip + "...</strong></p>";
	updateGenericDialog(title, text);
	showDialog('genericDialog');
	var request = "/location/detail/html.json";
	dojo.xhrPost({
        url: request,
        content: { 'ip':ip },
        handleAs: "json",
        timeout: 10000, //Time in milliseconds
        handle: function(response, ioArgs){    
            if(response instanceof Error){
                title = 'An Error Has Occurred...';
                if(response.dojoType == "cancel"){ 
                 	 text = "<div class=\"alertError\">The request was canceled.</div>";
                }else if(response.dojoType == "timeout"){
               		 text = "<div class=\"alertError\">Unable to complete loading in the allotted time, please try again.</div>";
                }else{ 
                  	 text = "<div class=\"alertError\">An unexpected error occurred. Please try again.</div>";
                }
                updateGenericDialog(title,text);
            }else{
            	if (response.html != null && response.html != '') {
            		text = response.html;
            	} else {
            		text = "<div class=\"alertError\">Unable to retrieve location detail for " + ip + "</div>";
            	}	
            	title = "Location Detail";
            	hideDialog('genericDialog');
            	updateGenericDialog(title, text);
            	showDialog('genericDialog');
            }
   	 	}
	});
}
function whois(ip) {
	var title = 'Please wait...';
	var text = '<p align="center"><img src="/images/waiting.gif"/> <strong>Finding host information...</strong></p>';
	updateGenericDialog(title,text);
	showDialog('genericDialog');
	dojo.xhrGet({
        url: "/whois.json", 
        content: {'ip':ip},
        sync : true,
        handleAs: "json",
        timeout: 10000,  
        handle: function(response, ioArgs){ 
        	var whois;
        	if(response instanceof Error){
          		html = "<span class=\"alertError\"> An unexpected error occurred retrieving host detail.</span>";
         	}else{
           		if (response != null) {
           			if (response.error != null) {
           				whois = "<span class=\"alertError\"> An unexpected error occurred retrieving host detail.</span>";
           			} else if (response.whois != null && response.whois != "") {
           				whois = '<pre class="whois">' + response.whois + '</pre>';
           			} else {
           				whois = "<span class=\"alertError\"> Could not retrieve host detail.</span>";
           			}
           		} else {
           			whois = "<span class=\"alertError\"> An unexpected error occurred retrieving host detail.</span>";
      			}
            }
            hideDialog('genericDialog');
            title = 'Host Information for ' + ip;
			updateGenericDialog(title, whois);
			showDialog('genericDialog');
   	 	}
   	});
}
function search(arguments) {
	var title = 'One Moment Please...';
	var text = "<p align=\"center\"><img src=\"/images/waiting.gif\"\> <strong>Searching...</strong></p>";
	updateGenericDialog(title,text);
	showDialog('genericDialog');
	showMap('mapCanvas', true, true);
	dojo.xhrPost({
        url: "/search.json",
        content: arguments,
        handleAs: "json",
        timeout: 30000, //Time in milliseconds
        handle: function(response, ioArgs){    
            if(response instanceof Error){
                title = 'An Error Has Occurred...';
                if(response.dojoType == "cancel"){ 
                	text = "<div class=\"alertError\">The request was canceled.</div>";
                }else if(response.dojoType == "timeout"){
               		text = "<div class=\"alertError\">Unable to complete search in the allotted time, please try again.</div>";
                }else{ 
                  	text = "<div class=\"alertError\">An unexpected error has occurred. Please try again.</div>";
                }
               updateGenericDialog(title,text);
            }else{
            	if (response.location.city == null){
           		 	title = 'Sorry...';
            		text = "<div class=\"alertError\">Unable to find a match. Please try again.</div>";
            		updateGenericDialog(title,text);
            	} else { 
               		plot(response.location); 
               		hideDialog('genericDialog');
               	}
            }
   	 	}
	});
}