$(function(){
	var _series_colors = [ 
		"#417DEC", 
		"#FFBC40", 
		"#7BA30D",
		"#EA1302", 
		"#6443ED", 
		"#EA7202",
		"#1A5F04", 
		"#A40D22", 
		"#047E8F", 
		"#3AEAD7", 
		"#2B920C" 
	];

	if($("#stats").size() !== 0){
		var stats_line_js = [];
		var series = [];
		var count_stats = count(stats_line);
		var show_legend = count_stats > 1 ? true : false;
		i = 0;
		$.each(stats_line, function(city, line){

			stats_line_js.push(line);
			_color = count_stats > 1 ? _series_colors[i] : line_color;
		
			series.push({
		        lineWidth: 3,
				label: stats_line_title[city],
				color: _color,
				fillColor: _color,
				fill: count_stats > 1 ? false : true,
				fillAndStroke: count_stats > 1 ? false : true,
				fillAlpha: 0.3,
		        markerOptions: {
					size: 3
		        },
				pointLabels:{
					show: false
				}
		    });
			i++;
			if (i > _series_colors.length){
				i = 0;
			}
		});
		
		plot_stats = $.jqplot('stats',stats_line_js,{
			grid: {
		        drawGridLines: true,
		        gridLineColor: '#ffffff',
		        background: '#f1f1f1',
		        borderColor: '#e9e9e9',
		        borderWidth: 2,
		        shadow: false,
		        renderer: $.jqplot.CanvasGridRenderer,
		        rendererOptions: {}
		    },
			legend: {
		        show: show_legend,
				location: 'nw'
		    },
			axes: {
		        xaxis: {
		            renderer: $.jqplot.DateAxisRenderer,
//		            tickInterval: '10 days',
					pad: 1.0,
		            rendererOptions: {
		                tickRenderer: $.jqplot.CanvasAxisTickRenderer
		            },
		            tickOptions: {
//		                formatString: '%d-%m-%Y',
						formatString: '%#d %b %Y',
		                fontSize: '8pt',
		                fontFamily: 'Tahoma'
//		                angle: -90
		            }
		        },
				yaxis: {
					pad: 1.0,
					ticks: stats_tick_array_y
				}
		    },
			highlighter: {
				lineWidthAdjust: 2.5,
				sizeAdjust: 7.5,
				showTooltip: true,
				tooltipLocation: 'n',
				tooltipOffset: 2,
				tooltipAxes: 'yx',    
				useAxesFormatters: true,
				formatString: sign +', %s'
		    },
		    series: series
		});
	}
	
	if($("#stats_count").size() !== 0){
	
		var stats_count_line_js = [];
		var series = [];
		var count_stats = count(stats_line);
		var show_legend = count_stats > 1?true:false;

		i = 0;	
		$.each(stats_count_line, function(city, line){
			stats_count_line_js.push(line);
			_color = count_stats > 1 ? _series_colors[i] : line_color;
		
			series.push({
				lineWidth: 3,
				label: stats_line_title[city],
				color: _color,
				fillColor: _color,
				fill: count_stats > 1 ? false : true,
				fillAndStroke: count_stats > 1 ? false : true,
				fillAlpha: 0.3,
				markerOptions: {
					size: 3
				},
				pointLabels:{
					show: false
				}
			});
			i++;
			if (i > _series_colors.length){
				i = 0;
			}
	    });
	

		plot_stats_count = $.jqplot('stats_count',stats_count_line_js,{
			grid: {
		        drawGridLines: true,
		        gridLineColor: '#ffffff',
		        background: '#f1f1f1',
		        borderColor: '#e9e9e9',
		        borderWidth: 2,
		        shadow: false,
		        renderer: $.jqplot.CanvasGridRenderer,
		        rendererOptions: {}
		    },
			legend: {
		        show: show_legend,
				location: 'nw'
		    },
			axes: {
		        xaxis: {
		            renderer: $.jqplot.DateAxisRenderer,
//		            tickInterval: '10 days',
					pad: 1.0,
		            rendererOptions: {
		                tickRenderer: $.jqplot.CanvasAxisTickRenderer
		            },
		            tickOptions: {
//		                formatString: '%d-%m-%Y',
						formatString: '%#d %b %Y',
		                fontSize: '8pt',
		                fontFamily: 'Tahoma'
//		                angle: -90
		            }
		        },
				yaxis: {
					pad: 1.0,
					ticks: stats_count_tick_array_y
				}
		    },
			highlighter: {
				lineWidthAdjust: 2.5,
				sizeAdjust: 7.5,
				showTooltip: true,
				tooltipLocation: 'n',
				tooltipOffset: 2,
				tooltipAxes: 'yx',    
				useAxesFormatters: true
		    },
		    series: series
		});
	}
	
	$(".jqplot-legend").mouseover(function(){
		$(this).parents(".jqplot-target").find(".jqplot-legend").fadeOut(300);
	});
	
	$(".jqplot-event-canvas").mouseout(function(){
		$(this).parents(".jqplot-target").find(".jqplot-legend").fadeIn(300);
	});

	
	
	$(".pie_chart").each(function(){
		var pie = $(this);
		
		var compare = $(pie).attr("compare");
		var max = 0;
		
		
		var data = [];
		$("input", pie).each(function(){
			var value = $(this).attr("value");
			var name = $(this).attr("name");
			var link = $(this).attr("link");
			
			if(compare !== undefined && compare !== ""){
				compare_str = "<input class='compare_"+compare+"' type='checkbox' name='"+name+"'> ";
			}else{
				compare_str = "";
			}
			
			if(link !== ""){
				name = compare_str + "<a href='" + link + "'>" + name + "</a>";
			}
			
			name = name + " - " + value;
			
			value = parseFloat(value);
			data.push([name, value]);
			
			if(value > max){
				max = value;
			}
			
		});
		
		if(max == 0){
			return;
		}
		
		plot_pie = $.jqplot($(pie).attr("id"), [data], {
			sortData: false,
			seriesDefaults:{renderer:$.jqplot.PieRenderer, 
				rendererOptions:{
					seriesColors: _series_colors,
					sliceMargin:7,
					diameter: 250
				}
			},
			grid: {
				shadow: false,
		        background: '#ffffff',
		        borderColor: '#ffffff',
		        borderWidth: 0

			},
			legend:{
				show:true,
				location: 'nw',
				preDraw: true,
				xoffset: 5,
				yoffset: 5
			},
			series:[
				{
					pointLabels:{
						show: false
					}
				}
			]
		});
	});
	
	
	$(".bar_chart").each(function(){
		var bar = $(this);
		
		var compare = $(bar).attr("compare");
		var data = [];
		var points = [];
		var ticks_y = [];
		var ticks_x = [];
		$("input", bar).each(function(i){
		
			if($(this).attr("class") == "line"){
			
				var name = $(this).attr("name");
				var value = $(this).attr("value");
				var link = $(this).attr("link");

				if(compare !== undefined && compare !== ""){
					compare_str = "<input class='compare_"+compare+"' type='checkbox' name='"+name+"'> ";
				}else{
					compare_str = "";
				}
				
				if(link !== ""){
					name = "<a href='" + link + "'>" + name + "</a> " + compare_str;
				}
				
				points.push(sign.replace('%s', value));

				if($(bar).attr("direction") === "vertical"){
					data.push([i+1, parseFloat(value)]);
				}else{
					data.push([parseFloat(value), i+1]);
				}
				ticks_y.push(name);
			}
			
			if($(this).attr("class") == "x"){
				var name = $(this).attr("name");
				var value = $(this).attr("value");
			
				ticks_x.push([parseFloat(name), value]);
			}
		});
		
		
		hi = parseInt(data.length) * 30 + 22;
		
		$(bar).css("height", hi);
		
		if($(bar).attr("direction") === "vertical"){
			plot = $.jqplot($(bar).attr("id"), [data], {
				grid: {
					shadow: false,
			        background: '#f1f1f1',      // CSS color spec for background color of grid.
			        borderColor: '#e9e9e9',     // CSS color spec for border around grid.
			        borderWidth: 2           // pixel width of border around grid.
				},
				seriesDefaults:{
					shadow: true,   // show shadow or not.
					color: line_color,	
					renderer:$.jqplot.BarRenderer, 
					rendererOptions:{barDirection:"vertical", barPadding: 6, barMargin: 15}
				},
				axes:{
					xaxis:{
						renderer:$.jqplot.CategoryAxisRenderer, 
						ticks:ticks_y
					}, 
					yaxis:{
						ticks:ticks_x
					}
				}
			});		
		}else{
			plot = $.jqplot($(bar).attr("id"), [data], {
				grid: {
					shadow: false,
			        background: '#f1f1f1',
			        borderColor: '#e9e9e9',
			        borderWidth: 2
				},
				seriesDefaults:{
					shadow: true,
					color: line_color,	
					renderer:$.jqplot.BarRenderer, 
					rendererOptions:{barDirection:"horizontal", barPadding: 6, barMargin: 13, barWidth: 15}
				},
				series:[
					{
						pointLabels:{
							show: true,
							labels: points,
							location:'e'
						}
					}
				],
				highlighter: {
					show: false,
					lineWidthAdjust: 2.5,
					sizeAdjust: 7.5,
					showTooltip: true,
					tooltipLocation: 'n',
					tooltipOffset: 2,
					tooltipAxes: 'x',    
					useAxesFormatters: true,
					formatString: sign + ', %s'
			    },
				axes:{
					xaxis:{
						ticks:ticks_x
					},
					yaxis:{
						renderer:$.jqplot.CategoryAxisRenderer, 
						ticks:ticks_y
					}
				}
			});		

		}
	});
	
	 //draw country svg map
	$(".country_svg").each(function(){
	
		var country_data = $(this);
	
		var link = map_data_link + $(country_data).attr("id") + ".html";
		
		$.get(link, function(state_data){
			state_data = eval('('+state_data+')');
			
			map_data_region_count = eval('('+map_data_region_count+')');
			
			var paper = $(country_data).attr("id");
			
			var R = Raphael(paper, $("#"+paper).width(), $("#"+paper).height());
			var attr = {
				fill: "#c1c1c1",
				stroke: "#fff",
				"stroke-width": 1,
				"stroke-linejoin": "round"
			};
			
			var country = {};
			var states = {};
			var state_stat_count = {};
			var state_link = {};
			var state_id = {};
			
			var max_count = 0;
			$.each(map_data_region_count, function(key, val){
				var count = parseInt(val["stat_count"]);
				if(count > max_count){
					max_count = count;
				}
			}); 
			
			get_legend(max_count, $(country_data).attr("id"));
			
			var start_color = $("a").css("color");
			
			$.each(state_data, function(i, val){

				var state_info = val;
				
				states[i] = state_info;

				try {
					state_info["stat_count"] = parseInt(map_data_region_count[i]["stat_count"]);
				} catch (e) {}

				if (state_info["stat_count"] > 0 && max_count > 0) {
					percent = Math.round(parseInt(state_info["stat_count"])/max_count*100);
				} else {
					percent = 0;
				}
				attr.fill = get_stat_color(start_color, "#c1c1c1", percent);
		
				var state = R.path(state_info["data"]);
				state.attr(attr);
				country[i] = state;
				country[i].color_1 = attr.fill;
			});
			
			$(country_data).find("h2").remove();
			$(country_data).css("background", "transparent");
			
			if($.browser.msie){ //бубен для IE
				var state = R.path("");
			}
			
			var current = null;
			
			$.each(country, function(i){
				country[i].color = Raphael.getColor();
				
				(function (st_obj, i) {
					st_obj[0].style.cursor = "pointer";
			
					$(st_obj[0]).mouseover(function(){
//						st_obj.attr({"stroke-width" : 3});
//						st_obj.toFront();
						st_obj.animate({fill: "#dedede"}, 200);
						if(!$.browser.mozilla){
							$("#region_link_"+states[i]["id"]).css("font-weight", "bold");	
						}

						R.safari();
						current = i;
						//$("#message").html("<b>"+state_title[i]+"</b> - " + state_stat_count[i]);
					});
					
					$("#region_link_"+states[i]["id"]).mouseover(function(){
						st_obj.animate({fill: "#dedede"}, 200);
						$(this).css("font-weight", "bold");	
					});
					
					$("#region_link_"+states[i]["id"]).mouseout(function(){
						st_obj.animate({fill: country[i].color_1}, 400);
						$(this).css("font-weight", "normal");
					});
						
					
					$(st_obj[0]).mouseout(function(){
//						st_obj.attr({"stroke-width" : 1});
						st_obj.animate({fill: country[i].color_1}, 400);
						if(!$.browser.mozilla){
							$("#region_link_"+states[i]["id"]).css("font-weight", "normal");
						}
					});

					$(st_obj[0]).click(function(){
						window.location = map_data_region_count[i]["link"];
					});
					
				})(country[i], i);
			});

		});
	});

	$(".jqplot-yaxis-tick input[type=checkbox]").click(function(){
		_parent_block = $(this).parents(".jqplot-yaxis");
		_process_compare_block(_parent_block);
/*
		var _labels_block = $(this).parents(".jqplot-yaxis");
		// Find number of checked boxes
		var _checked_num = _labels_block.find("input:checked").length;
		if (_checked_num >= 2 && _checked_num <= 5){
			_labels_block.parents(".similar_block").find(".similar_tools span").hide();	
			_labels_block.parents(".similar_block").find(".similar_tools .compare_button").show();
		} else {
			_labels_block.parents(".similar_block").find(".similar_tools .compare_button").hide();
			_labels_block.parents(".similar_block").find(".similar_tools span").show();	
		}
*/
	});

	$(".jqplot-legend input[type=checkbox]").click(function(){
		_parent_block = $(this).parents(".jqplot-legend");
		_process_compare_block(_parent_block);
/*
		var _labels_block = $(this).parents(".jqplot-legend");
		// Find number of checked boxes
		var _checked_num = _labels_block.find("input:checked").length;
		if (_checked_num >= 2 && _checked_num <= 5){
			_labels_block.find(".similar_tools span").hide();	
			_labels_block.find(".similar_tools .compare_button").show();
		} else {
			_labels_block.find(".similar_tools .compare_button").hide();
			_labels_block.find(".similar_tools span").show();	
		}
*/
	});
	
	var compare_types = {};
	
	//set events for together checkbox select
	$("body").find("div[compare]").each(function(key, val){
		var compare_type = $(this).attr("compare");
		
		
		compare_types[compare_type] = compare_type;
		
		$(".compare_"+compare_type).click(function(){
			$(".compare_"+compare_type+"[name="+$(this).attr("name")+"]").attr("checked", $(this).attr("checked"));
			_synchronize_compare_blocks ();
		});
		
		var cities = "";
		cities = window.location.href.match(new RegExp(compare_type+"\.(.+?)\/", "g"));
		if(cities !== null){
			cities = cities[0];
			cities = cities.replace(new RegExp(compare_type+"\.", "g"), "").replace(/\//g, "");
			cities = explode(",", cities);
			$.each(cities, function(key, city){
				city = ucwords(urldecode(city));
				$(".compare_"+compare_type+"[name="+city+"]").attr("checked", 1);
			});
			_synchronize_compare_blocks ();
		}
	});

	
	
	//compare button
	$(".compare_button").click(function(){
	
		var url = window.location.href;
		var compare_type = $(this).parents(".similar_chart").find("div[compare]").attr("compare");
		
		var comparies = "";
		var comparies_array = {};
		
		$.each($(".compare_"+compare_type+":checked"), function(){
			comparies_array[$(this).attr("name")] = $(this).attr("name");
		});
		
		$.each(comparies_array, function(compare){
			comparies += compare+",";
		});
		comparies = comparies.replace(/,$/g, "");
		
		if(comparies == ""){
			return false;
		}
		
		
		var url_comparies = window.location.href.match(new RegExp(compare_type+"\.(.+?)\/", "g"));
		
		if(url_comparies == null){
			url = url.replace(/\/$/g, "");
			url = url + "/"+compare_type+"."+comparies+"/";
		}else{
			url = url.replace(new RegExp(compare_type+"\.(.+?)\/", "g"), compare_type+"."+comparies+"/");
		}
		
		$.each(compare_types, function(key, val){
			if(val !== compare_type){
				var reg = new RegExp(val+"\.[^\,/]+?,(.+?)\/", "g");
				var result = reg.exec(url);
				
				if(result !== null){
					if(result[1] !== ''){
						url = url.replace(","+result[1], "");
					}
				}
			}
		});
		
		window.location.href = url;
	});

	$.each( $(".pie_chart"), function(i, obj){
		var _compare_tools = $(obj).parents(".similar_chart").find(".similar_tools");
		if(_compare_tools && $(obj).find(".jqplot-legend input[type=checkbox]").length > 1) {
			$(obj).find(".jqplot-legend").append(_compare_tools);
			$(obj).find(".jqplot-legend .similar_tools").css("text-align", "left").show();
		}
	});	
	
	
	
});

function _synchronize_compare_blocks () {
	$.each($(".jqplot-yaxis, .jqplot-legend"), function(i, obj){
		if($(obj).find("input[type=checkbox]").length > 0) {
			_process_compare_block($(obj));
		}
	});
}

function _process_compare_block (parent_block_obj) {
	var _labels_block = parent_block_obj;
	// Find number of checked boxes
	var _checked_num = _labels_block.find("input:checked").length;
	if (_checked_num >= 2 && _checked_num <= 5){
		_labels_block.parents(".similar_block").find(".similar_tools span").hide();	
		_labels_block.parents(".similar_block").find(".similar_tools .compare_button").show();
	} else {
		_labels_block.parents(".similar_block").find(".similar_tools .compare_button").hide();
		_labels_block.parents(".similar_block").find(".similar_tools span").show();	
	}
}


function get_legend (_max, _country){
	$("#" + _country + "_legend").append("<div class='legend_scale'>1</div>");
	var num_max = 0;
	for (i = 0; i < 100 ; i=i+10){      
		c = get_stat_color($("a").css("color"), "#c1c1c1", i);
		_round_vol = 1000;
		$("#" + _country + "_legend").append("<div  class='legend_scale' style='background:" + c + ";'></div>");
	}
	if(_max > _round_vol * 10) {
		num_max = Math.round(_max/_round_vol)*_round_vol;
	} else {
		num_max = _max;
	}
	$("#" + _country + "_legend").append("<div class='legend_scale' style='width:auto;'>" + num_max + " " + t_ads + "</div>");
}


/*
if($("#date_slider").size() !== 0){

	// Slider customized for date interval picking 
	// Date slider default values
	var slider_start = -30;
	if(stats_period_view !== undefined && stats_period_view !== ""){
		 slider_start = (-1)*stats_period_view;
	}
	var slider_end	 =	0;
	var limit_interval = 30 //days
}
*/
$(function(){

	if($("#date_slider").size() !== 0){

	  /* Slider customized for date interval picking */
	  // Date slider default values
	  var slider_start = -30;
	  if(stats_period_view !== undefined && stats_period_view !== ""){
		  slider_start = (-1)*stats_period_view;
	  }
	  var slider_end	 =	0;
	  var limit_interval = 30 //days
	}


	/* 1 day = 2px */
//	var	now		= new Date("2009-02-15");
	var	now		= new Date();             
	Date.format = 'yyyy-mm-dd';
	if (months_abbr) {
		Date.abbrMonthNames = months_abbr;
	}
	var day 	= now.getDate();
	var month 	= now.getMonth() + 1;
	var year 	= now.getFullYear();
	//alert(now + "#" + day + "#" +  month + "#" + year);
	for(i = 0; i <= 12; i++){
		month_str = month - i;
		css_class = "slider_month";
	//alert(i + "-" +month +"--" + month_str);
		if (month_str <= 0){
			month_str = month_str + 12;
			css_class = "slider_month2";
		}
		month_str = now.getMonthName(true);
		now.addMonths(-1);

		if (i == 0){
			$("#date_slider").append("<div class='"+ css_class +"' style='width:" + (day*2) + "px;'>&nbsp;" + month_str + "</div>");
		} else {
			if (i == 12) {
				$("#date_slider").append("<div class='"+ css_class +"' style='width:" + ((30 - day)*2) + "px;border:0;'>&nbsp;</div>");
			} else { 
				$("#date_slider").append("<div class='"+ css_class +"'>&nbsp;" + month_str + "</div>");
			}
		}
	}

	year_label_pos = day * 2 + 30 * 2 * (month - 1) - 20;
	if (year_label_pos < 0 ) {
		year_label_pos = 0;
	}
	show_year_label2 = true;
	if (year_label_pos > 650 ) {
		show_year_label2 = false;
	}
	year_label = "<div style='position:absolute; bottom:0;right:" + year_label_pos + "px;'>" + year + "</div>";
	$("#date_slider").append(year_label);
	if (show_year_label2) {
		year_label2 = "<div style='position:absolute; bottom:0;left:0px;'>" + (year - 1) + "</div>";
		$("#date_slider").append(year_label2);

	}

	now = new Date();
	cur_day_num = now.getDayOfYear();
	// dates to objects
	if (typeof(date_from) != "undefined") {
		start_date = Date.fromString(date_from);
		if (start_date.getFullYear() == year)	{
			start_val = start_date.getDayOfYear() - cur_day_num;
		} else {
			start_val = -1 * (365 - start_date.getDayOfYear() + cur_day_num);
		}
		if (start_val <=  (limit_interval * -1) && start_val > -365) {
			slider_start = start_val;
		}
	}
	if (typeof(date_to) != "undefined") {
		end_date = Date.fromString(date_to);
		if (end_date.getFullYear() == year)	{
			end_val = end_date.getDayOfYear() - cur_day_num;
		} else {
			end_val = -1 * (365 - end_date.getDayOfYear() + cur_day_num);
		}

		if (Math.abs(slider_start - end_val) < limit_interval){
			end_val = end_val + limit_interval;
		}
		if (end_val <  0 && end_val > (-365 + limit_interval)) {
			slider_end = end_val;
		}
	}
	var start_limit = -365;
	if (typeof(first_date) != "undefined") {
		start_limit = Date.fromString(first_date);
		if (start_limit.getFullYear() == year)	{
			start_limit = start_limit.getDayOfYear() - cur_day_num;	
		} else if((year - start_limit.getFullYear()) == 1) {
			start_limit = -1 * (365 - start_limit.getDayOfYear() + cur_day_num);	
		}
	}

	if(!$("#date_interval_text").text()) {
		// Fill default date interval
		_date_from = _localized_date(slider_start);
		_date_to = _localized_date(slider_end);
		$("#date_interval_text").append(_date_from + " - " + _date_to);
	}
	$("#date_slider").slider({
		range: true,
		min: -365,
		max: 0,
		step: 1,
		values: [slider_start, slider_end],
		orientation: 'horizontal',
		start: function(event, ui) {
			handle1 = ui.values[0];
			handle2 = ui.values[1];
		},
		slide: function(event, ui) {

			if (Math.abs(parseInt(ui.values[1]) - parseInt(ui.values[0])) < limit_interval) {
				if (ui.values[0] == handle1) {
					ui.values[1] = ui.values[0] + limit_interval;
				} else {
					ui.values[0] = ui.values[1] - limit_interval;
				}
				return false;
			}

			if (ui.values[0] < start_limit) {
				ui.values[0] = start_limit;
				return false;
			}

			var now1 = new Date();
			d1 = now1.addDays(parseInt(ui.values[0]));
			date_from = now1.asString(d1);

			var now2 = new Date();
			d2 = now2.addDays(parseInt(ui.values[1]));
			date_to = now2.asString(d2);

			_date_from = _localized_date(ui.values[0]);
			_date_to = _localized_date(ui.values[1]);
			$("#date_interval_text").text(_date_from + " - " + _date_to);

		},
		stop: function(event, ui) {
			if (handle1 == ui.values[0] && handle2 == ui.values[1]) {
				return false;
			}
			new_url = date_url(date_from, date_to);
		}
	});

	$("#apply_date_interval").click(function(){
		new_url = date_url(date_from, date_to);
		window.location.href = new_url;
		return false;
	});

});



function date_url(from, to) {
	var url = window.location.href;
	url = trim_last_slash(url);
	parsed_url = url.split("/");
    replace_from = "";
	replace_to	 = "";
	$.each(parsed_url, function(i,v){
		if (v.substr(0,9) == 'date_from') {
			replace_from = v;
		}
		if (v.substr(0,7) == 'date_to') {
			replace_to = v;
		}
	});

	if (replace_from == ""){
		url = trim_last_slash(url);
		url = url + "/date_from." + from + "/";
	} else {
		url = url.replace(replace_from, "date_from." + from);
	}
	if (replace_to == ""){
		url = trim_last_slash(url);
		url = url + "/date_to." + to + "/";
	} else {
		url = url.replace(replace_to, "date_to." + to);
	}
	url_len = url.length;
	if (url.substr(url_len-1, url_len) != "/") {
		url = url + "/";
	}
	return url;
}

function trim_last_slash(str) {
	str_len = str.length;
	if (str.substr(str_len-1, str_len) == "/") {
		str = str.substr(0, str_len-1);
	}
	return str;
}


/*
if($.browser.msie){ //бубен для IE
	window.onload = function () {
		$(".country_svg").each(function(){
			var country_data = $(this);
			var paper = $(country_data).attr("id")+"_paper";
			var R = Raphael(paper, $("#"+paper).width(), $("#"+paper).height());
		});
	};
}
*/

function count( mixed_var, mode ) {    // Count elements in an array, or properties in an object
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: _argos
 
    var key, cnt = 0;
 
    if( mode == 'COUNT_RECURSIVE' ) mode = 1;
    if( mode != 1 ) mode = 0;
 
    for (key in mixed_var){
        cnt++;
        if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
            cnt += count(mixed_var[key], 1);
        }
    }
 
    return cnt;
}

//Localize date from slider value format "-365" to format "15 May 2009" for example
function _localized_date (_days) {
	cur_date = new Date();
	Date.format = 'dd-mm-yyyy';
	var _localized = cur_date.addDays(parseInt(_days));
	_month = _localized.getMonthName(true);
	_localized = _localized.asString();
	_localized = _localized.replace(/-\d{2}-/, " " + _month + " ");
	return  _localized;
}

function explode( delimiter, string ) {
    var emptyArray = { 0: '' };
 
    if ( arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
 
    return string.toString().split ( delimiter.toString() );
}


