SG = window.SG || {};

SG.menu = {};


/* Change Language */
SG.changeLanguage = function(lang) {
	$("#lang-id").val(lang);
	$("#form-language").submit();
}

/*
SG.toggleAudio = function() {
	var player = parent.$f(0);
	$(".sound-control").toggle();
	if (player.getState() == 3) {
		player.pause();
	}
	else if (player.getState() == 4) {
		player.play();
	}
};
*/

SG.starSoundControl = function() {
	$(".sound-control").hover(
		function() {
			$(".sound-control").toggle();
		},
		function() {
			$(".sound-control").toggle();
		});
};

SG.openFullscreen = function() {
	/* Stop player audio 
	parent.$f(0).stop();
	*/
	window.open('home.html','kyscorp','target=_blank,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,width='+screen.width+',height='+screen.height+',top=0,left=0'); 
};

SG.fullBackground = {};

SG.fullBackground.startSupersized = function(data) {
	$.supersized({
		slideshow: 1,
		autoplay: 1,
		start_slide: 1,
		random: 0,
		slide_interval: 7000,
		transition: 1,
		transition_speed: 800,
		new_window: 0,
		pause_hover: 0,
		keyboard_nav: 0,
		performance: 1,
		image_protect: 0,
		image_path: 'images/supersized/',
		
		min_width: 0,
		
		vertical_center: 1,
		horizontal_center: 1,
		fit_landscape: 0,

		navigation: 0,
		thumbnail_navigation: 0,
		slide_counter: 0,
		slide_captions: 0,
		custom_navigation: 1,
		slides : data
	});
};


/*
 *	Bottom Menu Component
 */
SG.menu.lock=false;
SG.menu.tmpWidth=220;
SG.menu.init = function() {
	$("#nav-menu .field").click(function() {
		var ref = this;

		if ($(ref).hasClass("link")) {
			location.href=$(ref).attr("rel");
			return;
		}

		if ($(ref).hasClass("open") || $(ref).hasClass("gallery-link")) {
			return;
		}

		if (SG.menu.lock) {
			return;
		}
		SG.menu.lock=true;
		var closeWidth = SG.menu.tmpWidth;
		if ($("#nav-menu .field.open").length) {
			$("#nav-menu .field.open .sub").fadeOut(400, function() {
				$("#nav-menu .field.open .desc").fadeIn(500, function() {
					$("#nav-menu .field.open").stop().animate({ width: closeWidth }, 400, function() {
						$("#nav-menu .field").removeClass("open");
						SG.menu.openField(ref);
					});
				});
/*
				$("#nav-menu .field.open").stop().animate({ width: closeWidth }, 400, function() {
					$("#nav-menu .field.open .desc").fadeIn(500);
					$("#nav-menu .field").removeClass("open");
					SG.menu.openField(ref);
				});
*/
				$("#nav-menu .field.open .desc").fadeIn(400);
			});
		}
		else {
			SG.menu.openField(ref);
		}
	});
	$("#nav-menu .field .gallery-link").click(function() {
		$("#nav-menu .field .gallery-link.active").removeClass("active");
		$(this).addClass("active");
	});

	$(".gallery-link").click(function(e) {
		e.preventDefault();
		SG.menu.initGallery(this, $(this).attr('rel'));
	});

};

SG.menu.openField = function(ref) {
	$("#nav-menu .field .gallery-link.active").removeClass("active");

	var openWidth = "550px";

	if ( $(ref).find(".gallery-link").length > 12 ) {
		openWidth = "650px";
	}
	if ( $(ref).find(".gallery-link").length < 6 ) {
		openWidth = "265px";
	}

	SG.menu.tmpWidth = $(ref).width();
	$(ref).stop().animate({ width: openWidth }, 400, function() {
		$(ref).find(".desc").fadeOut(500, function() {
			$(ref).find(".sub").fadeIn(500);
			$(ref).addClass("open");
			SG.menu.lock=false;

			
			/* Handle gallery */
			$(".gallery-link").click(function() {
				//SG.menu.initGallery(ref, $(this).attr('rel'));
			});
			
			//SG.menu.initGallery(ref);

		});
	});
};

SG.menu.setWhiteLogo=function() {
	if ( $("#header").hasClass("white") ) {
		return;
	}
	$("#header").fadeOut('fast',
	function() {
		$("#header").addClass("white");
		$("#header").fadeIn();
	});
};
SG.menu.setBlackLogo=function() {
	if ( !$("#header").hasClass("white") ) {
		return;
	}
	$("#header").fadeOut('fast',
	function() {
		$("#header").removeClass("white");
		$("#header").fadeIn();
	});
};

SG.menu.initGallery = function(ref, id) {
	SG.menu.scrollInitialized = false;
	/* Ajax load gallery */
	$(".gallery").html();
	$(".gallery").remove();
	$.ajax({
		type: 'get',
		url: 'action/gallery.php',
		data: { id: id },
		success: function(data) {
			$("body").append(data);
			$(".gallery-nav").remove();

			$("#gallery-title").html( "<div id=\"gallery-title-content\" style=\"position:relative\">" + $("#gallery-start").attr("title") + "</div>");
//			$("#gallery-title").html( $("#gallery-start").attr("title") );
			$(".gallery a[rel=picture_group]").fancybox({
				'overlayColor'		: '#000000',
				'padding'		: '0',
				'transitionIn'		: 'fade',
				'transitionOut'		: 'fade',
				'titlePosition' 	: 'outside',
				'showNavArrows'		: true,
				'overlayOpacity'			: 0.94,
				'onComplete': function() {
					if(!SG.menu.scrollInitialized){
						SG.pageContent.initScroll("#gallery-title-content", false);
						SG.menu.scrollInitialized=true;
					}
				},
				'onStart'		: function() {
					$("#footer").fadeOut();
					$("#nav-menu").fadeOut();
					//$("#gallery-title").fadeIn();
					$("#nav-pause").click();
					SG.menu.setWhiteLogo();
				},
				'onClosed'		: function() {
					$("#nav-menu .field .gallery-link.active").removeClass("active");
					$("#gallery-title").fadeOut();
					$("#footer").fadeIn();
					$("#nav-menu").fadeIn();
					$("#nav-play").click();
					SG.menu.setBlackLogo();
				},
				'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
					//var label = '<div class="gallery-nav"><span class="gallery-prev">prev. &lt;</span> <span id="gallery-index"></span> <span class="gallery-next">&gt; next</span></div>';
					var cssPrevVisibility = "visibility: hidden;";
					var cssNextVisibility = "visibility: hidden;";
					if (currentIndex > 0) {
						var cssPrevVisibility = "visibility: visible;";
					}
					if (currentIndex < currentArray.length-1) {
						cssNextVisibility = "visibility: visible;";
					}
					var label = '<span id="fancybox-title-over">\
							<div class="navigator">';
					label += '<div style="' + cssPrevVisibility + '" class="gallery-prev" onClick="javascript: $.fancybox.prev();">prev.</div>';
					label += '<div class=\'page-index\'>'+(currentIndex + 1) + ' / ' + currentArray.length + '</div>';
					label += '<div style="' + cssNextVisibility + '" class="gallery-next" onClick="javascript: $.fancybox.next();">next</div>';
					label += '</div>';
//					label += (title.length ? '<div class=\'clear\'></div>' + title : '') + '</span>';
					return label;
				}

			});
			$(".navigator .gallery-prev").click($.fancybox.prev);
			$(".navigator .gallery-next").click($.fancybox.next);
			$("#gallery-start").click();
		}
	});


};

SG.pageContent = {};

SG.pageContent.init = function() {
	$(window).bind('resize', function() {
		SG.pageContent.reposition();
	});
	SG.pageContent.initScroll(".text-cont", true);
	SG.makeUnselectable(document.getElementById("content-box"));
};

SG.pageContent.initScroll=function(selector, positionAndShow) {
	var offset = 10;
	var scrollerWrapperStart = "<div class='wrapper'><div class='scr'><div class='scrollable'>";
	var scrollerWrapperEnd = "</div></div></div>";
	var scrollerBar = "<div class='scroll-comp'><div class='scroll-up'>&nbsp;</div><div class='scrollbar'><div class='scroll-drag'></div></div><div class='scroll-down'>&nbsp;</div></div>";
	var content = $(selector).html();
	$(selector).html(scrollerWrapperStart + content + scrollerWrapperEnd + scrollerBar);

	/* position and show */
	if (positionAndShow) {
		var top = parseInt( ( $(window).height() - $("#content-box").height() ) / 2);
		var left = parseInt( ( $(window).width() - $("#content-box").width() ) / 2);
		$("#content-box").offset({ top: (top-50), left: left });
		$("#content-box").fadeIn();
	}

	var selectorHeight = $(selector).height();
	var scrollableHeight = $(selector + " .scrollable").height();

	if (scrollableHeight <= selectorHeight) {
		$(selector + " .scroll-comp").hide();
		return;
	}

	var scrollbarDragHeight = (selectorHeight/scrollableHeight)*selectorHeight;
	
	var realScrollbarDragHeight = ( $(selector + " .scrollbar").height() * scrollbarDragHeight ) / selectorHeight;
	
	$(selector + " .scroll-drag").height(realScrollbarDragHeight);

	$(selector + " .scr").addClass("with-scroll");
	$(selector + " .scrollbar").show();

	var scrollableHeight = $(selector + " .scrollable").height();
	var scrollbarHeight = $(selector + " .scrollbar").height() - $(selector + " .scroll-drag").height();
	
	var coeff = (scrollableHeight - realScrollbarDragHeight)/scrollbarHeight;
	
	$( selector + " .scroll-drag" ).draggable({
		containment: "parent",
		scroll: true,
		drag: function() {
			var newTop = ($(this).position().top * coeff);
			if (newTop < 0) newTop = newTop * (-1);
			$(selector + " .scrollable").css("margin-top", "-" + newTop + "px");
		}
	});
	$(selector + " .scroll-up").click(function() {
		var toTopScrollbar = $(selector + " .scroll-drag").position().top - offset;
		if (toTopScrollbar < 0)
			toTopScrollbar = 0;
		var toMarginTopContent = toTopScrollbar * coeff;
		$(selector + " .scroll-drag").stop().animate({ top: toTopScrollbar + "px" });
		if (toMarginTopContent<0) toMarginTopContent = toMarginTopContent*(-1);
		$(selector + " .scrollable").stop().animate({ marginTop: "-" + toMarginTopContent + "px" });
	});
	$(selector + " .scroll-down").click(function() {
		var toTopScrollbar = $(selector + " .scroll-drag").position().top + offset;
		if (toTopScrollbar + $(selector + " .scroll-drag").height() > $(selector + " .scrollbar").height() )
			toTopScrollbar = $(selector + " .scrollbar").height() - $(selector + " .scroll-drag").height();
		var toMarginTopContent = toTopScrollbar * coeff;
		$(selector + " .scroll-drag").stop().animate({ top: toTopScrollbar + "px" });
		if (toMarginTopContent<0) toMarginTopContent = toMarginTopContent*(-1);
		$(selector + " .scrollable").stop().animate({ marginTop: "-" + toMarginTopContent + "px" });
	});
	
	$(selector).bind('mousewheel', function(event, delta) {
		if (delta>0) {
			$(selector + " .scroll-up").click();
		}
		else {
			$(selector + " .scroll-down").click();
		}
	});
	$(document).keydown(function(event) {
		if (event.keyCode==38) {
			$(selector + " .scroll-up").click();
			return false;
		}
		else if (event.keyCode==40) {
			$(selector + " .scroll-down").click();
			return false;
		}
	});
};
SG.pageContent.reposition = function() {
	var top = parseInt( ( $(window).height() - $("#content-box").height() ) / 2);
	var left = parseInt( ( $(window).width() - $("#content-box").width() ) / 2);
	$("#content-box").offset({ top: (top-50), left: left });
};

SG.pageContent.openBoxContent=function(id, lang) {
	$.ajax({
		url: "action/getPageContentAjaxAction.php?id="+id+"&lang="+lang,
		type: "GET",
		dataType: "html",
		success: function(data) {
			$(".footer-field a").removeClass("active");
			$("#content-box").html(data);
			SG.pageContent.init();
			$("#link-" + id).addClass("active");
		},
		error: function() { alert("Error on SG.pageContent.openBoxContent " + id + ", " + lang); }
	});
};

SG.pageContent.closeBoxContent=function() {
	$(".footer-field a").removeClass("active");
	$("#content-box").fadeOut(300, function() {
		$("#content-box").html("");
		$("#content-box").attr("style", "");
	});
};

SG.makeUnselectable=function(node) {
	return false;
    if (node.nodeType == 1) {
        node.unselectable = true;
    }
    var child = node.firstChild;
    while (child) {
    	SG.makeUnselectable(child);
        child = child.nextSibling;
    }
};

/* Reseller Complex Accordion */
SG.reseller = {};
SG.reseller.init=function() {
	$("#level2").html("");
	$("#level2").removeClass("title");
	$("#level3").html("");
	$("#level3").removeClass("title");
	$("#level4").html("");

	$(".country-list li").unbind('click');
	$("#level2").unbind('click');
	$("#level3").unbind('click');

	// Get country list
	$.ajax({
		type: 'get',
		url: 'action/getResellerAjaxAction.php',
		data: { cmd: 'country' },
		success: function(data) {
			$("#level2").hide();

			$("#level2").html(data);
			$("#level2").slideDown();

			// Position and show content
			$(window).bind('resize', function() {
				SG.pageContent.reposition();
			});
			// Init scrollbar
			SG.pageContent.initScroll(".country-list", true);
			SG.makeUnselectable(document.getElementById("content-box"));

			// Handle click country events and call openCountry
			$(".country-list li").click(function() {
				$(".country-list li").unbind('click');
				SG.reseller.openCountry($(this).attr("rel"));
			});
			
		},
		error: function() {
			alert("Error get country list");
		}
	});
};


SG.reseller.openItaly=function() {
	$("#level3").html("");
	$("#level3").removeClass("title");
	$("#level4").html("");

	$(".region-list li").unbind('click');
	$("#level3").unbind('click');

	// Get country list
	$.ajax({
		type: 'get',
		url: 'action/getResellerAjaxAction.php',
		data: { cmd: 'region' },
		success: function(data) {

			/* Animation and show content*/
			$("#level2").slideUp(function() {
				$("#level2").html("Italia");
				$("#level2").addClass("title");
				$("#level2").append("<hr/>");

				$("#level2").slideDown(function() {

					$("#level3").html(data);
					$("#level3").slideDown();
				
					/* Init scrollbar */
					SG.pageContent.initScroll(".region-list", false);
	
					/* Handle click region events and call openRegion */
					$(".region-list li").click(function() {
						$(".region-list li").unbind('click');
						SG.reseller.openRegion($(this).attr("rel"));
					});
					
					/* Handler click on country name (return to country list) */
					$("#level2").click(function() {
						$("#level2").unbind('click');
						$("#level3").slideUp(function() {
							SG.reseller.openItaly();
						});
					});
				});
			});

		},
		error: function() {
			alert("Error get region list");
		}
	});
};
SG.reseller.openCountry=function(country) {
	if (country.toLowerCase() == "italia") {
		SG.reseller.openItaly();
		return;
	}
	
	/* Get ajax (html) reseller */
	$.ajax({
		type: 'get',
		url: 'action/getResellerAjaxAction.php',
		data: { cmd: 'reseller', param: country },
		success: function(data) {

			/* Animation and show content*/
			$("#level2").slideUp(function() {
				
				$("#level2").html(country);
				$("#level2").addClass("title");
				$("#level2").append("<hr/>");
				$("#level2").slideDown(function() {
					$("#level3").html(data);
					$("#level3").slideDown();

					/* Init scrollbar */
					SG.pageContent.initScroll(".reseller-list", false);
	
					/* Handler click on country name (return to country list) */
					$("#level0").click(function() {
						$("#level0").unbind('click');
						$("#level3").slideUp(function() {
							SG.reseller.init();
						});
					});
				});
			});
		},
		error: function() {
			alert("Error get reseller list");
		}
	});
	
};
SG.reseller.openRegion=function(region) {
	/* Get ajax (html) reseller */
	$.ajax({
		type: 'get',
		url: 'action/getResellerAjaxAction.php',
		data: { cmd: 'reseller-region', param: region },
		success: function(data) {
			/* Animation and show content*/
			$("#level3").slideUp(function() {
				$("#level3").html(region);
				$("#level3").addClass("title");
				$("#level3").append("<hr/>");
				$("#level3").slideDown(function() {
					$("#level4").hide();
					$("#level4").html(data);
					$("#level4").slideDown();
					
					/* Init scrollbar */
					SG.pageContent.initScroll(".reseller-list", false);

					/* Handler click on country name (return to country list) */
					$("#level2").click(function() {
						$("#level2").unbind('click');
						$("#level4").slideUp(function() {
							SG.reseller.openItaly();
						});
					});
				});
			});
		},
		error: function() {
			alert("Error get region reseller list");
		}
	});
};


SG.news = {};
SG.news.init=function() {
	SG.pageContent.initScroll("#news-list", true);
	
	$(".news-thumb .gal").click(function() {
		SG.menu.initGallery(this, $(this).attr("id"));
	});
	
};

(function($) {
	$.fn.inputLabel = function(params) {
		params = $.extend({
			labelValue: 'valore...',
			cssClass: 'input-label',
			textarea: false
		}, params);

		var inputId = $(this).attr('id');
		if (params.textarea){
			var inputLabel = $("<textarea>").attr('id', 'label-' + inputId).attr('value', params.labelValue).addClass(params.cssClass);
		}
		else {
			var inputLabel = $("<input>").attr('id', 'label-' + inputId).attr('value', params.labelValue).attr('type', 'text').addClass(params.cssClass);
		}
		$(this).after(inputLabel);
		
		$(this).bind('blur', function() { toggleLabel(false, inputId); } );
		$('#label-' + inputId).bind('focus', function() { toggleLabel(true, inputId); } );

		$(this).hide();

		toggleLabel = function(bool, id) {
			if ( (bool) || ( (!bool) &&  ($('#'+id).val()=='') ) ) {
				$("#label-"+id).toggle();
				$("#"+id).toggle();
				document.getElementById(id).focus();
			}
		};
		if ($("#"+inputId).val() != "") {
			$("#label-"+inputId).hide();
			$("#"+inputId).show();
		}
	};
	return this;
})(jQuery);


SG.contact = {};
SG.contact.submitForm=function(){
	if(!SG.contact.validateForm()) {
		$("#required-fields-dialog").dialog({ modal: true, resizable: false, draggable: false, height: 150 });
	}
	else if (!$('#privacy-accept').attr('checked')) {
		$("#check-privacy-dialog").dialog({ modal: true, resizable: false, draggable: false, height: 150 });
	}
	else {
		$('#contact-form').submit();
	}
};
SG.contact.validateForm=function(){
	if ( ($('#firstname').val()=="") ||
		($('#lastname').val()=="") ||
		($('#email').val()=="") ||
		($('#occupation').val()=="") ||
		($('#company').val()=="") ) {
		return false;
	}
	return true;
};
SG.contact.closeDialogPrivacy=function(){
	$("#check-privacy-dialog").dialog("close");
};
SG.contact.closeDialogReqField=function(){
	$("#required-fields-dialog").dialog("close");
};
SG.contact.closeDialogMailSent=function(){
	$("#mail-sent-dialog").dialog("close");
	location.href='area_riservata.html';
};
SG.contact.openDialogMailSent=function(){
	$("#mail-sent-dialog").dialog({ modal: true, resizable: false, draggable: false, height: 150 });
};



