//======================
//======================
var g_mapmgr_chart_data = [];

//======================
//======================
function mapReady ( id )
{
	$('#'+g_mapmgr_chart_data['obj_id'])[0].flashXMLLoad ( g_mapmgr_chart_data['data_url'] );
}

//======================
//======================
function simpleEncode ( val, lim )
{
	var simpleEncoding = 
		  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	if ( lim <= 0 )
		return '_';

	//var currentValue = valueArray[i];
	if (!isNaN(val) && val >= 0) 
	{
		return ( simpleEncoding.charAt(Math.round((simpleEncoding.length - 1) * val / lim)));
	} 
	else 
	{
		return '_';
	}
}

// ======================
// ======================
function embed_map ( obj_id, use_swf, data_url, chart_wid, chart_ht, chart_id, swf_url )
{
	g_mapmgr_chart_data['data_url'] = data_url;
	g_mapmgr_chart_data['use_swf'] = use_swf;
	g_mapmgr_chart_data['obj_id'] = obj_id;
	
	if ( use_swf )
	{
		var chart_pars = 
		{ 
			width: chart_wid, 
			height: chart_ht, 
			quality: "high", 
			movie: swf_url, 
			allowFullScreen: "true", 
			wmode: "transparent" 
		};
		var flash_vars = 
		{
			"id" : chart_id, 
			"save_image_message" : "Copyright Anvato, Inc"
		}; 
		swfobject.embedSWF ( swf_url, obj_id, chart_wid, chart_ht, "9.0.0", "expressInstall.swf", flash_vars, chart_pars, {} );
	}
	else
	{
		// do an ajax and get the url
		$.ajax ( {  type: "GET",  cache: false, url: data_url, 
					success: function (xml)
					{
						geo_stats = $(xml).find ( 'geo_stats' );
						if ( geo_stats != null )
						{
							// not lways set :( find sum first
							//parseInt ( geo_stats.attr("view") );
							views = 0;
							$('country', geo_stats).each ( function () {
								views += parseInt ( $(this).attr("view") );
							} );

							var codes = "";
							var values = "";
							$('country', geo_stats).each ( function () {
								if ( $(this).attr("code") != "" )
								{
									codes = codes + $(this).attr("code");
									values = values + simpleEncode ( parseInt ( $(this).attr("view") ), views );
								}
							} );
							
						}
						
						var img_url = "http://chart.apis.google.com/chart?chf=bg,s,EAF7FE&chco=f5f5f5,edf0d4,c9dba3,a6c27d,6c9642,365e24,13390a&cht=t&chs=440x220&chtm=world&chld="+codes+"&chd=s:"+values;
						
						var par_ht = chart_ht;
						var par_wid = $('#'+obj_id).width();
						
						// Google chart has 2x1 ratio
						if ( par_wid > 2*par_ht )
							par_wid = 2 * par_ht;
						else
							par_ht = par_wid / 2;
						$('#'+obj_id).html ( '<div style="margin: 0 auto;width:'+par_wid+'px;height:'+par_ht+'px"><img src="'+img_url+'" style="width:'+par_wid+'px;height:'+par_ht+'px"></div>' );
					},
					complete: function (XMLHttpRequest, textStatus)  { },
				    error: function(XMLHttpRequest, textStatus, errorThrown){ }
		});
	}
}
