﻿try { if (window.console == undefined) { window.console = { log: function() {} }; } } catch (e) {}
var typeRouteMap				= "short";
var typeRouteReturn			= "fast";
var userid_redazionale	= "f-OtVDj4/miV0Lrgmv";

printAction = function() {
	var url = getMapUrl("stampa.html").replace('undefined', '');
	window.open(url, "Stampa");
}

function getMapUrl(_pageName) {
	var arrInfoCenterMap	= GetInfoCenterMap(map);
	//var strUrl						= "http://"+ window.location.hostname +"/"+ _pageName +"?lat1="+ arrInfoCenterMap[0] +"&lon1="+ arrInfoCenterMap[1] +"&zoom="+ arrInfoCenterMap[2] +"&style="+ arrInfoCenterMap[3] +"&orientation="+ arrInfoCenterMap[4] +"&zoomO="+ zoomLevelMap +"&width=425px&height=350px";
	var strUrl						= "http://"+ window.location.hostname +"/"+ _pageName +"?lat="+ arrInfoCenterMap[0] +"&lon="+ arrInfoCenterMap[1] +"&zoom="+ arrInfoCenterMap[2] +"&style="+ arrInfoCenterMap[3] +"&orientation="+ arrInfoCenterMap[4] +"&zoomO="+ zoomLevelMap;
	var type							= readCookie("print");
	var s 								= "";
	switch (type)
	{
		case "route":
			var qs_partenza, qs_destinazione;
			var qs_sosta;
			var optimizedDistance	= "1";
			
			var partenza						= getIndirizzo("indirizzo",2); //da generalizzare
			var destinazione				= getIndirizzo("indirizzo",3); //da generalizzare
			
			var htmlStops = $("#ROUTEDIRECTIONS>ol").children("div");
			var qs_itinerario = "";
			$.each(htmlStops, function(index, item) {
								var sosta = getIndirizzo("indirizzo",index+2);
								var lat = $("#sosta-lat-"+(index+2)).val();
								var lon = $("#sosta-lon-"+(index+2)).val();
								qs_sosta	= "&indirizzo"+(index+1)+"="+ escape(sosta.address)+"&paese"+(index+1)+"="+ escape(sosta.country) +"&lat"+(index+1)+"="+ lat +"&lon"+(index+1)+"="+ lon;
								qs_itinerario+=qs_sosta;
			});
			
			if (typeRouteMap != "short") optimizedDistance = "0";
			if (qs_itinerario)
				s = qs_itinerario +"&service=FindRoute";
			if (s)
				strUrl += s;
			break;
		case "aziende":
			var indirizzo	= getIndirizzo('azienda'); // 2.0
			if (indirizzo.address)
				s = "&cosacerchi="+ escape(indirizzo.cosa) +"&indirizzo1="+ escape(indirizzo.address) +"&paese1="+ escape(indirizzo.country);
			if (s)
				strUrl = strUrl + s +"&service=FindCompany";
			break;
		default:
			var indirizzo	= getIndirizzo('indirizzo'); // 2.0
			if (indirizzo.address)
				s = "&indirizzo1="+ escape(indirizzo.address) +"&paese1="+ escape(indirizzo.country);
			if(s)
				strUrl = strUrl + s +"&service=FindAddress";
			break;
	}
	return strUrl;
}

function GetInfoCenterMap(map) {

	var info = "", orientation = "";
	var latCenter, longCenter, zoomLevel, styleMap;
	zoomLevelMap	= "2";
	zoomLevel			= map.GetZoomLevel();
	styleMap			= map.GetMapStyle();
	latCenter			= map.GetCenter().Latitude;
	longCenter		= map.GetCenter().Longitude;
	

	if ( map.IsBirdseyeAvailable() )
	{
		if (styleMap=="b" || styleMap=="o")
		{
			var be					= map.GetBirdseyeScene();
			orientation			= be.GetOrientation();
			orientationMap	= orientation;
			zoomLevelMap		= map.GetZoomLevel();
			map.SetMapStyle("r");
			zoomLevel				= map.GetZoomLevel();
			latCenter				= map.GetCenter().Latitude;
			longCenter			= map.GetCenter().Longitude;
			map.SetMapStyle(styleMap);

			setTimeout(function() {
				map.SetBirdseyeOrientation(orientationMap);
				map.SetZoomLevel(zoomLevelMap);
			}, 600);
		}
	}
	return [latCenter, longCenter, zoomLevel, styleMap, orientation];
}
function getIndirizzo(_type, index) {
	var indirizzo = new Address();
	if (index >=2 ){
		indirizzo.address	= ($("#indirizzo"+index).val() != document.getElementById('indirizzo'+index).defaultValue) ? $("#indirizzo"+index).val() : "";
		if(indirizzo.address)
				indirizzo.country	= $("#italia"+index).attr("checked")?"IT":"-";
		
	}
	else
	if (_type == "indirizzo")
	{
		indirizzo.address	= ($("#address_text").val() != document.getElementById('address_text').defaultValue) ? $("#address_text").val() : "";
		if(indirizzo.address)
			indirizzo.country	= $("#italia").attr("checked")?"IT":"-";
		else indirizzo.country = "IT";
	}
	else if (_type == "azienda")
	{
		indirizzo.address	= ($("#indirizzo-aziende").val() != document.getElementById('indirizzo-aziende').defaultValue) ? $("#indirizzo-aziende").val() : "";
		indirizzo.country	= indirizzo.address ? "IT" : "";
		indirizzo.cosa		= ($("#cosacerchi").val() != document.getElementById('cosacerchi').defaultValue) ? $("#cosacerchi").val() : "";
	}

	return indirizzo;
}
	
	
// time is an integer representing seconds
// returns a formatted string
GetTime =  function(time) {
	if (time == null) {
		return("");
	}
	if (time > 60) {                                 
		var seconds = time % 60;       
		var minutes = time - seconds;  
		minutes = minutes / 60;
		if (minutes > 60) {
			var minLeft = minutes % 60;
			var hours = minutes - minLeft;
			hours = hours / 60;
			return (hours + " ore, " + minLeft + " min, " + seconds + " sec");
		} else {
			return(minutes + " min e " + seconds + " sec");
		}
  } else {
  	return(time + " sec");
	}
}


/* Querystring functions */
function Querystring(qs) { // optionally pass a querystring to parse

	this.params = new Object();
	this.get = Querystring_get;

	if (qs == null)
		qs = location.search.substring(1,location.search.length);

	if (qs.length == 0) return;

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

	// split out each name=value pair
	for (var i=0; i<args.length; i++)
	{
		var value;
		var pair = args[i].split('=');
		var name = unescape(pair[0]);

		if (pair.length == 2)
			value = unescape(pair[1]);
		else
			value = name;

		this.params[name] = value;
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;

	var value = "";
	if (key=="")
 		value = this.params;
	else value = this.params[key];
	
	if (value==null) value = default_;
	
	
	return value;
}

/* Cookie features */
function createCookie( _name, _value, _days ) {
	if (_days)
	{
		var date = new Date();
		date.setTime(date.getTime() + _days*24*60*60*1000);
		var expires = "; expires="+ date.toGMTString();
	} else
		var expires = "";
	document.cookie = _name +"="+ _value + expires +"; path=/";
}

function readCookie( _name ) {
	var nameEQ	= _name +"=";
	var ca		= document.cookie.split(';');
	for (var i=0; i<ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);

		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie( _name ) {
	createCookie(_name, "", -1);
}

/* UTF-8 encoding/decoding features */
function _utf8_encode( _string ) {
	var utftext = "";
	if (_string){
	_string = _string.replace(/\r\n/g,"\n");
	
	for (var n=0; n<_string.length; n++)
	{
		var c = _string.charCodeAt(n);
		if (c < 128)
		{
			utftext += String.fromCharCode(c);
		} else if ((c > 127) && (c < 2048))
		{
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		} else
		{
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}
}
	return utftext;
}

function _utf8_decode( _utftext ) {
	var string = "", i = 0, c = c1 = c2 = 0;
	while (i < _utftext.length)
	{
		c = _utftext.charCodeAt(i);
		if (c < 128)
		{
			string += String.fromCharCode(c);
			i++;
		} else if ((c > 191) && (c < 224))
		{
			c2 = _utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		} else
		{
			c2 = _utftext.charCodeAt(i+1);
			c3 = _utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	return string;
}

/* String features */
function capWords( _inputString ) {
	var outputString = "", tmpStr, tmpChar, preString, postString, strlen;
	tmpStr		= _inputString.toLowerCase();
	stringLen	= tmpStr.length;
	if (stringLen>0)
	{
		for (var i=0; i<stringLen; i++)
		{
			if (i==0)
			{
				tmpChar			= tmpStr.substring(0, 1).toUpperCase();
				postString	= tmpStr.substring(1, stringLen);
				tmpStr			= tmpChar + postString;
			} else
			{
				tmpChar = tmpStr.substring(i, i+1);
				if ( ((tmpChar == " ") || (tmpChar == "'")) && i < (stringLen-1) )
				{
					tmpChar			= tmpStr.substring(i+1, i+2).toUpperCase();
					preString		= tmpStr.substring(0, i+1);
					postString	= tmpStr.substring(i+2, stringLen);
					tmpStr			= preString + tmpChar + postString;
				}
			}
		}
	}
	outputString = tmpStr;
	return outputString;
}

String.prototype.capitalize = function() {
	return this.replace( /(^|\s)([a-z])/g , function(m, p1, p2) { return p1+p2.toUpperCase(); } );
};

String.prototype.toStringUrl = function() {
	return this.replace(/\'/g, "\\'").replace(/\"/g, "\\'");
};

String.prototype.toStringHtml = function() {
	//return this.replace(/\\"/g, "&quot;").replace(/\\'/g, "'").replace(/\\\\/g, "\\");
	return this.replace(/\\"/g, "&quot;").replace(/\\'/g, "'").replace(/\\\\/g, "\\").replace(/&#039;/g,"'").replace(/&#034;/g,"\"");
	
};

/* Others */
function getPoiTitleValue(_default) {
	var desc;
	
	($("#poiDesc") && $("#poiDesc").val()) ? desc = $("#poiDesc").val() : $("div#address_found>p").val() ? desc = $("div#address_found>p").val() : "";
	if (!desc)
		_default ? desc = _default.toStringHtml() : desc = "PUNTO DI INTERESSE";

	return desc;
}

function getPoiAddressValue(_default) {
	var desc;
	($("#poiAddress") && $("#poiAddress").val()) ? desc = $("#poiAddress").val() : $("div#address_found>p").val() ? desc = $("div#address_found>p").val() : "";
	if (!desc)
		_default ? desc = _default.toStringHtml() : desc = "";

	return desc;
}


function trim(stringValue){
	return stringValue.replace(/^\s+|\s+$/g,'');

}

/* Mostra codice */
function show_code(wdh,hgh,sel) {
	fill_over(wdh, hgh, sel);
	var cntH = Math.round($('#content').height()/2)-173;
	var cntW = Math.round($('#content').width()/2)-263;
	$('#div-code-blog').html("Caricamento in corso...");
	var html =	"<div style=\"width:425px; background:url(http://mappe.virgilio.it/images/map_blog_bg.gif) repeat-x\">"+
							"<a href=\"http://mappe.virgilio.it\"><img src=\"http://mappe.virgilio.it/images/map_blog_ico.gif\" alt=\"Virgilio Mappe\" style=\"border:0\" /></a>"+
							"<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\""+ getMapUrl("mappa.html").replace('undefined', '') +"\"></iframe>"+
							"</div>";
	$('#code_blog').val(html);
	$('#div-code-blog').html("<textarea id=\"code_blog\" class=\"textarea\" name=\"codetext\" rows=\"6\" cols=\"60\">"+ html +"</textarea>");
	$("#copy_link").val(getMapUrl("index.html"));
}

function hide_code(sel) {	
	$('.overLay').remove();
	$('#overlay_cnt').attr('style', '');
	$('#overlay_cnt').hide();
	$('#'+sel+'').attr('style', '');
}

/*
function setDimValue(el,event) {
  if (isNaN(el.val())){ el.val(" "); return ;}
	 var textDiv = $("#code_blog").val();
		switch (el.attr("id")){
		case "w_blog":
				var patternWidth1 = "width=\"[a-zA-Z0-9]*\"";
				var patternWidth2 = "width:[a-zA-Z0-9]*px;";
				var patternWidth3 = "width=[a-zA-Z0-9]*px";
				textDiv = replaceMatch(patternWidth1,textDiv,"width=\""+el.val()+"\"");
				textDiv = replaceMatch(patternWidth2,textDiv,"width:"+el.val()+"px;");
				textDiv = replaceMatch(patternWidth3,textDiv,"width="+el.val()+"px");
		break;
		case "h_blog":
				var patternHeight1 = "height=\"[a-zA-Z0-9]*\"";
				var patternHeight2 = "height:[a-zA-Z0-9]*px;";
				var patternHeight3 = "height=[a-zA-Z0-9]*px";
				textDiv = replaceMatch(patternHeight1,textDiv,"height=\""+el.val()+"\"");
				textDiv = replaceMatch(patternHeight2,textDiv,"height:"+el.val()+"px;");
				textDiv = replaceMatch(patternHeight3,textDiv,"height="+el.val()+"px");
		break;
		}
		$("#code_blog").val(textDiv);
}*/

function replaceMatch(patternText, textToMatch, textToReplace) {
	var pattern = new RegExp(patternText);
	var resultMatch = textToMatch.match(pattern);
	if (pattern.test(textToMatch)) {
		textToMatch = eval('textToMatch.replace(/'+ resultMatch +'/g,textToReplace)');
	}
	return textToMatch;
}

function openWindow(mapUrl, pageName) {
	mapUrl = mapUrl.replace(/undefined/g, "");
	var qs = mapUrl.substring(mapUrl.indexOf("?")+1,mapUrl.length);
	window.open('/'+ pageName +'?'+ qs, '', 'width=833,height=488,resizable=yes');
}

/* OVERLAY */
function fill_over(wdh, hgh, sel) {
	var scrH = $('#content').height();
	var scrW = $('#content').width();
	var overLay = $('<div/>').attr('class', 'overLay').css({'width':scrW, 'height':scrH});
	$('BODY').append(overLay);
	$('#overlay_cnt').css({
		'top': scrH/2 +'px',
		'left': scrW/2 +'px'
	}).animate({
		'width': wdh +'px',
		'height': hgh +'px',
		'left': '-='+(wdh/2)+'px',
		'top': '-='+(hgh/2)+'px'
	},1000,function(){
		$('#'+sel+'').css('display', 'block')	  
	})
	$('.overLay').bind('click', function(){
		$(this).remove();
		$('#overlay_cnt').attr('style', '');
		$('#overlay_cnt').hide();
		$('#'+sel+'').attr('style', '');
	});
}

