/**
 * Disabilita l'override delle funzioni Prototype
 */
jQuery.noConflict();

/**
 * Funzione per l'invio di una mail
 */
function sendmail(user, domain) {
	if (!domain) { domain = 'keycode.it'; }
	window.open('mailto:'+user+'@'+domain, '_self');
}

function getLanguage() {
	languages = ['italian', 'english', 'german', 'spanish'];
	for (i = 0; i < languages.length; i++) {
		if (document.location.href.indexOf('/'+languages[i]+'/') != -1) {
			return languages[i];
		}
	}
	return 'italian';
}

/**
 * Script per l'attivazione dell'effetto dei top links
 */
jQuery(function(){
	//add enhanced class to body
	jQuery('body').addClass('jquery');

	jQuery('#top-links li').hover(
		function(){
			obj = jQuery(this).find('img'); 
			obj.attr('src', obj.attr('src').replace('.png', '-over.png').replace('spacer.1x24-over', 'spacer.1x24'));
			jQuery(this).find('a:hidden').show();
		},
		function(){
			obj = jQuery(this).find('img'); 
			obj.attr('src', obj.attr('src').replace('-over.png', '.png').replace('spacer.1x24-over', 'spacer.1x24'));
			jQuery(this).find('a:visible').hide();
		}
	);
});

/**
 * Script per l'effetto JS del template Case-History
 */
jQuery(function(){
	//add enhanced class to body
	jQuery('body').addClass('jquery');

	jQuery('#griglia li').hover(
		function(){jQuery(this).find('div.layer:hidden').fadeIn(500);},
		function(){jQuery(this).find('div.layer:visible').fadeOut(200);}
	);

	//cta click
	jQuery('#griglia li div p').click(function(){
		jQuery(this).parent().prev().trigger('click');
	});
});

activeBox = 0;

/**
 * Script per l'animazione del box di ogni case history
 */
function animateCaseHistory(action, cid, box) {
	language = getLanguage();
	switch(action) {
		case 'open-left': case 'open-right':
			jQuery("#currentCaseHistory").css('left', (action == 'open-left' ? 8 : 438));
			if (cid) { jQuery.get("/"+language+"/case-history.php", { action: 'gch', cid: cid }, function(data){
				jQuery("#box-" + box).find('img').css('background-position', '0px -125px'); 
				activeBox = box; jQuery("#currentCaseHistoryContent").html(data);
				jQuery("#currentCaseHistoryContainer").animate({ height: 391, width: 422, opacity: 1 }, 1000);
			});	}
			break;
		case 'close':
			jQuery("#currentCaseHistoryContainer").animate({ height: 0, width: 0, opacity: 1 }, 1000);
			if (activeBox) { jQuery("#box-" + activeBox).find('img').css('background-position', '0px 0px'); }
			break;
	}
}

/**
 * Script per il calendario
 */
function CalendarioCaricato() {
	jQuery('.date_has_event').each(function () {
		// options
		var distance = 10;
		var time = 250;
		var hideDelay = 300;

		var hideDelayTimer = null;

		// tracker
		var beingShown = false;
		var shown = false;

		var trigger = jQuery(this);
		var popup = jQuery('.events ul', this).css('opacity', 0);

		// set the mouseover and mouseout on both element
		jQuery([trigger.get(0), popup.get(0)]).mouseover(function () {
			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);

			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;

				// reset position of popup box
				popup.css({
					bottom: 20,
					left: -76,
					display: 'block' // brings the popup back in to view
				})

				// (we're using chaining on the popup) now animate it's opacity and position
				.animate({
					bottom: '+=' + distance + 'px',
					opacity: 1
				}, time, 'swing', function() {
					// once the animation is complete, set the tracker variables
					beingShown = false;
					shown = true;
				});
			}
		}).mouseout(function () {
			// reset the timer if we get fired again - avoids double animations
			if (hideDelayTimer) clearTimeout(hideDelayTimer);

			// store the timer so that it can be cleared in the mouseover if required
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.animate({
					bottom: '-=' + distance + 'px',
					opacity: 0
				}, time, 'swing', function () {
					// once the animate is complete, set the tracker variables
					shown = false;
					// hide the popup entirely after the effect (opacity alone doesn't do the job)
					popup.css('display', 'none');
				});
			}, hideDelay);
		});
	});
}

/**
 * Script per il calendario
 */
function CaricaCalendario(year, month) {
	jQuery("#loading-mask").show(); jQuery("#loading").show();
	jQuery.get("/_templates/php-scripts/keycode-academy.php", { action: 'get-calendar', year: year, month: month}, function(data) {
		jQuery("#calendar").html(data);
		CalendarioCaricato();
		jQuery("#loading-mask").hide(); jQuery("#loading").hide();
	});
	return false;
}

function CaricaEvento(obj, eid) {
	linkObj = jQuery(obj); linkPos = linkObj.offset(); 
	destObj = jQuery("#destination-label"); destPos = destObj.offset(); destObj.html('');
	labelObj = jQuery("#floating-label");
	labelObj.html(linkObj.html());
	labelObj.css('top', linkPos.top + 'px').css('left', linkPos.left + 'px');
	labelObj.show().animate({ left: (destPos.left + 20) + 'px', top: destPos.top + 'px', fontSize: '16px' }, 500, '', function() {
		labelObj = jQuery("#floating-label");
		jQuery("#destination-label").show(); jQuery("#destination-text").show();
		jQuery("#destination-label").html(labelObj.html()); labelObj.hide();
		jQuery.get("/_templates/php-scripts/keycode-academy.php", { action: 'get-event-desc', eid: eid }, function(data) {
			jQuery("#destination-text").html(data);
			jQuery("#step-two-closer").click(function(){ ChiudiEvento(); });
			jQuery("#step-two-closer").css('display', 'block');
		});
	});
	jQuery("#step-two").css('visibility', 'visible');
	jQuery("#step-two-mask").animate({ opacity: 1 }, 500);
	return false;
}

function ChiudiEvento() {
	jQuery("#step-two").animate({ opacity: 0 }, 500, '', function() {
		jQuery("#step-two").css('visibility', 'hidden');
		jQuery("#step-two-closer").css('display', 'none');
		jQuery("#step-two-mask").css('opacity', 0);
		jQuery("#step-two").css('opacity', 1);
		jQuery("#destination-text").html('');
	});
	if (jQuery("#step-three").css('visibility') == 'visible') {
		jQuery("#step-three").animate({ opacity: 0 }, 500, '', function() {
			jQuery("#step-three").css('visibility', 'hidden');
			jQuery("#step-three").css('height', 0);
			jQuery("#step-three").css('opacity', 1);
		});
	}
}

function CaricaForm(eid) {
	jQuery("#step-three").css('visibility', 'visible');
	jQuery("#step-three").animate({ height: '430px' }, 500);
	jQuery("#eid").val(eid);
	return false;
}

function InviaIscrizione() {
	jQuery("#loading-mask").show(); jQuery("#loading").show();
	jQuery.post("/_templates/php-scripts/keycode-academy.php", {
		action: 'subscribe',
		eid: jQuery("#eid").val(),
		name: jQuery("#name").val(),
		surname: jQuery("#surname").val(),
		society: jQuery("#society").val(),
		number: jQuery("#number").val(),
		phone: jQuery("#phone").val(),
		mobile: jQuery("#mobile").val(),
		email: jQuery("#email").val()
	}, function(data){ 
		jQuery("#step-three-content").html(data);
		jQuery("#loading-mask").hide();
		jQuery("#loading").hide(); 
	});
	return false;
}

/**
 * Dati e funzioni relative alla Mappa con la sede aziendale
 */
latitudine = 45.52564432918267; 
longitudine = 10.211734065589905; 
zoom = 15;

messaggio  = '<div style="width: 120px;">';
messaggio += '<strong>KeyCode Italia Srl</strong><br />';
messaggio += 'Via Cipro, 1<br />';
messaggio += '25124, Brescia (BS)<br />';
messaggio += '<br />';
messaggio += 'P.IVA 02969290986';
messaggio += '</div>';

function LoadMap() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("g-map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(latitudine, longitudine), zoom);
		var point = new GLatLng(latitudine,longitudine);
		var icon = new GIcon();
		icon.image = "http://www.gsosangiacinto.com/images/marker.png";
		icon.iconSize = new GSize(20, 34);
		icon.iconAnchor = new GPoint(10, 34);
		icon.infoWindowAnchor = new GPoint(18, 2);
//		icon.shadow = "http://www.gsosangiacinto.com/images/marker-shadow.png"; 
//		icon.shadowSize = new GSize(39, 34);
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(messaggio);
		})
		map.addOverlay(marker);
	}
}


/**
 * Script generici
 */
jQuery(document).ready(function(){
	document.documentElement.className = "js";
	ch = jQuery('#currentCaseHistoryCloser');
	if (ch) { ch.click(function(){ animateCaseHistory('close'); }); }
	if (document.getElementById("calendar")) { CalendarioCaricato(); } 
	else if (!document.getElementById("griglia")) { jQuery(document).pngFix(); }
	if (document.getElementById("g-map")) { LoadMap(); window.onunload = GUnload; }
});

/**
 * Traduzione dei campi tendina
 */
jQuery(document).ready(function(){
	translations = new Array();
	translations['Azienda'] = 'Company';
	translations['Privato'] = 'Private person';
	translations['Professionista'] = 'Free lance';

	translations['Motori di ricerca'] = 'Search engines';
	translations['Stampa'] = 'Press';
	translations['Passaparola'] = 'Friends';
	translations['Visita di un nostro commerciale'] = 'KeyCode seller';
	translations['Eventi KeyCode'] = 'KeyCode meetings';
	if (/^(.+)\/english\/(.+)$/.test(document.location.href)) {
		jQuery("select > option").each(function(idx) {
			opt = jQuery(this);
			if(typeof translations[opt.text()] != 'undefined') {
				opt.text(translations[opt.text()]);
			}
		});
	}
});