// JavaScript Document
// array descrittivo dei codici restituiti dal server
// [la scelta dell'array è per evitare problemi con vecchi browsers]
var statusText = [];
statusText[100] = "Continue";
statusText[101] = "Switching Protocols";
statusText[200] = "OK";
statusText[201] = "Created";
statusText[202] = "Accepted";
statusText[203] = "Non-Authoritative Information";
statusText[204] = "No Content";
statusText[205] = "Reset Content";
statusText[206] = "Partial Content";
statusText[300] = "Multiple Choices";
statusText[301] = "Moved Permanently";
statusText[302] = "Found";
statusText[303] = "See Other";
statusText[304] = "Not Modified";
statusText[305] = "Use Proxy";
statusText[306] = "(unused, but reserved)";
statusText[307] = "Temporary Redirect";
statusText[400] = "Bad Request";
statusText[401] = "Unauthorized";
statusText[402] = "Payment Required";
statusText[403] = "Forbidden";
statusText[404] = "Page Not Found";
statusText[405] = "Method Not Allowed";
statusText[406] = "Not Acceptable";
statusText[407] = "Proxy Authentication Required";
statusText[408] = "Request Timeout";
statusText[409] = "Conflict";
statusText[410] = "Gone";
statusText[411] = "Length Required";
statusText[412] = "Precondition Failed";
statusText[413] = "Request Entity Too Large";
statusText[414] = "Request-URI Too Long";
statusText[415] = "Unsupported Media Type";
statusText[416] = "Requested Range Not Satisfiable";
statusText[417] = "Expectation Failed";
statusText[500] = "Internal Server Error";
statusText[501] = "Not Implemented";
statusText[502] = "Bad Gateway";
statusText[503] = "Service Unavailable";
statusText[504] = "Gateway Timeout";
statusText[505] = "HTTP Version Not Supported";
statusText[509] = "Bandwidth Limit Exceeded";

jQuery.ajaxSetup({
				 type: 'POST',
				 timeout: 30 * 1000,
				 dataType: 'html'
				 });

/* Prototype Ajax */
function setAjaxProto(url, type, fload, ferror, formId) {
	if (!url) return false;
	
	bindArgs = {};
	bindArgs.url = url;
	type = (type)?type.toUpperCase():"POST";
	bindArgs.type = type;
	if (fload) bindArgs.success = fload;
	if (ferror) bindArgs.error = ferror;
	if (formId) bindArgs.data = jQuery(isHash(formId)).serialize();
	return bindArgs;
}

function openLayer (html, options) {
	// DEFAULT SETTINGS
	options = jQuery.extend({
		overlayCss: null,
		containerCss: null,
		closeBtn: true,
		closeCss: null,
		closeFn: function () { closeLayer(); }
	}, options);

	var arrayPageSize = [parseInt(jQuery('body').width(), 10), parseInt(jQuery('body').height(), 10)];
	
	// OVERLAY
	var overlayHtml = '<div id="layerOverlay" class="layerOverlay" />';
	var objOverlay = jQuery('#layerOverlay');
	if (objOverlay.length === 0) {
		objOverlay = jQuery(overlayHtml);
		jQuery('body').prepend(objOverlay);
	}
	if (options.overlayCss) objOverlay.css(options.overlayCss);
	objOverlay.css({'top': '0px','left': '0px'});
	objOverlay.height(arrayPageSize[1]);
	objOverlay.width(arrayPageSize[0]);
	
	// CLOSE
	if (options.closeBtn) {
		var closeHtml = '<div id="layerClose" class="layerClose">CHIUDI</div>';
		var objClose = jQuery('#layerClose');
		if (objClose.length === 0) {
			objClose = jQuery(closeHtml);
			jQuery(objOverlay).prepend(objClose);
		}
		if (options.closeCss) objClose.css(options.closeCss);
		if (options.closeFn) objClose.click(options.closeFn);
	} else{
		jQuery('#layerClose').remove();
	}
	
	// DEBUG
	var debugHtml = '<div id="layerDebug" class="layerDebug" />';
	var objDebug = jQuery('#layerDebug');
	if (objDebug.length === 0) {
		objDebug = jQuery(debugHtml);
		//jQuery(objOverlay).prepend(objDebug);
	}

	// CONTAINER
	var containerHtml = '<div id="layerContainer" class="layerContainer" />';
	var objContainer = jQuery('#layerContainer');
	if (objContainer.length === 0) {
		objContainer = jQuery(containerHtml);
		jQuery(objOverlay).prepend(objContainer);
	}
	if (options.containerCss) objContainer.css(options.containerCss);
	
	if(typeof html == "String"){
		objContainer.html(html);
	} else{
		objContainer.append(html);
	}
		
	var w_src = objContainer.width();
	var h_src = objContainer.height();
		
	// SET WINDOW WIDTH AND HEIGHT
	if(arrayPageSize[0] < w_src || arrayPageSize[1] < h_src){
		var w_ratio = (arrayPageSize[0] != 0)? arrayPageSize[0] / w_src: 1;
		var h_ratio = (arrayPageSize[1] != 0)? arrayPageSize[1] / h_src: 1;
		if(h_ratio < w_ratio){
			var nw = (h_ratio <= 1)? parseInt(w_src * h_ratio, 10): parseInt(w_src, 10);
			var nh = (h_ratio <= 1)? arrayPageSize[1]: parseInt(h_src, 10);
		} else{
			var nh = (w_ratio <= 1)? parseInt(h_src * w_ratio, 10): parseInt(h_src, 10);
			var nw = (w_ratio <= 1)? arrayPageSize[0]: parseInt(w_src, 10);
		}
	} else{
		var nw = parseInt(w_src, 10);
		var nh = parseInt(h_src, 10);
	}

	objContainer.width(nw);
	objContainer.height(nh);
	
	var top = parseInt(((arrayPageSize[1] - nh) / 2), 10);
	objContainer.css('top', top + 'px');
	var left = parseInt(((arrayPageSize[0] - nw) / 2), 10);
	objContainer.css('left', left + 'px');
	
	objContainer.css('visibility', 'visible');
}

function closeLayer () {
	var objContainer = jQuery('#layerContainer');
	objContainer.empty();
	
	var objOverlay = jQuery('#layerOverlay');
	objOverlay.css({'top': '-2000px','left': '-2000px'});

	jQuery('#layerClose').remove();
}

function openIntro (options) {
	var arrayPageSize = [parseInt(jQuery('body').width(), 10), parseInt(jQuery('body').height(), 10)];
	
	var w_src = 920;
	var h_src = 730;

	// SET WINDOW WIDTH AND HEIGHT
	if(arrayPageSize[0] < w_src || arrayPageSize[1] < h_src){
		var w_ratio = (arrayPageSize[0] != 0)? arrayPageSize[0] / w_src: 1;
		var h_ratio = (arrayPageSize[1] != 0)? arrayPageSize[1] / h_src: 1;
		if(h_ratio < w_ratio){
			var nw = (h_ratio <= 1)? parseInt(w_src * h_ratio, 10): parseInt(w_src, 10);
			var nh = (h_ratio <= 1)? arrayPageSize[1]: parseInt(h_src, 10);
		} else{
			var nh = (w_ratio <= 1)? parseInt(h_src * w_ratio, 10): parseInt(h_src, 10);
			var nw = (w_ratio <= 1)? arrayPageSize[0]: parseInt(w_src, 10);
		}
	} else{
		var nw = parseInt(w_src, 10);
		var nh = parseInt(h_src, 10);
	}
	
	var html = '<div style="width: ' + nw + 'px; height: ' + nh + 'px; overflow: hidden;">' + 
		'<div id="introFlash" style="width: ' + nw + 'px; height: ' + nh + 'px; position: relative; left: 0px; top: 0px;">' + 
		'<div id="intro_n" />' + 
		'</div>' + 
		'</div>';
		
	openLayer(html, options);
	
	var flashvars = false;
	var params = {quality: 'high', allowScriptAccess: 'sameDomain', bgcolor: '#ffffff', wmode: 'transparent'};
	var attributes = {quality: 'high', allowScriptAccess: 'sameDomain', bgcolor: '#ffffff', wmode: 'transparent'};

	swfobject.embedSWF("intro/intro_n.swf", "intro_n", "100%", "100%", "9.0.0","js/expressInstall.swf", flashvars, params, attributes);
}

function closeIntro () {
	//jQuery('#introFlash').animate({'top': '-2000px'}, 1000);
	jQuery('#layerOverlay').fadeOut(1000, function() {
		closeLayer();
		jQuery('#layerOverlay').css({'opacity': '1'});
	});
}

function openSlide (url, options) {
	if (!url) return;
	
	var arrayPageSize = [parseInt(jQuery('body').width(), 10), parseInt(jQuery('body').height(), 10)];
	
	var w_src = arrayPageSize[0] * 3 / 4;
	var h_src = arrayPageSize[1] * 3 / 4;

	// SET WINDOW WIDTH AND HEIGHT
	if(arrayPageSize[0] < w_src || arrayPageSize[1] < h_src){
		var w_ratio = (arrayPageSize[0] != 0)? arrayPageSize[0] / w_src: 1;
		var h_ratio = (arrayPageSize[1] != 0)? arrayPageSize[1] / h_src: 1;
		if(h_ratio < w_ratio){
			var nw = (h_ratio <= 1)? parseInt(w_src * h_ratio, 10): parseInt(w_src, 10);
			var nh = (h_ratio <= 1)? arrayPageSize[1]: h_src;
		} else{
			var nh = (w_ratio <= 1)? parseInt(h_src * w_ratio, 10): h_src;
			var nw = (w_ratio <= 1)? arrayPageSize[0]: parseInt(w_src, 10);
		}
	} else{
		var nw = parseInt(w_src, 10);
		var nh = parseInt(h_src, 10);
	}

	var params = setAjaxProto(url, 'get', loadAjaxBox, errorAjaxBox, null);
	
	var req = jQuery.ajax(params);
	
    function loadAjaxBox(responseText, textStatus) {
		var html = '<div style="width: ' + nw + 'px; height: ' + nh + 'px; overflow: hidden;">' + responseText + '</div>';
		openLayer(html, options);
		myIst = new ImageFlow();
		myIst.init({
			ImageFlowID: 'fotoNardi',
			reflectPath: 'js/ImageFlow/',
			buttons: true,
			opacity: true,
			aspectRatio: nw / nh,
			imageCursor: 'pointer',
			onClick: function() {
				return hs.expand(this, { src: this.getAttribute('longdesc') } ); 
				} 
			});
    }
    
	function errorAjaxBox(XMLHttpRequest, textStatus, errorThrown) {					
		msg = "Impossibile effettuare l'operazione richiesta.\n";
		msg += "Errore riscontrato: " + statusText[XMLHttpRequest.status];
		alert(msg);
    }

	return false;
}

function initMainMenu () {
	var animateduration = {
		over: 300, 
		out: 300
	};
	
	var $mainmenu = jQuery("#btMenu ul"); // menu principale
	
	var $headers = $mainmenu.find("ul").parent(); // collezione degli LI con figlio UL
	
	$headers.each(function (i, dom) {
		var $curobj = jQuery(this); // this LI
		
		var $subul = jQuery(this).find('ul:eq(0)'); // UL sottomenu
		
		this._dimensions = { // dimensioni
					w: this.offsetWidth, 
					h: this.offsetHeight, 
					subulw: $subul.outerWidth(), 
					subulh: $subul.outerHeight()
				};
		
		this.istopheader = ($curobj.parents("ul").length == 1) ? true : false;
		
		$subul.css({
				bottom: (this.istopheader) ? this._dimensions.h + "px" : 0
			});
		
		$curobj.hover(
			function (e) {
				var $targetul = jQuery(this).children("ul:eq(0)");
					
				this._offsets = {
					left: jQuery(this).offset().left, 
					top: jQuery(this).offset().top
				};
				
				var menuleft = (this.istopheader) ? 0 : this._dimensions.w;
						
				menuleft = (this._offsets.left + menuleft + this._dimensions.subulw > jQuery(window).width()) ? ((this.istopheader) ? -this._dimensions.subulw + this._dimensions.w : -this._dimensions.w) : menuleft;
						
				if ($targetul.queue().length <= 1) { //if 1 or less queued animations
					$targetul.css({
								  left: menuleft + "px", 
								  width: this._dimensions.subulw + 'px'
							  }).delay(300).slideDown(animateduration.over);
				}
				
				jQuery(this).children("a:eq(0)").addClass('selected').children("img:eq(0)");
			},
			function (e) {
				var $targetul = jQuery(this).children("ul:eq(0)");
				$targetul.delay(300).slideUp(animateduration.out);
				
				jQuery(this).children("a:eq(0)").removeClass('selected').children("img:eq(0)");
			}
		) //end hover
	});
	
	jQuery("#btMenu").css({visibility: 'visible'});
	
	$mainmenu.find("ul").css({
						 display: 'none', 
						 visibility: 'visible'
					 });
}

function prodotti(id){
	if(!id) return;
	
	jQuery('#prodCont > div.selected').removeClass('selected').delay(300).animate({'top': '-500px'}, 'slow');
	
	if(id == 'introd')
		jQuery('#' + id).addClass('selected').delay(300).animate({'top': '0px'}, 'slow');
	else
		jQuery('#container-' + id).addClass('selected').delay(300).animate({'top': '0px'}, 'slow');

	return false;
}

function initChart () {
	var chart = jQuery.cookie('chart');
	var id, price;
	var tot = 0;
	
	if(chart){
		var items = chart.split('|');
		for(var i = 0; i < items.length; i++){
			var item = items[i].split(':');
			
			id = item[0];
			price = item[1];
			
			if (jQuery('#ideeForm input#' + id + ':checkbox')[0]) {
				jQuery('#ideeForm input#' + id + ':checkbox')[0].checked = true;
			} else if (jQuery('#ideeForm select#' + id)[0]) {
				jQuery('#ideeForm select#' + id).val(price);
			}
			
			tot += parseInt(price);
			
		}
	} else{
		jQuery.cookie('chart', '');	
	}
	
	jQuery('#totVoucher').html(tot + ',00');
}

function calcTot(){
	var tot = 0;
	var cookie = '';
	
	jQuery('#ideeForm input.required:checked').each(function () {
		cookie += this.id + ':' + jQuery(this).val() + '|';
		tot += parseInt(jQuery(this).val(), 10);
	});
	jQuery('#ideeForm select.required').each(function () {
		if(jQuery(this).val() > 0)
			cookie += this.id + ':' + jQuery(this).val() + '|';
		tot += parseInt(jQuery(this).val(), 10);
	});
	
	cookie = cookie.substring(0, cookie.length - 1);
	jQuery.cookie('chart', cookie);
	
	jQuery('#totVoucher').html(tot + ',00');
}

function checkChart(){
	var some = 0;
	
	jQuery('#ideeForm input.required:checked').each(function () {
		some++;
	});
	jQuery('#ideeForm select.required').each(function () {
		if(jQuery(this).val() > 0)
			some++;
	});
	
	if(some == 0){
		alert('Nessun prodotto selezionato!');
		return false;	
	}
	
	return true;
}

function checkData(frm){
	if(!jQuery(frm).checkForm()) return false;
	
	jQuery('input:text', frm).each(function () {
		jQuery.cookie(jQuery(this).attr('name'), jQuery(this).val());
	});
	
	return true;
}
