// VARS DECLARATION
	var siteRoot = 'http://www.leoburnett.it/';
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	var debugActive = false;
	var objD = new Object();
	var content = new Object();
	var orig_content = new Object();
	var contentWG = '';
	var boxesSlide = 0;
	var contentW = '';
	var disableButton = false;
	var currentPage = 1;
	var totPages = 0;
	var searchCont = '';
	var historySelected='';
	var historyTab= 1;
	var contentH = '';
	var headerH = '';
	var totElements = 0;
	var windowH = $(window).height();
	var windowW = $(window).width();
	var historyItems=0;
	if (typeof(key) != 'undefined') { var searchString = key; } else { var searchString=''; }
	var sezArray = { "who-we-are":"CHI SIAMO", "approach":"APPROCCIO", "portfolio":"PORTFOLIO", "news":"NEWS" };
	var subSezArray = { "our-history":"LA STORIA", "burnetters":"BURNETTER", "our-network":"GRUPPO LEO BURNETT ITALIA", "our-brands":"I NOSTRI CLIENTI","humankind":"HUMANKIND", "gpc-scale":"GPC", "leo-quotes":"PARLA CON LEO","case":"CASE HISTORY","projects":"PROGETTI","evergreen":"EVERGREEN","awards":"PREMI","press-release":"PRESS RELEASE","big-pencils":"BIG PENCILS" };

$(document).ready(function(){
	
	if(navigator.appName!= "Mozilla"){document.onkeyup=capturekey}
else{document.addEventListener("keypress",capturekey,true);}
	
	function capturekey(e){
	var key=(typeof event!='undefined')?window.event.keyCode:e.keyCode;
		if (key == '39') {
			if ($("#next").css('display') == 'block') {
				nextPage();
			}
		}
		
		if (key == '37') {
			if ($("#prew").css('display') == 'block') {
				prevPage();
			}
		}
	}
	
	//ROLLOVER
	if (!isiPad) {
	if (subSez!='our-brands') {
		$('.boxes[data-overlayer="1"]').live('hover', function() {
			$(this).children('.rollover').slideToggle();
		});
		$('.boxes[data-overlayer="2"]').live('hover', function() {
			$(this).children('.rollover').slideToggle();
		});
	}
	}
	
	// resolution adjustment
		$("#homeCont").click(function() { document.location.href='/'; });
		$("#logo").click(function() { document.location.href='/'; });
		var containeH =$('#container').height();
		var containeW =$('#container').width();
		headerH = $('#header').outerHeight();
		var headerW = $('#header').width();
		var footerH = $('#footer').outerHeight();
		var footerW = $('#footer').width();
		contentH = (windowH - headerH - footerH);
		var detailsH = (windowH - 84);
		contentW = $('#content').width();
		if (isiPad && sez!='home') {
			$('#mask').css('width', (contentW-59) + 'px');
		}
		contentWG = contentW;
		boxesSlide = (contentWG /2);
		$("#content").css('height', windowH);
		$("#contentScroll").css('height', windowH);
		$(".details").css('height', detailsH);
		/*ghost mod the follow elements overflow the viewport*/
		
		$("#leftMenu").css('height', detailsH + 30);
		$("#leftMenuContent").css('height', detailsH + 30);
		$("#leftMenuBG").css('height', detailsH + 30);
		//$("#leftMenuContent").css('height','550px');
		//$("#leftMenuBG").css({'height':'550px','position':'absolute'});
		//$("#leftMenu").css('height','550px');
		//$("#content").css('height','550px');
		$("#container").css('height', windowH);
		objD = {A:windowH,B:windowW,C:containeH,D:containeW,E:headerH,F:headerW,G:footerH,H:footerW,I:contentH,L:contentW};
	
	// FIRST DB CALL TO FILL THE CONTENTS
		function getJson(pencilPosition){
			if (sez=='home') {
				var defSez = '';
			} else {
				defSez = sez; 
			}
			$.getJSON(siteRoot + "fill.php?s=" + searchString + "&p=" +pencilPosition + "&x=" + contentW + "&y=" + contentH + "&h=" + headerH + '&sez=' + defSez + '&subSez=' + subSez, function(data) {
				totPages = data.totPages;
				content = data.blocks;
				orig_content = data.blocks;
				$('#contentScroll').empty();
				fillContent(orig_content);
			})
			.success(function() {
				calculate();
				if (isIOS) { main(totElements); }
			});
		};
	
	
	$("#next").click(function() {
		nextPage();
	});
	
	$("#prew").click(function() {
		prevPage();
	});
	
	var _event = 'click';

	// BOXES CLICK
		$('.boxes[data-overlayer="1"]').live(_event, function() {
			_gaq.push(['_trackPageview', '/' + $(this).attr('data-sez') + '/' + $(this).attr('data-subsez') + '/' + $(this).attr('data-title')]);
			if (subSez=='our-history' || $(this).attr('data-subsez') == 'our-history' || subSez=='gpc-scale' || $(this).attr('data-subsez') == 'gpc-scale' || subSez=='humankind' || $(this).attr('data-subsez') == 'humankind') {
				historyLoad($(this).attr('data-id'), $(this).attr('data-subsez'));
			} else {
				if ($(this).attr('data-subsez') == 'our-network') {
					ourNetworkLoad($(this).attr('data-id'));
				} else {
					if ($(this).attr('data-subsez') == 'burnetters') {
						burnettersLoad($(this).attr('data-id'));
					} else {
						if ($(this).attr('data-subsez') == 'leo-quotes' || ($(this).attr('data-subsez') == '' && $(this).attr('data-sez') == 'approach')) {
							leoquotes($(this).attr('data-id'));
						} else {
							if ($(this).attr('data-subsez') != 'our-brands') {
								hpItems($(this).attr('data-id'), $(this).attr('data-subsez'));
							}
						}
					}
				}
			}
		});
	
	// OUTGOING LINKS
		$('.boxes[data-overlayer="2"]').live(_event, function() {
			window.open($(this).attr('data-link'));
		});

	// TEMPLATE LOADING FUNCTIONS
		// ourNetworkLoad
		function ourNetworkLoad(id) {
			$('#overlay').load('/template/our-network.html #ch', function() {
				$.getJSON(siteRoot + "overlayDetails.php?sez=our-network&hid=" + id, function(data) {
					var history = data.blocks;
					var lastId = '';
					for (i=0;i<history.length;i++){
						if (i==0) {
							$("#first").clone().insertAfter("#first").attr('id', history[i].id);
						} else {
							$("#" + lastId).clone().insertAfter("#" + lastId).attr('id', history[i].id);
						}
						lastId = history[i].id;
						$('#' + history[i].id + ' h2').html(history[i].main_title);
						$('#' + history[i].id + ' .textScroll').html(history[i].text + '<br clear="all" /><div class="divider"></div>');
						$(".detailsRight").css('width', 410);
						$(".detailsRight").css('padding-right', 20);
						$(".textScroll").css('width', 390);
						$(".textScroll").css('padding', 10);
						$(".textScroll").css('height', detailsH - 160);
						$('#' + history[i].id).css('background' ,'url(/images/contents/pic/' + history[i].id + '.jpg) no-repeat');
						if (sez=='home' || subSez=='') {
							$('.detailsBottomLeft').html('<i>&gt;&gt; <a href="' + siteRoot + history[i].sez + '/' + history[i].subSez + '/">SCOPRI ' + subSezArray[history[i].subSez] + '</a></i>');
						} else {
							if (history[i].link != '') {
								$('.detailsBottomLeft').html('&gt;&gt; <i>website</i> : <a href="http://' + history[i].link + '">' + history[i].link + '</a>');
							} else {
								$('.detailsBottomLeft').remove();
							}
						}
						
					}
					$('#first').remove();
				})
				.success(function() {
					$(".details").fadeIn(function() {
						$(this).addClass('open');
						fleXenv.initByClass("textScroll");
					});
				});
			});
		}
		
		// burnettersLoad
		function burnettersLoad(id) {
			$('#overlay').load('/template/burnetters.html #ch', function() {
				$.getJSON(siteRoot + "overlayDetails.php?sez=burnetters&hid=" + id, function(data) {
					var history = data.blocks;
					var lastId = '';
					for (i=0;i<history.length;i++){
						if (i==0) {
							$("#first").clone().insertAfter("#first").attr('id', history[i].id);
						} else {
							$("#" + lastId).clone().insertAfter("#" + lastId).attr('id', history[i].id);
						}
						lastId = history[i].id;
						$('#' + history[i].id + ' h2').html(history[i].main_title + ' - <span class="unactive">' + history[i].subtitle + '</span>');
						$('#' + history[i].id + ' .textScroll').html('<hr /><span style="font-size:28px">' + history[i].text.substr(0,1) + '</span>' + history[i].text.substr(1,history[i].text.length) + '<hr />');
						$('#' + history[i].id).css('background' ,'url(/images/contents/pic/' + history[i].id + '.jpg) no-repeat');
						$('#' + history[i].id).css('background-position' ,'0px 21px');
						if (sez=='home' || subSez=='') {
							$('.detailsBottomLeft').html('<i>&gt;&gt; <a href="' + siteRoot + history[i].sez + '/' + history[i].subSez + '/">SCOPRI I ' + subSezArray[history[i].subSez] + '</a></i>');
						} else {
							if (history[i].link != '') {
								$('.detailsBottomLeft').html('&gt;&gt; <i>website</i> : <a href="http://' + history[i].link + '">' + history[i].link + '</a>');
							} else {
								$('.detailsBottomLeft').remove();
							}
						}
						
					}
					$('#first').remove();
				})
				.success(function() {
					$(".details").fadeIn(function() {
						$(this).addClass('open');
					});
				});
			});
		}
		
		// historyLoad
		function historyLoad(id, ssez) {
			$('#overlay').load('/template/history.html #ch', function() {
				if (subSez=='our-history' || subSez == 'gpc-scale' || subSez == 'humankind') {
					var url = siteRoot + "overlayDetails.php?sez=" + ssez;
				} else {
					var url = siteRoot + "overlayDetails.php?sez=" + ssez + "&hid=" + id;
				}
				$.getJSON(url, function(data) {
					var history = data.blocks;
					var lastId = '';
					for (i=0;i<history.length;i++){
						if (i==0) {
							$("#first").clone().insertAfter("#first").attr('id', history[i].id);
						} else {
							$("#" + lastId).clone().insertAfter("#" + lastId).attr('id', history[i].id);
						}
						lastId = history[i].id;
						$('#' + history[i].id + ' h2').html(history[i].main_title);
						$('#' + history[i].id).css('background' ,'url(/images/contents/pic/' + history[i].id + '.jpg) no-repeat');
						if (subSez=='our-history' || subSez=='gpc-scale' || subSez == 'humankind') {
							$('.detailsBottomLeft ul').append('<li id="lsthistory' + history[i].id + '" class="unactive">' + history[i].rolloverTitle + '</li>');
						}
						if (ssez=='our-history') {
							$('#' + history[i].id + ' .textScroll').html(history[i].text);
							$('#' + history[i].id + ' .detailsRight').css('margin-right', '115px');
						} else {
							if (ssez=='gpc-scale') {
								if (history[i].ordine=='0' || history[i].ordine == '8') {
									var colore = '#000';
								} else {
									var colore = '#FFF';
								}
								$('#' + history[i].id + ' .textScroll').parent().css('color', colore);
								$('#' + history[i].id + ' .textScroll').parent().css('background', 'transparent');
								if (history[i].ordine!='0' && history[i].ordine !='10') {
									var tempHtml = '<h1>' + history[i].rolloverSubTitle + '</h1>';
									tempHtml += '<div style="width:100%; height:1px; background:' + colore + '; margin:10px 0px 10px 0px"></div>';
									tempHtml += history[i].text;
									$('#' + history[i].id + ' .detailsRight').css('margin-right', '130px');
									$('#' + history[i].id + ' .detailsRight').css('width', '346px');
									$('#' + history[i].id + ' .detailsRight').css('padding-right', '0px');
									$('#' + history[i].id + ' .textScroll').css('display', 'table-cell');
									$('#' + history[i].id + ' .textScroll').css('vertical-align', 'middle');
									$('#' + history[i].id + ' .textScroll').css('width', '346px');
									$('#' + history[i].id + ' .textScroll').css('font-family', 'CaslonProSemibold');
									$('#' + history[i].id + ' .textScroll').html(tempHtml);
								} else {
									if (history[i].ordine!='10') {
										var tempHtml = '<br /><br /><br /><div style="width:100%; height:1px; background:' + colore + '; margin:20px 0px 20px 0px"></div>';
										tempHtml += history[i].text;
										$('#' + history[i].id + ' .detailsRight').css('margin-right', '175px');
										$('#' + history[i].id + ' .detailsRight').css('width', '630px');
										$('#' + history[i].id + ' .detailsRight').css('padding-right', '0px');
										$('#' + history[i].id + ' .textScroll').css('display', 'table-cell');
										$('#' + history[i].id + ' .textScroll').css('vertical-align', 'middle');
										$('#' + history[i].id + ' .textScroll').css('width', '630px');
										$('#' + history[i].id + ' .textScroll').css('font-family', 'CaslonProRegular');
										$('#' + history[i].id + ' .textScroll').html(tempHtml);
									} else {
										printDebug('eccolo');
										$('#' + history[i].id + ' .detailsRight').remove();
									}
								}
							} else {
								if (ssez=='humankind') {
									var colore = '#000';
									var tempHtml = history[i].text;
									if (tempHtml!='') {
										$('#' + history[i].id + ' .detailsRight').css('margin-right', '120px');
										if (history[i].ordine=='1') {
											$('#' + history[i].id + ' .detailsRight').css('margin-top', '3px');
											$('#' + history[i].id + ' .detailsRight').css('width', '260px');
											$('#' + history[i].id + ' .detailsRight').css('padding-right', '0px');
											$('#' + history[i].id + ' .detailsRight').css('height', 'auto');
											$('#' + history[i].id + ' .textScroll').css('width', '240px');
											$('#' + history[i].id + ' .textScroll').css('height', 'auto');
											$('#' + history[i].id + ' .textScroll').html(tempHtml);
										} else {
											if (parseInt(history[i].ordine)<5) {
												$('#' + history[i].id + ' .detailsRight').css('margin-top', '18px');
												$('#' + history[i].id + ' .detailsRight').css('width', '260px');
												$('#' + history[i].id + ' .detailsRight').css('padding-right', '0px');
												$('#' + history[i].id + ' .textScroll').css('width', '240px');
												$('#' + history[i].id + ' .textScroll').css('height', '341px');
												$('#' + history[i].id + ' .textScroll').html(tempHtml);
											}
										}
									} else {
										$('#' + history[i].id + ' .detailsRight').remove();
									}
								}
							}
						}		
					}
					if (ssez == 'humankind') {
						$('.historyItems .detailsTitles h2').css('width', '380px');
					}
					if (subSez=='our-history' || subSez=='gpc-scale' || subSez=='humankind') {
						$('#lsthistory' + id).click();
						$('.detailsBottomLeft').live('mousemove', function(event) {
							var mousePosition = event.pageX - 210;
							var menuLength = parseInt($('.detailsBottomLeft ul').css('width').replace('px', ''));
							var escursione = menuLength - 757;
							var percentuale = parseInt(mousePosition * 100 / 757);
							var spostamento = parseInt( escursione / 100 * percentuale);
							$('.detailsBottomLeft ul').css('margin-left', '-' + spostamento + 'px');
						});
					} else {
						if (ssez == 'our-history') {
							$('.detailsBottomLeft').html('<i>&gt;&gt; <a href="/who-we-are/our-history/">Scopri tutta la storia&nbsp;&nbsp;&nbsp;</a></i>');
						} else {
							if (ssez == 'gpc-scale') {
								$('.detailsBottomLeft').html('<i>&gt;&gt; <a href="/approach/gpc/">Scopri tutta la scala GPC&nbsp;&nbsp;&nbsp;</a></i>');
							} else {
								$('.detailsBottomLeft').html('<i>&gt;&gt; <a href="/approach/humankind/">Scopri tutto di Humankind&nbsp;&nbsp;&nbsp;</a></i>');
							}
						}
						$('.detailsBottom').css('top', '450px');
						$('#historyRows').remove();
					}
					$('#first').remove();
					$('#historyRows').css('display', 'block');
				})
				.success(function() {
					$(".details").fadeIn(function() {
						if (typeof(ipad) != 'undefined') {
							if (ipad) {
								$('.detailsBottomLeft').hide();
							}
						}
						$(this).addClass('open');
					});
				});
			});
		}
		
		// hpItems
		function hpItems(hid, ssez) {
			$('#overlay').load('/template/caseHistory.html #ch', function() {
				$.getJSON(siteRoot + "overlayDetails.php?hid=" + hid, function(data) {
					if (data.main_title!='') {
						$(".main_title").html((data.main_title).replace('-', '<img src="/images/star.gif" />') + '<div class="divider"></div>');
					} else {
						$(".main_title").hide();
					}
					if (data.title!='') {
						$(".title").html(data.title).after('<div class="divider"></div>');
					} else {
						$(".title").hide();
					}
					if (data.subtitle!='') {
						$(".subtitle").html(data.subtitle);
					} else {
						$(".subtitle").hide();
					}
					$(".textScroll").html(data.text + '<br clear="all" /><div class="divider"></div>');
					if (sez == 'who-we-are') {
						$(".textScroll").css('height', detailsH - 138);
					} else {
						if (ssez=='awards') {
							$(".detailsLeft").remove();
							$(".detailsRight").css('width', 660);
							$(".detailsRight").css('padding-right', 90);
							$(".textScroll").css('width', 620);
							$(".textScroll").css('padding', 10);
							$(".textScroll").css('display', 'inline-block');
							$(".textScroll").css('height', detailsH - 220);
						} else {
							$('.detailsRight').css('margin-right', '50px');
							$(".textScroll").css('height', detailsH - 220);
						}
					}
					if (sez=='home' || subSez=='') {
						var tempTitle = '';
						switch(data.subSez) {
							case 'awards': case 'projects':
								tempTitle = 'I ';
								break;
							case 'case': case 'big-pencils':
								tempTitle = 'LE ';
								break;
							case 'evergreen':
								tempTitle = 'GLI ';
								break;
							case 'press-release':
								tempTitle = 'LA ';
								break;
						}
						$('.detailsBottomLeft').html('<i>&gt;&gt; <a href="' + siteRoot + data.sez + '/' + data.subSez + '/">SCOPRI ' + tempTitle + subSezArray[data.subSez] + '</a></i>');
					} else {
						if (data.link != '') {
							$('.detailsBottomLeft').html('&gt;&gt; <i>website</i> : <a href="http://' + data.link + '" target="_blank">' + data.link + '</a>');
						} else {
							$('.detailsBottomLeft').remove();
						}
					}
					$('.imgDetails').css('background-image', 'url(/images/contents/pic/' + hid + '.jpg)');
					
					if (data.video!='') {
						$('.imgDetails').css('cursor', 'pointer');
						$('.imgDetails img').attr('src', '/images/play.png');
						$('.imgDetails').attr('data-content-type', 'video');
						$('.imgDetails').attr('data-content', data.video);
					} else {
						if (data.image!='') {
							$('.imgDetails').css('cursor', 'pointer');
							$('.imgDetails img').attr('src', '/images/expand.png');
							$('.imgDetails').attr('data-content-type', 'image');
							$('.imgDetails').attr('data-content', hid);
						}
					}
					
					var urlSez = '';
					if (data.sez!='') {
						urlSez = '/' + data.sez + '/';
						if (data.subSez != '') {
							urlSez += data.subSez + '/';
						}
						$('.detailsBottomRight').html('&gt;&gt; <i><a href="' + urlSez + '">go to see other works</a></i>');
					} else {
						$('.detailsBottomRight').html('');
					}
				
				})
				.success(function() {
					$(".details").fadeIn(function() {
						fleXenv.initByClass("textScroll");
						$(this).addClass('open');
					});
				});
			});
		}
		
		initLeoQuotes();
	
	// MASK CLICK
		$("#mask").click( function() {
			if (sez =='' && subSez == '') {
				document.getElementById('youtube2_if').src='';
				document.getElementById('youtube2').style.display='none';
				document.getElementById('youtube1_if').src='';
				document.getElementById('youtube1').style.display='none';
			}
			$("#overlay").fadeOut();
			$(this).fadeOut();
			/**/
		});
	
	function containerDim(){
			windowH = $(window).height();
			windowW = $(window).width();
			contentH = (windowH - headerH - footerH);
			contentW = $('#content').width();
			detailsH = (windowH - headerH);
			objD.I = contentH;
			objD.L = contentW;
			//console.log(objD);
			getJson(0);
	};
	function scrollNav(){
		/*check if is possible to scroll*/
		var scroll = true;
		function deactivateScroll(){
			$('#prew, #next').css('visibility','hidden');
		}
		function checkScroll(){
			showScroll();
		}
		function showScroll(){
			if (scroll == true){
			$('#prew, #next').css('visibility','visible');
			}
			else{
				return false;
			}
		}
		deactivateScroll();
		checkScroll();
	};
	function scrollCont(){
		$('#scrollbar').slider({ animate: true });
	};
	function search(){
		$('#txt_search').keypress(function(event) {
			if ( event.which == 13 ) {
				chkSearch();
			}
		});
		function chkSearch() {
			$.get('/checkSearch.php?s=' + $("#txt_search").val(), function(data) {
				if (data=='true') {
					document.location.href='/search.php?p=' + $("#txt_search").val();
				} else {
					$('#searchAlert').slideDown();
				}
			});
		}
		function animateSearch(){
			var open = false;
			$('#searchIco').click(function(){
				if(open == false){
					open = true;
					$('#searchResult').animate({
						height: '30px'	
					},100);
					$(this).css('background-position','-93px -60px').animate({
						height: '36px'
					},100);
				}
				else{
					if ($("#txt_search").val().length > 3) {
						chkSearch();
					} else {
						$('#searchResult').animate({
							height: '0px'	
						},100);
						$(this).css('background-position','-93px -68px').animate({
						height: '28px'
						},100);
						open = false;
					}
				}
			});
		};
		function resultSearch(){
			var searchCont = $('#contentSearc').height();
			var result = objD.A - (objD.E + objD.G);
			$('#contentSearc').height(result + 'px');
		};
		function movePencil(openFoo){
			if(openFoo == true){
				var matita = $('#pencilCurr').width();
				var footerSize = $('#fooModal').width();
				var tolleration = '50';
				var tolleration2 = matita;
				var tolleration3 = '30';
				var result = (footerSize - matita) - tolleration;
				var result2 = result + matita;
				var fooEl = new Array;
				$('#pencilCont').width(result2 + 'px');
				$('#line').animate({
					width: result + 'px'
				},800);
				$('.elFoot').each(function(){
					fooEl.push($(this).width());
				});
				$('#fooMenuCont').width(result + 'px');
				$('#fooMenuCont ul').width(result + 'px');
				//console.log(fooEl);
				var sommaelementi = fooEl[0] + fooEl[1] + fooEl[2] + fooEl[3] + fooEl[4];
				var spazio = ($('#fooMenuCont ul').width()) - sommaelementi; 
				var spaceW = Math.ceil(spazio / 6);
				$('.space').width((spaceW)+ 'px');
			}
			else{
				$('#line').animate({
					width:'0px'
				},300);
			}
		};
		function showFoo(){
			var openFoo = false;
			$('#fooLogo').click(function(){
				if(openFoo == false){
					openFoo = true;
					$('#fooModal').animate({
						height:'150px'
					},300);
					$('#fooLogo').removeClass('fooLogoOpen').addClass('fooLogoClose');
					movePencil(openFoo);
				}
				else{
					openFoo = false;
					movePencil(openFoo);
					$('#fooModal').animate({
						height:'0px'
					},1300);
					$('#fooLogo').removeClass('fooLogoClose').addClass('fooLogoOpen');
				}
			});
		};
		function showSlider(){
			var lastValue = 0;
			$("#flagSlider *").fadeIn();
			$( "#slider" ).slider(
					{
						max:100,
						min:0,
						step:1,
						value:50,
						change: function(event, ui) {
							var result =Math.ceil( ui.value/20);
							if (result == 0) { result = 1; }
							if (result == 6) { result = 5; }
							_gaq.push(['_trackPageview', '/pencil/' + sez + '/' + result]);
							if (result != lastValue) {
								lastValue = result;
								reorganize(result);
							}
						}
					}		
			);
		}
		function calculateFoo(){
			var windowSize = $(window).width();
			//alert(windowSize + 'px');
			$('#modFooCont').css('width',windowSize);
			$('#fooModal').css('width',windowSize);
		}
		animateSearch();
		resultSearch();
		showFoo();
		showSlider();
		calculateFoo();
		$(window).resize(function(){
			resultSearch();
			calculateFoo();
		});
	};
	getJson(0);
	scrollNav();
	scrollCont();
	search();
	$(window).resize(function(){
		//$('#contentScroll').html('');
		//containerDim();
	});
// IPAD FUNC
	$.extend($.support, {
        touch: "ontouchend" in document
});

//
// Hook up touch events
//
$.fn.addTouch = function() {
        if ($.support.touch) {
                this.each(function(i,el){
                        el.addEventListener("touchstart", iPadTouchHandler, false);
                        el.addEventListener("touchmove", iPadTouchHandler, false);
                        el.addEventListener("touchend", iPadTouchHandler, false);
                        el.addEventListener("touchcancel", iPadTouchHandler, false);
                });
        }
};

var lastTap = null;
$('#slider').addTouch();
$('#fooLogo').addTouch();
$('#searchIco').addTouch();
});

// reorganize
	function reorganize(p) {
		$("#flagSlider").fadeOut();
		if (sez=='home') {
			var defSez = '';
		} else {
			defSez = sez; 
		}
		$.getJSON(siteRoot + "fill.php?p=" + p + "&x=" + contentW + "&y=" + contentH + "&h=" + headerH + "&currentPage=" + currentPage + '&sez=' + defSez + '&subSez=' + subSez, function(data) {
			totPages = data.totPages;
			var content = data.blocks;
			//scandisco il vecchio oggetto che contiene tutti i blocchi, se trovo l'id anche nel nuovo, aggiorno le coordinate per riposizionalro, altrimenti setto reposition=false e poi lo nascondo
			for (i=0;i<orig_content.length;i++){
				orig_content[i].reposition=false;
			}
			for (i=0;i<orig_content.length;i++){
				for (k=0;k<content.length;k++){
					if (orig_content[i].ID == content[k].ID) {
						orig_content[i].reposition=true;
						orig_content[i].newx=content[k].x;
						orig_content[i].newy=content[k].y;
					}
				}
			}
			
			//scandisco l'oggetto nuovo e cerco i nuovi box
			for (i=0;i<content.length;i++){
				var found = false;
				for (k=0;k<orig_content.length;k++){
					if (orig_content[k].ID == content[i].ID) {
						found = true;
						break;
					}
				}
				if (!found) {
					content[i].newBlock=true;
				}
			}
			
			var tempObject = new Array();
			var tempObject1 = new Array();
			
			//scandisco di nuovo l'oggetto originale e ridispongo i blocchi ancora presenti, nascondo e rimuovo i blocchi non pił presenti, aggiorno il mio nuovo oggetto temporaneo
			for (i=0;i<orig_content.length;i++){
				if(orig_content[i].reposition) {
					tempObject.push(orig_content[i]);
					$("#id" + orig_content[i].ID).animate({
						left: orig_content[i].newx +'px',
						top: orig_content[i].newy+'px'
					}, 1000);
				} else {
					$("#id" + orig_content[i].ID).fadeOut(200, function() { 	$(this).remove(); } );
				}
			}
			
			//scandisco il nuovo oggetto, aggiungo i blocchi nuovi, aggiorno il nuovo oggetto
			for (i=0;i<content.length;i++){
				if(content[i].newBlock) {
					tempObject.push(content[i]);
					tempObject1.push(content[i]);
				}
			}
			
			orig_content = tempObject;
			
			printDebug(orig_content.length);
			
			fillContent(tempObject1);
			
		});
	}

// fillContent
	function fillContent(obj) {
		for (i=0;i<obj.length;i++){
			var firstRow = '';
			if (obj[i].y == 0) {
				firstRow = ' firstRow';
			} else {
				firstRow = '';
			}
			var element = '<div data-id="' + obj[i].ID + '" id="id' + obj[i].ID + '" ' + 'class="r' + obj[i].relevance + ' ' +  obj[i].dimension + ' boxes' + firstRow + '" style="left:' + obj[i].x + 'px; top: ' + obj[i].y + 'px  ';
			if ((obj[i].overlayer=='1' || obj[i].overlayer=='2') && subSez!='our-brands') {
				element = element + ';cursor:pointer';
			}
			if (sez=='search') {
				if (i%2==0) {
					element = element + ';background:#FFF';
				} else {
					element = element + ';background:#dedede';
				}
			}
			element += '" data-link="' + obj[i].link + '"';
			element += ' data-overlayer="' + obj[i].overlayer + '" data-subsez="' + obj[i].subSez + '" data-sez="' + obj[i].sez + '" data-title="' + obj[i].rolloverTitle + '">';
			if (sez=='search') {
				element += '<img src="/images/contents/11/' + obj[i].ID + '.' + obj[i].ext + '" style="display:none;float:left;">';
			} else {
				element += '<img src="/images/contents/'+ obj[i].dimension.replace('c', '') + '/' + obj[i].ID + '.' + obj[i].ext + '" style="display:none;float:left;">';
			}
			
			if (sez=='search') {
				element += '<div id="searchResRight">';
				element += '<p class="titleArticle">' + sezArray[obj[i].sez] + '</p>';
				element += '<p class="subtitleArticle">' + subSezArray[obj[i].subSez] + '</p>';
				element += '<p class="contentArticle">' + obj[i].text + '</p>';
				element += '</div>';
				//element += '<div class="seeMore">&gt;&gt;clicca per saperne di pi&ugrave;</div>';
			} else {
			
				//ROLLOVER
					if (sez=='home' || subSez=='') {
						if (obj[i].subSez=='burnetters') {
							if (isiPad && (obj[i].overlayer=='1' || obj[i].overlayer=='2')) {
								element += '<div class="rollover" style="bottom:21px; height:50px; display:block">';
							} else {
								element += '<div class="rollover" style="bottom:21px; height:50px">';
							}
							element += '<div class="rolloverTitle">BURNETTER</div>';
							element += '<div class="rolloverSubTitle">Leggimi</div>';
						} else {
							if (isiPad && (obj[i].overlayer=='1' || obj[i].overlayer=='2')) {
								element += '<div class="rollover" style="display:block">';
							} else {
								element += '<div class="rollover">';
							}
							if (obj[i].subSez == '') { var tempTitle = 'Parla con Leo'; } else { var tempTitle = subSezArray[obj[i].subSez]; }
							element += '<div class="rolloverTitle">' + tempTitle + '</div>';
							element += '<div class="rolloverSubTitle">' + obj[i].rolloverTitle + '</div>';
						}
					} else {
						if (subSez=='burnetters') {
							if (isiPad && (obj[i].overlayer=='1' || obj[i].overlayer=='2')) {
								element += '<div class="rollover" style="bottom:21px; height:33px; display:block">';
							} else {
								element += '<div class="rollover" style="bottom:21px; height:33px;">';
							}
							element += '<div class="rolloverTitle">Leggimi</div>';
						} else {
							if (isiPad && (obj[i].overlayer=='1' || obj[i].overlayer=='2')) {
								element += '<div class="rollover" style="display:block">';
							} else {
								element += '<div class="rollover">';
							}
							if (obj[i].subSez == '') {
								element += '<div class="rolloverTitle">Parla con Leo</div>';
								element += '<div class="rolloverSubTitle">Fagli la tua domanda</div>';
							} else {
								element += '<div class="rolloverTitle">' + obj[i].rolloverTitle + '</div>';
								element += '<div class="rolloverSubTitle">' +  obj[i].rolloverSubTitle + '</div>';
							}
						}
					}
					element += '</div>';
			}
					
			element += '</div>';
			
			$(element).appendTo($('#contentScroll'));
			$('#id' + obj[i].ID + ' img').fadeIn(1500);
		}
		currentPage = 1;
		checkArrows();
	}

function nextPage() {
		currentPage+=0.5;
		$(".boxes").animate({ left: '-=' + boxesSlide }, 500, function() { disableButton=false; $("#prew").fadeIn(); });
		checkArrows();
}

function prevPage() {
	currentPage-=0.5;
	$(".boxes").animate({  left: '+=' + boxesSlide }, 500, function() { disableButton=false; if (currentPage == 1) { $("#prew").fadeOut(); } });
	checkArrows();
}

//checkArrows
	function checkArrows() {
		printDebug('currentPage: ' + currentPage + ' / totPages: ' + totPages);
		if (currentPage==1 && totPages==1) {
			$("#next").fadeOut();
			$("#next").fadeOut();
		} else {
			if (currentPage==totPages) {
				$("#next").fadeOut();
				$("#prew").fadeIn();
			} else {
				if (currentPage==1) {
					$("#next").fadeIn();
					$("#prew").fadeOut();
				} else {
					if ($("#next").css('display') == 'none') {
						$("#next").fadeIn();
					}
					if ($("#prew").css('display') == 'none') {
						$("#prew").fadeIn();
					}
				}
			}
		}
	}

// PRINT DEBUG
	function printDebug(str) {
		if (debugActive) {
			console.log(str);
		}
	}

// CALCULATE
	function calculate(){
		totElements = 0;
		$('.firstRow').each(function(){
			totElements += parseInt($(this).width());
	  });
	 }

$('.detailsClose').live('click', function() {
	$('.if_youtube').attr('src', '');
	$('.if_youtube').hide();
	$(".details").fadeOut().html('');
});
$('.video_close').live('click', function() {
	$('.if_youtube').attr('src', '');
	$('.youtube').hide();
	$('.detailsRight').show();
});
$('.imgDetails').live('click', function() {
	if ($(this).attr('data-content-type') == 'image') {
		$('.if_image').html('<img src="'+ siteRoot + 'images/contents/big/' + $(this).attr('data-content') + '.jpg"/>');
		$('.if_youtube').hide();
	} else {
		$('.if_youtube').attr('src', 'http://www.youtube.com/embed/' + $(this).attr('data-content') + '?rel=0&autoplay=1&showinfo=0');
		$('.if_image').hide();
	}
	$('.detailsRight').hide();
	$('.youtube').show();
});
$('.detailsBottomLeft ul li').live('click', function() {
	scrollHistory($('.detailsBottomLeft ul li').index(this));
	if (isiPad) { swipeInit(); }
});

// HISTORY SCROLL
	function scrollHistory(indice) {
		$('#ch').animate({ marginTop: '-' +  (indice * 444) });
		historyItems = indice;
		$('.detailsBottomLeft ul li').removeClass('active');
		$('.detailsBottomLeft ul li').addClass('unactive');
		$('.detailsBottomLeft ul li:eq(' + indice + ')').addClass('active');
		if (historyItems==0) {
			$('#historyUp').css('display', 'none');
			$('#historyDown').css('display', 'block');
		} else {
			$('#historyUp').css('display', 'block');
			if (historyItems < $('.detailsBottomLeft ul li').length - 1) {
				$('#historyDown').css('display', 'block');
			} else {
				$('#historyDown').css('display', 'none');
			}
		}
	}
	$('#historyUp').live('click', function() {
		historyItems--;
		scrollHistory(historyItems);
	});
	$('#historyDown').live('click', function() {
		historyItems++;
		scrollHistory(historyItems);
	});
	
	function swipeInit() {
 			$('#ch').bind("swipeup",function(){
				if (historyItems<$('.detailsBottomLeft ul li').length-1) {
					historyItems++;
					scrollHistory(historyItems);
				}
 			});
			
 			$('#ch').bind("swipedown ",function(){
				if (historyItems>0) {
					historyItems--;
					scrollHistory(historyItems);
				}
			});
			
	}
	
//leoquotes
	function leoquotes() {
		$('#overlay').load('/template/leoquotes.html #ch', function() {
			$.getJSON(siteRoot + "overlayDetails.php?sez=leo-quotes", function(data) {
				quotes = data.blocks;
			})
			.success(function() {
				$(".details").fadeIn(function() {
					$(this).addClass('open');
				});
			});
		});
	}
	
	function initLeoQuotes(){
		var urlToShare = '';
		var titleToShare = '';
		var contentToShare = '';
		var pHeight = '';
		var contHeight = '';
		var resHeight = '';
		var click = true;
			$("#ball").live('click',function(){	
				if(click == true){
					click = false;
					$(this).animate({
						top: '25px'
						},200);
							for(i=0;i<5;i++){
								$(this).animate({
									left: '365px'
								},50).animate({
									left: '405px'
								},50).animate({
								left: '385px'
								},50);
							}
							$(this).animate({
								top: '85px'
							},200,function(){
								$(this).parent().animate({
										margiTop:'460px'
									},1).fadeOut(100,function(){
										click = true;
										});
								$('.leoquotes2').css('top','100px').fadeIn();	
							});
							if(idQuotes != ''){
								pro();
								}
							else{
								normal();
								}
							$("#arrowNext").live('click',function(){
								normal();
							});
							$("#arrowPrev").live('click',function(){
								normal();
							});
							$("#refresh").live('click',function(){
								$('.leoquotes2').fadeOut(1,function(){
										$(this).css('top','460px');
									});
								$('.leoquotes1').css('margin-top','0px').fadeIn();
							});
					}
				});
			function pro(){
				$("#quotesContainer p").html(quotes[idQuotes].text);
				$("#quotesBox1 h4").html('LEO ' + (parseInt(idQuotes) +1));
				urlToShare = 'http://www.leoburnett.it/approach/leo-quotes/index.php?id=' + idQuotes + '&title=LEO' + randomIndex;
				$("#share a").attr("href", "http://www.facebook.com/sharer.php?u=" + urlToShare +"&t="+ titleToShare +"'");
			}
			function normal(){
				randomIndex = Math.floor(Math.random()*101);
				$("#quotesContainer p").html(quotes[randomIndex].text);
				$("#quotesBox1 h4").html('LEO ' + (parseInt(randomIndex) +1));
				urlToShare = 'http://www.leoburnett.it/approach/leo-quotes/index.php?id=' + randomIndex + '&title=LEO' + randomIndex;
				titleToShare = '';
				contentToShare = '';
				$("#share a").attr("href", "http://www.facebook.com/sharer.php?u=" + urlToShare +"&t="+ titleToShare +"'");
			}
	};
	
// leoHeritage
		function leoHeritage() {
			$('#overlay').load('/template/leoHeritage.html #ch', function() {
				$('.if_youtube').attr('src', 'http://www.youtube.com/embed/VGiaAA9ZuIU?rel=0&autoplay=1&showinfo=0');
				$('.youtube').show();
				$(".details").fadeIn(function() {
					$('#overlay').addClass('open');
				});
			});
		}
