// handle Firebug console
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

var MAPANUIBTN = {};

MAPANUIBTN.vcard = {
	vcard:            '<div class="vcard">',
    given_name:       '  <span class="given-name">',
    additional_name:  '  <span class="additional-name">',
    family_name:      '  <span class="family-name">',
    org:              '  <div class="org">',
    street_address:   '  <div class="street-address">',
    locality:         '  <span class="locality">',
    region:           '  <span class="region">',
    postal_code:      '  <span class="postal-code">',
    country_name:     '  <span class="country-name">'
};

MAPANUIBTN.bkmrklt = "javascript:(function(){function%20l(u,i,t,b){var%20d=document;if(!d.getElementById(i)){var%20s=d.createElement('script');s.src=u;s.id=i;d.getElementsByTagName('head')[0].appendChild(s);}s=setInterval(function(){u=0;try{u=t.call()}catch(i){}if(u){clearInterval(s);b.call()}},200)}l('http://www.mapanui.com/bookmarklet/bkmrklt.js','MapanuiJS',function(){return!!(typeof%20MAPANUI=='function')},function(){MAPANUI()})})();"
MAPANUIBTN.link = '<div id="mapanuiBkmrklt"><a href="'+MAPANUIBTN.bkmrklt+'">Locate me<\/a><\/div>';

MAPANUIBTN.create = function(){
	
	var errs = MAPANUIBTN.validateForm();
	if(errs){
		$("#warning").html(errs);
		$("#warning").fadeIn('normal');
		return false;
	}

	
	var $form = $("#addressform");
	var result=[];
	var resultField = $("#microf");
	var geoData = {
    	street_address:"",
    	locality:      "",
    	region:        "",
    	postal_code:   "",
    	country_name:  ""
	};
	
	
	result.push(MAPANUIBTN.vcard["vcard"]+"\n");
	// iterate over input fields, get the value, create a MF element
	$(':input', $form).each(function(){
		var type = this.type;
		var id = this.id;
		var value = $.trim(this.value);
		
		if(type=="text" && value.length>0 && MAPANUIBTN.vcard[id]){
			var element = MAPANUIBTN.vcard[id] + value + ((MAPANUIBTN.vcard[id].indexOf("<div")>-1)?"<\/div>\n":"<\/span>,\n");
			result.push(element);
			console.debug("is geodata? "+geoData[id]);
			if(geoData[id]!=undefined){
				console.debug("set geodata value "+value);
				geoData[id] = value;
			}
		}
	
	});
	
	
	// look up geodata
	var location = MAPANUIBTN.getGeoData(geoData);
	
	// close vcard
	result.push("<\/div>");
	
	// put the vcard in the text field
	resultField.text(result.join(""));
	
	// add the link
	result.push(MAPANUIBTN.link);
	
	// show the resulting vcard and link as an example
	$("#sample").hide()
		.html("This is what it will look like by default:<br \/>" + result.join(""))
		.fadeIn('normal');
	
	return false;
}

MAPANUIBTN.doReset = function(){
	return true;
}

MAPANUIBTN.validateForm = function(){

	var errors = [];
	var valid = null;
	
	$("#warning").hide();
	
	$("#addressform :input").each(function(){
		var $thisField = this;
		if($thisField.type == "text"){
			var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
			$thisField.value = $.trim($thisField.value);
			if ($thisField.value.match(illegalChars)) {
				$(this).parents("li:first").addClass("warning");
				var label = $(this).parent().parent("li").text();
				label = $.trim(label);
				errors.push("-"+label +" contains invalid characters, and may break your page")
			}else{
				$(this).parents("li:first").removeClass("warning");
			}
		}
	
	});
	
	$("#addressform :input.required").each(function(){
		var $thisInput = $(this)
		if(this.value.length==0){
			$thisInput.parents("li:first").addClass("warning");
			var label = $thisInput.parent().parent("li").text();
			label = $.trim(label);
			errors.push("-"+label +" is required")
		}else{
			$thisInput.parents("li:first").removeClass("warning");
		}
	});
	
	
	if(errors.length!=0){
		valid = "Please correct the following errors:<br \/>" + errors.join("<br \/>");
	}
	
	return valid;
	
}


MAPANUIBTN.getGeoData = function(geoData){
	console.debug("geoData lookup");
	
	$("#geodata").text("Looking up geodata...");
	$("#geoinfo").fadeIn('normal').css('visibility','visible');
		
	var lookup = "";
	var location = {};
	var ok = false;
	
	for(var d in geoData){
		if(geoData[d].length>0){
			lookup = (lookup.length>0) ? lookup+","+geoData[d] : geoData[d];
		}
	}
	if(lookup.length>0){
		console.debug("lookup: "+lookup);
		$.get('/bookmarklet/geo?q='+lookup,
			function(data){
				if(data){
					console.debug("lookup result: "+data);
					var ginfo = data.split(',');
					if(ginfo[0] == "200"){
						console.debug("lookup succesful ");
						location["lat"] = ginfo[2];
						location["lon"] = ginfo[3];
						ok = true;
						//add to result textarea field
						var geomf = '<span class="geo" style="display:none"><span class="latitude">'+location["lat"]+'<\/span><span class="longitude">'+location["lon"]+'<\/span><\/span>\n<\/div>'
						var current = $("#microf").text();
						$("#microf").text(current.substring(0, current.lastIndexOf("</div>")) + geomf + "\n" + MAPANUIBTN.link);
						$("#geodata").text(location["lat"]+", "+location["lon"]);
						//reset example,  MAPANUIBTN.link
						$("#sample").hide()
							.html($("#microf").text())
							.fadeIn('normal');
					}else{
						$("#geodata").text("Could not find a geo location for your address data.");
					}
				}
			}
		);
	}
	
	return (ok) ? location : null;
}

$(document).ready(function(){
	
	$("input.required").each(function(){
		var $thisInput = $(this);
		$thisInput.parents("li:first").addClass("req");
	});

});