mgr = null;
google_map = null;
notification = null;
map_markers = [];
current_notification_index = 0;
box = null;
email_forn = null;
overlay = null;
form_data = {answer : null, formation : null, team : null};

fb_links = [{"href":"http://tiricordiil2006.mediaworld.it/","text":"Partecipa"}];
fb_attachments = {
 	'site' : {"href":"http://tiricordiil2006.mediaworld.it/","name":"E tu ci credi? Puoi vincere una Alfa Mito!","media":[{"href":"http://tiricordiil2006.mediaworld.it/","src":"http://mondiali-minisito.cayenne-digital.it/images/fb_icon.png","type":"image"}],"caption":"tiricordiil2006.mediaworld.it","description":"Ricordi il 2006? Partecipa anche tu al sondaggio, puoi vincere una Alfa Mito con Media World."},
 	'yes' : {"href":"http://tiricordiil2006.mediaworld.it/","name":"Io CI CREDO! E forse vinco una Alfa Mito.","media":[{"href":"http://tiricordiil2006.mediaworld.it/","src":"http://mondiali-minisito.cayenne-digital.it/images/fb_icon.png","type":"image"}],"caption":"tiricordiil2006.mediaworld.it","description":"Ricordi il 2006? Partecipa anche tu al sondaggio, puoi vincere una Alfa Mito con Media World."},
	'no' : {"href":"http://tiricordiil2006.mediaworld.it/","name":"Io NON CI CREDO! Ma forse vinco una Alfa Mito.","media":[{"href":"http://tiricordiil2006.mediaworld.it/","src":"http://mondiali-minisito.cayenne-digital.it/images/fb_icon.png","type":"image"}],"caption":"tiricordiil2006.mediaworld.it","description":"Ricordi il 2006? Partecipa anche tu al sondaggio, puoi vincere una Alfa Mito con Media World."}
};

MARKER_ICON = new GIcon(G_DEFAULT_ICON);
MARKER_ICON.iconSize.width = 37;
MARKER_ICON.iconSize.height = 39;
MARKER_ICON.iconAnchor = new GPoint(18, 35);
MARKER_ICON.infoWindowAnchor = new GPoint(18, 18);

map_objects = {
	icons : {
		yes : new GIcon(MARKER_ICON),
		no	: new GIcon(MARKER_ICON)
	}
};

map_objects.icons.yes.image = "/images/marker_yes.png";
map_objects.icons.no.image = "/images/marker_no.png";

steps = {
	step1 : {width : 591, height : 587},
	step2 : {width : 715, height : 488},
	step3 : {width : 641, height : 460},
	step4 : {width : 556, height : 568},
	step5 : {width : 556, height : 568}
}
current_step = null

function Popup(name, city, answer, gender, lat, lng) {
	this.name_ = name;
	this.city_ = city;
	this.answer_ = answer;
	this.gender_ = gender;
	this.point_ = new GLatLng(lat, lng);
}

Popup.prototype = new GOverlay();
Popup.prototype.initialize = function(map) {
	var div = new Element('div', {'class' : 'popup'});
	var content = new Element('div', {'class' : 'content ' + this.gender_});
	var share = new Element('div', {'class' : 'share'});
	var answer_text = null;

	if (this.answer_ == 'yes')
		answer_text = '<span class="yes">ci crede</span>!';
	else
		answer_text = '<span class="no">non ci crede</span>!';
	content.insert({bottom : new Element('span', {'class' : 'name'}).update(this.name_)})
	content.insert({bottom : ' di ' + this.city_ + '<br />'});
	content.insert({bottom : new Element('span', {'class' : 'answer ' + this.answer_}).update(answer_text)});
	share_fb = new Element('a', {'href' : '#', 'class' : 'facebook'}).update('&nbsp;');
	share.insert({bottom : share_fb});
	share_twitter = new Element('a', {'href' : '#', 'class' : 'twitter'}).update('&nbsp;');
	share.insert({bottom : share_twitter})
	share_email = new Element('a', {'href' : '#', 'class' : 'email', 'id' : 'popup_share_email'}).update('&nbsp;');
	share.insert({bottom : share_email})
	div.insert({bottom : content});
	div.insert({bottom : share});
  map.getPane(G_MAP_MARKER_PANE).appendChild(div);
	share_email.observe('click', show_email_form);
	share_fb.observe('click', function(e){ e.stop(); fb_share(true); });
	share_twitter.observe('click', twitter_share);
  this.map_ = map;
  this.div_ = div;
}

Popup.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.popup_);
}

Popup.prototype.copy = function() {
  return new Popup(this.name_, this.city_, this.answer_, this.lat_, this.lng_);
}

Popup.prototype.redraw = function(force) {
	var p = this.map_.fromLatLngToDivPixel(this.point_);
	this.div_.style.left = '' + (p.x - 15) + 'px';
	this.div_.style.top = '' + (p.y - 103) + 'px';
}

Notification = function() {};
Notification.prototype = new GOverlay();
Notification.prototype.initialize = function(map) {
 	this.map_ = map;
  this.div_ = new Element('div', {'class' : 'notification'}, {'style' : 'display: none'});
	this.div_.style.position = "absolute";
	this.div_.style.top = "105px";
	this.div_.style.left= "70px";
	this.div_.style.width = "198px";
	this.div_.style.height = "28px";
	this.div_.style.padding = "2px 5px";
//  this.map_.getPane(G_MAP_FLOAT_PANE).appendChild(this.div_);
	$(document.body).insert(this.div_);
  this.visible_ = false
}
Notification.prototype.isVisible = function() { return this.visible_; }
Notification.prototype.remove = function() { this.div_.parentNode.removeChild(this.div_); }
Notification.prototype.copy = function() { return new Notification(); }
Notification.prototype.redraw = function(force) {}
Notification.prototype.appear = function() {
  this.visible_ = true
  new Effect.Appear($(this.div_), { duration : 0.3 });
}
Notification.prototype.fade = function() {
  this.visible_ = false
  new Effect.Fade($(this.div_), { duration : 1.0 });
}
Notification.prototype.showLabel = function(label) {
	$(this.div_).update(label);
}

function setup(vote) {
	$('fb_share').observe('click', function(e){ e.stop(); fb_share(false);});
	$('twitter_share').observe('click', twitter_share);
	$('email_share').observe('click', function(e){ e.stop(); show_email_form();});
	$('expand_map').observe('click', toggle_map);
	setup_map();
	mgr.addMarkers(map_markers, 6, 11);
	mgr.refresh();
	if (vote) setup_box();
}

function setup_map() {
  google_map = new GMap2($('map'));
  google_map.setCenter(new GLatLng(45.4612, 9.1878), 7);
	google_map.setUIToDefault();
	G_PHYSICAL_MAP.getMinimumResolution = function () { return 6 };
	G_NORMAL_MAP.getMinimumResolution = function () { return 6 };
	G_SATELLITE_MAP.getMinimumResolution = function () { return 6 };
	G_HYBRID_MAP.getMinimumResolution = function () { return 6 };

	G_PHYSICAL_MAP.getMaximumResolution = function () { return 11 };
	G_NORMAL_MAP.getMaximumResolution = function () { return 11 };
	G_SATELLITE_MAP.getMaximumResolution = function () { return 11 };
	G_HYBRID_MAP.getMaximumResolution = function () { return 11 };
	mgr = new MarkerManager(google_map);
	markers.each(function(m) {

		var marker = new GMarker(new GLatLng(m.lat, m.lng), {icon : map_objects.icons[m.answer], title : m.first_name });
		// google_map.addOverlay(marker);
		
		var msg = m.first_name + ' da ' + m.city;
		if (m.answer == 'yes') {
			msg += ' <span class="yes">ci crede</a>!';
		} else {
			msg += ' <span class="no">non ci crede</a>!';
		}
		marker.bindInfoWindow(new Element('div', {'class' : 'markerinfo'}).update(msg));
		map_markers.push(marker);
	});
	notification = new Notification();
	if (notifications.length > 0) { 
		google_map.addOverlay(notification);
		play_notifications();
	}
}


function play_notifications() {
	new PeriodicalExecuter(function(pe){
		if (notification.isVisible()) {
			notification.fade()
		} else {
			notification.showLabel(notifications[current_notification_index]);
			notification.appear();
			current_notification_index += 1;
			if (current_notification_index == notifications.length)
				current_notification_index = 0;
		}
	}, 3);
}

function setup_box() {
	overlay = new S2.UI.Overlay();
	box = new Element('div', {id : 'box'});
	$(document.body).insert(overlay);
	resize_box(556, 520);
	$(document.body).insert(box);
	new Ajax.Updater('box', '/box', {method : 'get', evalScripts : true})
}
	
function resize_box(width, height) {
  var viewport_size = document.viewport.getDimensions();
  var position = {
    left: ((viewport_size.width / 2) - (width / 2)).round(),
    top	: ((viewport_size.height / 2) - (height / 2)).round()
  };
  var offsets = document.viewport.getScrollOffsets();
  position.left += offsets.left;
  position.top  += offsets.top;
  box.setStyle({
		width	: width + 'px',
		height: height + 'px',
    left	: position.left + 'px',
    top		:  position.top  + 'px'
  });
}

function show_email_form() {
	var width = 273;
	var height = 365;
  var viewport_size = document.viewport.getDimensions();
  var position = {
    left: ((viewport_size.width / 2) - (width / 2)).round(),
    top	: ((viewport_size.height / 2) - (height / 2)).round()
  };
  var offsets = document.viewport.getScrollOffsets();
  position.left += offsets.left;
  position.top  += offsets.top;
	email_form = new Element('div', {id : 'email_form'});
	email_form.setStyle({
		width	: width + 'px',
		height: height + 'px',
    left	: position.left + 'px',
    top		:  position.top  + 'px'
  });
	overlay = new S2.UI.Overlay();
	$(document.body).insert(overlay);
	overlay.toElement().observe('click', close_email_form);
	$(document.body).insert(email_form);
	new Ajax.Updater('email_form', '/email', {method : 'get', evalScripts : true});
	return false;
}

function close_email_form() {
	email_form.remove();
	overlay.destroy();
}

function show_step(name) {
	resize_box(steps[name].width, steps[name].height);
	if (current_step != null) current_step.hide();
	current_step = $(name)
	current_step.show();
}

function select_formation(e) {
	e.stop();
	if (form_data.formation != null)
		$(form_data.formation).up().style.backgroundColor = '';
	form_data.formation = e.findElement('a').id;
//	$(form_data.formation).up().setStyle({'border-color' : 'red'})
	$(form_data.formation).up('div').style.backgroundColor = '#ffffd0';
	$('formation').value = form_data.formation;
}

function show_team_label(e) {
	var label = new Element('div', {'class' : 'label'})
	label.update('<span>' + e.findElement('img').readAttribute('alt') + '</span>')
	e.findElement('.team').insert({top : label})
}

function hide_team_label(e) {
	var label = e.findElement('.team').down('.label');
	if (label != null) label.remove();
}

function select_team(e) {
	e.stop();
	if (form_data.team != null)
		$(form_data.team).removeClassName('selected');
	form_data.team = e.findElement('a').hash.substring(1);
	$(form_data.team).addClassName('selected');
	$('team').value = form_data.team;
}

function placeholder_text(elem, text) {
	elem = $(elem);
	elem.addClassName('empty');
	elem.value = text;
	elem.store('placeholder', text);
	elem.observe('focus', function(e) {
		var elem = $(e.target);
		elem.removeClassName('error');
		if ($F(elem) == elem.retrieve('placeholder')) {
			elem.value = '';
			elem.removeClassName('empty');
		}
	});
	elem.observe('blur', function(e) {
		var elem = $(e.target);
		if ($F(elem) == '') {
			elem.value = elem.retrieve('placeholder');
			elem.addClassName('empty');
		}
	});
}

var email_expr = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

function check_registration_form() {
	var errors = false;
	if ($F('first_name') == '' || $('first_name').hasClassName('empty')) {
		$('first_name').addClassName('error');
		errors = true;
	}
	if ($F('last_name') == '' || $('last_name').hasClassName('empty')) {
		$('last_name').addClassName('error');
		errors = true;
	}
	if ($F('email') == '' || $('email').hasClassName('empty') || !$F('email').match(email_expr)) {
		$('email').addClassName('error');
		errors = true;
	}
	var day = parseInt($F('day'), 10);
	if (!(day >= 1 && day <= 31)) {
		$('day').addClassName('error');
		errors = true;
	}
	var month = parseInt($F('month'), 10); //  TOGLIERE LO ZERO INIZIALE
	if (!(month >= 1 && month <= 12)) {
		$('month').addClassName('error');
		errors = true;
	}
	var year = parseInt($F('year'), 10);
	if (!(year >= 1900 && year <= 2010)) {
		$('year').addClassName('error');
		errors = true;
	}
	var cap = $F('zip_code');
	if (cap == '' || $('zip_code').hasClassName('empty') || cap.length != 5) {
		$('zip_code').addClassName('error');
		errors = true;
	}
	
	if ($F('city') == null || $F('city') == '' || $F('province') == null || $F('province') == '') {
		$($('city').parentNode).down('.errormsg').show();
		errors = true;
	}
	var cf = $F('cf');
	if (cf == '' || $('cf').hasClassName('empty') || cf.length != 16) {
		$('cf').addClassName('error');
		errors = true;
	}
	
	// if (!$('privacy_yes').checked) {
	// 	$('privacy_message').show();
	// }
	return !errors;
}

function close_box() {
	box.remove();
	overlay.destroy();
}

function handle_registration_response(response) {
	var r = response.responseJSON;
	if (r.result == "success") {
		close_box();
		google_map.setCenter(new GLatLng(r.geo.lat, r.geo.lng));
		show_popup_on_map(r.record.answer, r.record.first_name, r.geo.city, r.record.gender, r.geo.lat, r.geo.lng);
	} else {
	  $('step4_fwd').enable();
	  $('spinner').hide();
		$($('zip_code').parentNode).down('.errormsg').update('');
		$($('day').parentNode).down('.errormsg').update('');
		$($('email').parentNode).down('.errormsg').update('');
		$($('cf').parentNode).down('.errormsg').update('');
		if (r.error == "invalid_zip_code") {
			$('zip_code').addClassName('error');
			$($('zip_code').parentNode).down('.errormsg').update(r.message);
		}
		if (r.error == "invalid_birth_date") {
			$('day').addClassName('error');
			$('month').addClassName('error');
			$('year').addClassName('error');
			$($('day').parentNode).down('.errormsg').update(r.message);
		}
		if (r.error == "email_found") {
			$('email').addClassName('error');
			$($('email').parentNode).down('.errormsg').update(r.message);
		}
		if (r.error == "invalid_fiscal_code") {
			$('cf').addClassName('error');
			$($('cf').parentNode).down('.errormsg').update(r.message);
		}
	}
}

function show_popup_on_map(answer, name, city, gender, lat, lng) {
	var popup = new Popup(name, city, answer, gender, lat, lng);
	google_map.addOverlay(popup);
	return popup;
}

function _fb_share(e) {
	if (e) e.stop();
	// var u = location.href;
	// var t = document.title;
	// window.open("http://www.facebook.com/sharer.php?u="+encodeURIComponent(u)+"&t="+encodeURIComponent(t),"sharer","toolbar=0,status=0,width=626,height=436");
	// return false;
//  FB.ensureInit(function () {
    FB.Connect.streamPublish('', null, null);
//  });
	return false
}

function twitter_share(e) {
	if (e) e.stop();
	msg = "Ti+ricordi+il+2006?+http://bit.ly/aa1fuv"
	window.open("http://www.twitter.com/?status="+msg,"twitter","toolbar=0,status=0,width=626,height=436");
	return false;
}

function check_email_form() {
	var errors = false;
	if ($F('email_sender_name') == '' || $('email_sender_name').hasClassName('empty')) {
		$('email_sender_name').addClassName('error');
		errors = true;
	}
	if ($F('email_sender_address') == '' || $('email_sender_address').hasClassName('empty') || !$F('email_sender_address').match(email_expr)) {
		$('email_sender_address').addClassName('error');
		errors = true;
	}
	if ($F('email_rcpt_name') == '' || $('email_rcpt_name').hasClassName('empty')) {
		$('email_rcpt_name').addClassName('error');
		errors = true;
	}
	if ($F('email_rcpt_address') == '' || $('email_rcpt_address').hasClassName('empty') || !$F('email_rcpt_address').match(email_expr)) {
		$('email_rcpt_address').addClassName('error');
		errors = true;
	}
	return !errors;
}

var map_is_expanded = false
function toggle_map(e) {
	e.stop();
	if (map_is_expanded) {
		new Effect.Morph('map', { style : { height : '430px' }, duration : 1.0 });
	} else {
		new Effect.Morph('map', { style : { height : '700px' }, duration : 1.0 });
	}
	map_is_expanded = !map_is_expanded;
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
		if (status.indexOf('#mondiali') >= 0) {
    	statusHTML.push('<span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a>');
		  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
			$('twitter').show();
			return;
		}
  }
}

function twitterCallback(data) {
	if (data.results && data.results.length > 0) {
		rt = relative_time(data.results[0].created_at);
		$('twitter_update_list').update('<span class="text">' + data.results[0].text + '</span> <span class="ts">' + rt + '</span>');
		$('twitter_update').show();
	}
}

function relative_time(time_value) {
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'meno di un minuto fa';
  } else if(delta < 120) {
    return 'circa un minuto fa';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minuti fa';
  } else if(delta < (120*60)) {
    return "circa un\'ora fa";
  } else if(delta < (24*60*60)) {
    return 'circa ' + (parseInt(delta / 3600)).toString() + ' ore fa';
  } else if(delta < (48*60*60)) {
    return '1 giorno fa';
  } else {
    return (parseInt(delta / 86400)).toString() + ' giorni fa';
  }
}

function fb_share(use_answer) {
	if (use_answer) {
		att = fb_attachments[form_data.answer];
	} else {
		att = fb_attachments['site'];
	}
  FB.Connect.streamPublish('', att, fb_links);
}

