/*
 * caricamento del flash home
 */
function loadFlashHome() {
	var flashvars = {
		num_img: 7
	  , img1   : "/skin/website/img/foster_home01.jpg"
	  , img2   : "/skin/website/img/foster_home02.jpg"
	  , img3   : "/skin/website/img/foster_home03.jpg"
	  , img4   : "/skin/website/img/foster_home04.jpg"
	  , img5   : "/skin/website/img/foster_home05.jpg"
	  , img6   : "/skin/website/img/foster_home06.jpg"
	  , img7   : "/skin/website/img/foster_home07.jpg"
	  , testo  : ""
	  , x      : 10
	  , y      : 10
	};
	var params = {
		scale: "noscale"
	};
	var attributes = {};

	swfobject.embedSWF("/skin/website/swf/slideShow.swf", "flash", "555", "409", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}
function loadFlashInterna(flash) {
	var lang = $('.language_list .selected a').text()
	  , lang = lang.toLowerCase()
		;
	var flashvars = {
			dominio: "http://"+document.domain+"/",
			lang: lang,
			xmlpath: "history_data/"
		};
	var params = {
		scale: "noscale",
		wmode: "transparent"
	};
	var attributes = {};

	swfobject.embedSWF("/skin/website/swf/" + flash, "flashInterna", "780", "330", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}

function loadConfiguratore(flash) {
	var dominio = $('#flashConfigurator').attr('class');
	var lang = $('#flashConfigurator').attr('lang');
	var flashvars = {
		dominio: dominio + '/',
		config: "top-inox.php" + '?lang=' + lang
	};
	var params = {
		scale: "noscale"
	};
	var attributes = {};

	swfobject.embedSWF("/skin/website/swf/configuratore.swf", "flashConfigurator", "800", "600", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}
/*function scrollWin(){
	$('html, body').animate({
		scrollTop: $("#scrollToHere").offset().top
	}, 2000);
}*/

/*
 * Dimensiona e posiziona la page, la colonna a sx e la banda grigia (sfondi)
 */
function positionCols() {
	var posPage = $('.page').offset();	
	var posArea = $('#areaRiservata').offset();
	$('.page').css('height', $(document).height());	
	if ($('.mainFasciaSx').length > 0) {
		$('.mainFasciaSx').css('top', posArea.top);
		$('.mainFasciaSx').css('width', posPage.left);
	}
	if ($('.mainColSx').length > 0) {
		$('.mainColSx').css('width', posPage.left+1);
		$('.mainColSx').css('height', $(document).height());
	}	
	if ($('.mainImage').length > 0) {
		var imgLeft = 632 + posPage.left;
		var imgWidth = Math.round($('body').width() - imgLeft);
		$('.mainImage').css('width', imgWidth);
		$('.mainImage').css('left', imgLeft);
	}
}

function doveTroviRegione(tipo, tipologia, stato)
{
	$.ajax({
		  url: '/return/regprov?tipo=' + tipo + '&tipologia=' + tipologia + '&stato=' + escape(stato)
		, async: false
		, success: function(html) {
				$('div.graphicSelect.dependsOnCountry .listOptions ul').empty();
				var noResults = (html.indexOf('noResults') > 0);
				var lang = $('#searchLang').attr("value");
				if (noResults) {
					$('.dependsOnCountry').hide();
					listaPuntiVendita(tipo, tipologia, stato, '', lang);
				} else {
					$('.dependsOnCountry').show();
					$('div.graphicSelect.dependsOnCountry .listOptions ul').append(html);
					$('div.graphicSelect.dependsOnCountry input#dependsOnCountry_view').val("- Seleziona -");
				}
				// Ricrea hover li options
				recreatesHoverListOptions();
		}
	});
}

function listaPuntiVendita(tipo, tipologia, stato, reg, lang)
{
	$.ajax({
		  url: '/return/puntivendita?tipo=' + tipo + '&tipologia=' + escape(tipologia) + '&stato=' + escape(stato) + '&reg=' + escape(reg) + '&lang=' + escape(lang)
		, async: false
		, success: function(html) {
			$('.listaPuntiVendita').empty();
			$('.listaPuntiVendita').append(html);
		}
	});
}

/*
 * Validazione form
 */
(function($) {
	$.fn.validation = function(pos) {
		var error    = 0;
		var position = pos;
			
		$('.mandatory', this).each(function() {
			var input = $(':input', this).attr("value");
			var check = $(':checkbox:checked', this).length;
			if (input == "" || ($(':checkbox:checked', this).length == 0 && input == "Y")) {
				$(this).css('font-weight', 'bold');
				if (pos == false) {
					$('p.errorMessage', this).remove();
					$(this).append('<p class="errorMessage"><span class="error"></span></p>');
					$('span.error', this).html('Please fill in this field.');
					$(':input', this).addClass("errorHighlight");
					error++;
				} else {
					$(':input', this).attr("value", 'Fill in this field');
					$(':input', this).addClass("errorHighlight");
					error++;
				}
			} else {
				$(this).css('font-weight', 'normal');
				if (pos == false) {
					$('p.errorMessage', this).remove();
					$(':input', this).removeClass("errorHighlight");
				} else {
					//$(':input', this).attr("value", input);
					$(':input', this).removeClass("errorHighlight");
				}
			}
		});
		
		if (error == 0) {
			return true;
		} else {
			return false;
		}
	};
})(jQuery);

/*
 * Paginazione lista
 */
(function($) {
	$.fn.paginator = function(ne) {

		$.each($(this), function (k,v) {

			var mainList        = $(this)
			  , nElementsInPage = (ne === undefined ? 4 : ne)
			  , totElements     = $('li', mainList).length
			  , totPages        = Math.ceil(totElements / nElementsInPage) - 1
			  , listPages       = ''
			  , currPage        = 0
			  ;	

			function showElements(el, currPage, nElementsInPage) {
				var showFirst = currPage * nElementsInPage;
				var showLast  = Math.min(showFirst+nElementsInPage, totElements);
				$('li', el).hide();
				// lazy loading delle immagini
				$('li img', el).slice(showFirst, showLast).each(function(){
					var title = $(this).attr('title');
					if (title) {
						$(this).attr('src', title);
						$(this).removeAttr('title');
					}
				});
				$('li', el).slice(showFirst, showLast).fadeIn();
			}


			showElements(mainList, currPage, nElementsInPage);

			if (totPages > 0) {

				for (i=0;i<=totPages;i++) {
					listPages += '<li class="pag' + i + (currPage == i ? " cur" : "") + '"><a href="' + i + '" title="pag ' + (i+1) + '">' + (i+1) + '</a></li>';
				}
				var html = '<div class="pages">'
					 + '<ul>' + listPages + '</ul>'
					 + '</div>'
					 ;
				mainList.after(html);
				

				var pagination = mainList.next('.pages');
				var parWidth = pagination.width();
				var ulWidth  = $('ul', pagination).width();
				var leftUl   = (parWidth - ulWidth) / 2;

				$('ul', pagination).css('left', leftUl + 'px');

				$('ul li a', pagination).bind('click', function() {
					currPage = $(this).attr('href');
					cur =      $(this).attr('href');
					
					// Per ie7 vado a togliere il dominio davanti all'href in quanto
					// al posto di recuperare solo il valore, recupera l'intero url
					// Es: http://fosterspa.intesys.net/Prodotti/rm/Lavelli/2 invece che 2
					posLastSlash = strrpos(currPage, '/');			
					currPage = parseInt(currPage.substring(posLastSlash + 1, currPage.length));
					posLastSlash = strrpos(cur, '/');				
					cur = parseInt(cur.substring(posLastSlash + 1, cur.length));
					
					showElements(mainList, currPage, nElementsInPage);
					$('ul li', pagination).removeClass('cur');
					$('ul li.pag'+cur, pagination).addClass('cur');
					return false;
				});
			}
		});

	};
})(jQuery);


function strrpos (haystack, needle, offset) {
    // Finds position of last occurrence of a string within another string  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/strrpos    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   input by: saulius
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strrpos('Kevin van Zonneveld', 'e');    // *     returns 1: 16
    // *     example 2: strrpos('somepage.com', '.', false);
    // *     returns 2: 8
    // *     example 3: strrpos('baa', 'a', 3);
    // *     returns 3: false    // *     example 4: strrpos('baa', 'a', 2);
    // *     returns 4: 2
    var i = -1;
    if (offset) {
        i = (haystack+'').slice(offset).lastIndexOf(needle); // strrpos' offset indicates starting point of range till end,        // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning
        if (i !== -1) {
            i += offset;
        }
    }    else {
        i = (haystack+'').lastIndexOf(needle);
    }
    return i >= 0 ? i : -1;
}


// TEST
//$(document).ready(function() {
//console.profile();
//console.profileEnd();
//});
// END TEST

$(document).ready(function() {

	if ($('ul.prodotti').length > 0) {
		$('ul.prodotti').paginator();
	}

	if ($('#flash').length > 0) {
		loadFlashHome();
	}
	if ($('#flashInterna').length > 0) {
		var flash = $('#flashInterna').attr('title');
		if (flash == 'history.swf') { loadFlashInterna(flash); }
	}
	if ($('#flashConfigurator').length > 0) {
		var flash = $('#flashConfigurator').attr('title');
		if (flash == 'configuratore.swf') { loadConfiguratore(flash); }
	}

	if ($("a.fancybox-me").length > 0) {
		$("a.fancybox-me").fancybox({
				'overlayShow':    true
			  , 'overlayOpacity': 0.5
		});
	}
	if ($("a.fancybox-me-YT").length > 0) {
		$("a.fancybox-me-YT").fancybox({
				'overlayShow':    true
			  , 'overlayOpacity': 0.5
			  , 'frameWidth' : '640'
			  , 'frameHeight' : '390'
		});
	}
	
	$('.newWin').click(function (e) {
		/*var url = $(this).attr('href');
		window.open(url, "", "width=1000,height=800");
		return false;*/
		this.target = "_blank";
    });
	/*
	if ($('a.newWin').length > 0) {
		$('a.newWin').popup();
	}
	*/
	// gestione ombra su contentSpace
	if (jQuery.support.leadingWhitespace) {
		var cs = $('.maxwidth .contentSpace');
		if (cs.hasClass('isList') == false){
			cs.css('background-image', 'none');
			var cssObj = {
							'position'   : 'absolute'
						  , 'top'        : '0'
						  , 'left'       : '0'
						  , 'width'      : '20px'
						  , 'height'     : '470px'
						  //, 'background' : 'url(/skin/website/widgets/bg_content.png) no-repeat top left'
						  , 'z-index'    : '1000'
							}
			cs.prepend('<div class="ombretta"></div>');
			$('.ombretta').css(cssObj);
		}
	}

	$('#link_configuratore').click(function () {
		$('#flashcontent').fadeIn();
		return false;
    });
	
	$('.openConfigurator').click(function () {
		window.open("/configuratore.php", "", "width=840,height=640");
		return false;
    });

	// validazione form accesso area riservata
	$("#areaRiservata").submit(function () {
		//$(this).validation(false);
		//return false;
		return $(this).validation(false);
	});
	
	// validazione form ricerca
	$("#searchForm").submit(function () {
		//$(this).validation(true);
		//return false;
		return $(this).validation(true);
	});
	
	// validazione form contatti
	$("#fContatti").submit(function () {
		//$(this).validation(false);
		//return false;
		return $(this).validation(false);
	});
	
	/* gestione menu carattere/stampa */
	if ($('.char_print').length > 0) {
		var original = $('.contentSpace .testo p').css('font-size');		
		$('.char_print li').click(function() {
			var action = $(this).attr('class');
			if (action == 'small') {
				var cssObj = {'font-size' : '9px'}
      			$('.testo p').css(cssObj);
				//$('.contentSpace .testo').css('font-size': '9');
			} else if (action == 'medium') {
				var cssObj = {'font-size' : original}
      			$('.testo p').css(cssObj);
			} else if (action == 'large') {
				var cssObj = {'font-size' : '14px'}
      			$('.testo p').css(cssObj);
			} else if (action == 'print') {
				window.print();
			}
			return false;
		});
	}

	/* Gestione menu III livello */
	if ($('.menuI ul.level3 li').length > 0) {
		$('.content').attr('class', 'content thirdLevel')
		$(".contentSpace").after('<div class="menuIII"></div>');
		//$(".contentSpace").css('background', 'url(/skin/website/widgets/bg_content.gif) no-repeat top left');

		var lev2 = $('.menuI ul.level3').html();
		$('.menuI ul.level3').appendTo(".menuIII");
		if ($('li.level2.open').length > 0) {
			$('ul.level3').css('top', $('li.level2.open').offset().top - $('.header').height());
		} else {
			$('ul.level3').css('top', ($('ul.level1').offset().top - $('.header').height()) + 5);
		}
	}
	if ($('.menuCategorie').length > 0) {
		if ($('li.level2.open').length > 0) {
			$('ul.level3').css('top', $('li.level2.open').offset().top - $('.header').height());
		} else {
			$('ul.level3').css('top', ($('ul.level1').offset().top - $('.header').height()) + 5);
		}
	}

	// movimento FAQ
	$("a.faq").click(function () {
		var gotos = $(this).attr('href');
		gotos = gotos.substring(1);
		$('html, body').animate({
			scrollTop: $('a[name$='+gotos+']').offset().top
		}, 1000);
		return false;
	});
	
	// movimento TOP page
	$(".top a").click(function () {
		$('html, body').animate({scrollTop: 0}, 500);
		return false;
	});
	
	/*if ($('.language_list').length > 0) {
		var widthLanguageList = $('.language_list').width();
		var left = '-' + (widthLanguageList + 13) + 'px';
		var lang = $('.language_list li[class=selected]').attr('title');

		$('.currentLang').text(lang);
		$('.language_list').animate({'left': '0'}, 1000)
						   .animate({'left': left}, 2000)
						   ;
		$('.language_list').hover(								   
			function () {
				$(this).stop().animate({'left': '0'}, 500);
			}, 
			function () {
				$(this).stop().animate({'left': left}, 2000);
			}
		);
	}*/
	
	/* IMG Novità prodotti */
	if ($('#slider1').length > 0) {
		$('#slider1').s3Slider({
			timeOut: 4000 
		});
	}
	
	// form mask
	if ($('.codice_prodotto_libretto').length > 0) {
		$.mask.definitions['~']='[+-]';
		$("#codice_prodotto").mask("9999 999",{placeholder:"_"});
		//$("#codice_prodotto").mask("*@*.*",{placeholder:"_"});
	}
	if ($('.infiniteCarousel').length > 0) {
		$('.infiniteCarousel').paginator(3);
	}

	if ($('.rsText').length > 0) {
		var infCarOffset = $('.testo.ricerca.stile').offset();
		//var infCarHeight = $('.testo.ricerca.stile li img').height();
		var img1 = $('.testo.ricerca.stile li.col1');
		var img2 = $('.testo.ricerca.stile li.col2');
		var img3 = $('.testo.ricerca.stile li.col3');
		var txt1 = $('.rsText.col1');
		var txt2 = $('.rsText.col2');
		var txt3 = $('.rsText.col3');
		var img1Offset = img1.offset();
		var img2Offset = img2.offset();
		var img3Offset = img3.offset();
		var cssObj = {
			  'position' : 'absolute'
			, 'top' : '150px'
			, 'width' : '187px'
			, 'height' : '290px'
			//, 'left' : '0'
			, 'float' : 'none'
			, 'margin' : '0'
			, 'padding' : '0'
		}
		//txt1.before('.testo.ricerca.stile');
		txt1.before('&nbsp;');
		txt1.css(cssObj);
		txt1.css('left', '5px');
		//txt2.before('.testo.ricerca.stile');
		txt2.before('&nbsp;');
		txt2.css(cssObj);
		txt2.css('left', '203px');
		//txt3.before('.testo.ricerca.stile');
		txt3.before('&nbsp;');
		txt3.css(cssObj);
		txt3.css('left', '401px');
	}
	
	// Filtro ricerca prodotto	
	$('#fRicercaModello select:odd').css('float', 'right');
	$('#fRicercaModello :selected').each(function(i, selected){
		if ($(selected).attr('value') != '') {
			var cssObj = {
				  'background-color' : '#f1f1f2'
				, 'border' : 'solid 1px #ccc'
				, 'font-weight' : 'bold'
			}
			$(selected).parent().css(cssObj);
		}
	});
	
	/*if ($('a.lightbox').length > 0) {
		$('a.lightbox').lightbox();
	}*/
	/*if ($('.arrow').length > 0) {
		$('.arrow').mouseover(function () {
			$(this).css('background-color', '#666');
		});
	}*/
	
	//$(".mySelect").styleSelect({styleClass: "fosterStyle"});
	
	positionCols();

	if ($('a.downloadThis').length > 0) {
		var url = $('a.downloadThis').attr('href');
		//window.setTimeout("download('"+url+"')", 500);
		setTimeout("location.href = '"+url+"'",500);
	}
	
	/*if ($('.back2prev').length > 0) {
		//$('.back2prev').each(function(){
			$('.back2prev').click(function () {
				history.back();
				return false;
			});
		//});
	}*/

	$("div.graphicSelect.listaStati ul li").click(function() {
		//Reset div 
		$("div.graphicSelect.dependsOnCountry input").attr("value","");
		$('.listaPuntiVendita').empty();
		
		var tipo = $('#searchOnTipo').attr("value");
		var tipologia = $('#searchOnTipologia').attr("value");
		var lang = $('#searchLang').attr("value");
		var stato = $(this).attr('rel');		
		doveTroviRegione(tipo, tipologia, stato);
		
		$("div.graphicSelect.dependsOnCountry ul li").click(function() {
			var prov = $(this).attr('rel');
			listaPuntiVendita(tipo, tipologia, stato, prov, lang);
		});		
	});
});

$(window).load(function() {
	$(window).resize(function() {
		positionCols();
	});
});

/*
 * Variabile utilizzata per riconoscere se sono nel dettaglio di un punto vendita o meno
 * false - non sono nel dettaglio
 * true  - sono nel dettaglio
 */
var detail = false;

/*
 * Visualizzo informazioni web per il punto vendita selezionato
 */
function getWebInformation(idPuntoVendita) {
	
	//Se siamo nel dettaglio disabilito il link presente nel testo della ragione sociale del punto vendita
	if (detail) { 
		return ;
	}
	
	var idPuntoVendita = parseInt(idPuntoVendita);
	var count = 1;
	var totalePuntiVendita = parseInt($("span.numBox").html()); 
	var imgPuntoVendita = $("#box"+idPuntoVendita+" span.imgPuntoVendita").html();

	//Nascondo il form di scelta nazione/provincia
	//$("#fDoveTrovi").css('display', 'none');
	$("#fDoveTrovi").slideToggle();
	
	//Nascondo tutti gli altri punti di vendita escludendo quello cliccato
	for(count; count<=totalePuntiVendita; count++ ) {
		if(count!=idPuntoVendita) { 
			//$("#box"+count).css('display', 'none');
			$("#box"+count).slideToggle();
		}
	}
	
	//Visualizzo il div contenente il testo del punto vendita selezionato
	//$("div.listaPuntiVendita li#box"+idPuntoVendita+" .informazioniWebPuntoVendita").css('display', 'block');
	$("div.listaPuntiVendita li#box"+idPuntoVendita+" .informazioniWebPuntoVendita").slideToggle();
	
	//Visualizzo il div contenente l'immagine del punto vendita selezionato
	if(imgPuntoVendita!=null)
		$("div.mainImage").css('background', 'url('+imgPuntoVendita+') no-repeat left top');
	else
		$("div.mainImage").css('background', 'url(/skin/website/img/bg_dovetrovifoster_default.jpg) no-repeat left top');
	
	//Visualizzo il pulsante per tornare alla lista di punti vendita
	//$(".returnToStoreList").css('display', 'block');
	$(".returnToStoreList").slideToggle();
	
	//Setto la variabile per indicare che sono nel dettaglio di un punto vendita
	detail = true;
}

/*
 * Ritorna alla lista di punti vendita
 */
function returnToStoreList() {
	var count = 1;
	var totalePuntiVendita = parseInt($("span.numBox").html()); 
	
	//Visualizzo il form di scelta nazione/provincia
	//$("#fDoveTrovi").css('display', 'block');
	$("#fDoveTrovi").slideDown();
	
	//Visualizzo tutti gli i punti di vendita
	for(count; count<=totalePuntiVendita; count++ ) {
		//$("#box"+count).css('display', 'block');
		$("#box"+count).slideDown();
		//Nascondo il testo e l'immagine per il web di ogni punto vendita
		//$("#box"+count+" .informazioniWebPuntoVendita").css('display', 'none');
		$("#box"+count+" .informazioniWebPuntoVendita").slideUp();
		//$("#box"+count+" .immagineWebPuntoVendita").css('display', 'none');
		$("div.mainImage").css('background', 'none');
	}
	
	//Nascondo il pulsante per tornare alla lista di punti vendita
	$(".returnToStoreList").css('display', 'none');
	
	//Ripristino la variabile per indicare che non sono più nel dettaglio di un punto vendita
	detail = false;
}

