/* Author:
marco di gennaro - dnsee
*/
//to do: easing on drag
var news;
//variabile per google map. spostata per errore su ie7 
if($('#main').attr('class') === 'storelocator'){
	var map;
}

function initPage() {
	$.ajaxSetup({cache: false});
	$('#container').fadeIn('slow');
	sizes();
	resizeImg();
	$('li:last-child, p:last-child, input:last-child, fieldset:last-child, select:last-child, span:last-child').addClass('last');
	$('li:first-child, p:first-child, input:first-child, fieldset:first-child, select:first-child, span:first-child').addClass('first');
	
	$('#social ').find('img').each(function(){
			var srcImg = $(this).attr('src').split('.png')[0];
			$(this).hover(function(){
				$(this).attr('src', srcImg +'_on.png');
			},function(){
				$(this).attr('src', srcImg +'.png');
			});
			
	});
	//
	var page = $('#main').attr('class');
	
	switch (page) {
	case 'home':
		break;
	case 'storelocator':
		var geocoder;
		//var	map;
		var globalData, googleData;
		initializeMap();
		$('select').customSelect();
		locateStore();
		pageScroll();
	break;
	case 'collection':
		scroller();
		break;
	case 'madeinitaly':
		pageScroll();
		break;
	case 'brand':
		pageScroll();
		break;
	case 'cashmere':
		pageScroll();
		break;
	case 'news':
		$.imageParams = {
			newWidth: 0,
			newHeight: 0
		};
		initScrollbarElments();
		getNews();
		pageScroll();
		/*if ($(document).hasClass('no-video')) {
			$('#video.no-flash').hide();
		}
		if ($(document).hasClass('video')) {
			$('#video.flash').hide();
		}*/
		break;
	case 'press':
		$.imageParams = {
			newWidth: 0,
			newHeight: 0
		};
		initScrollbarElments();
		getPress();
		pageScroll();
		break;
	case 'stores':
		//setBg();
		$.imageParams = {
			newWidth: 0,
			newHeight: 0
		};
		getStores();
		initScrollbarElments();
			
		pageScroll();
		break;
	case 'worldStores':
		
		
		break;	
		
	case 'contacts':
		pageScroll();
		break;
	case 'mymalo':
		pageScroll();
		$('select').customSelect();
		break;
	case 'resources':
		pageScroll();
		$('label.upload input[type=file]').bind('change focus click', function () {
			$(this).customUpload();
		});
		$('#human_resource input, #human_resource textarea').placeholder();
		$('select').customSelect();
		break;
	case 'storelocator':
		
		pageScroll();
	break;
	default:
		return false;
	}
	$(window).resize(function () {
		sizes();
		//resizeImg();
		var page = $('#main').attr('class');
		switch (page) {
		case 'home':
			break;
		case 'collection':
			dragBigImg();
			break;
		case 'madeinitaly':
			pageScroll();
			break;
		case 'brand':
			pageScroll();
			break;
		case 'cashmere':
			pageScroll();
			break;
		case 'press':
			
			$.imageParams = {
				newWidth: 0,
				newHeight: 0
			};
			drawGallery();
			initScrollbarElments();
			pageScroll();
			break;
		case 'news':
			
			$.imageParams = {
				newWidth: 0,
				newHeight: 0
			};
			drawGallery();
			initScrollbarElments();
			pageScroll();
			break;
		case 'worldStores':
			
			
			break;	
			
			
		case 'stores':
			//setBg();
			$.imageParams = {
				newWidth: 0,
				newHeight: 0
			};
			drawStoresGallery();
			initScrollbarElments();
			
			pageScroll();
			break;
		case 'contacts':
			pageScroll();
			break;
		case 'mymalo':
			pageScroll();
			break;
		case 'resources':
			pageScroll();
			break;
		default:
			return false;
		}
	});
}


function setBg() {
	var bg = $('#content_default_l').find('img').attr('src');
	$('#content_default_r').css({
		background: 'url(' + bg + ') no-repeat top left'
	});
}

function dragBigImg() {
	var viewport = $('#big').height();
	var bigImg = $('#big #product > img');
	var dragSize = Math.round(bigImg.height() - viewport);
	$('#product').css({
		height: dragSize * 2 + viewport,
		marginTop: -dragSize
	});
	bigImg.draggable({
		containment: $('#product'),
		axis: 'y'
	}).addTouch();
}

function centerSmallImg(){
	
	var smallImg = $('.items div.active > img'),
	pageH = $(window).height();
	smallImg.load(function () {
		var smallImgHeight = (pageH - 138) + ((pageH - 138) * 35 / 100);
	    $(this).height(smallImgHeight);
		var smallImgWidth = (smallImg.width() / 2) * -1;
		smallImg.css({
			marginLeft: smallImgWidth,
			marginTop: (smallImgHeight / 2 * -1) - 15
		});
		$('.items').animate({left:0}, function(){
			$('.items div.active > img').fadeIn()
		});
		
	});
	if($.browser.msie || isiTouchDevice()){
		var smallImgHeight = (pageH - 138) + ((pageH - 138) * 35 / 100);
	    smallImg.height(smallImgHeight);
		var smallImgWidth = (smallImg.width() / 2) * -1;
		smallImg.css({
			marginLeft: smallImgWidth,
			marginTop: (smallImgHeight / 2 * -1) - 15
		});
		$('.items').animate({left:0}, function(){
			$('.items div.active > img').fadeIn()
		});
	}
}
function centerBigImg(){
	
	var bigImg = $('#product > img'),
		loading = $('img#imgLoad');
		loading.css({width: 'auto', height:'auto, margin: 0'});
	bigImg.hide().load(function () {
		var bigWidth = bigImg.width(),
			bigHeight = bigImg.height();
		bigImg.css({
			marginLeft: -bigWidth / 2
		}).fadeIn();
		loading.hide();
	})
	if($.browser.msie || isiTouchDevice()){
		bigImg.hide();
		var bigWidth = bigImg.width(),
			bigHeight = bigImg.height();
		
		bigImg.css({
			marginLeft: -bigWidth / 2
		}).fadeIn();
		loading.hide();
	}
}
function addItem(galItem) {
	var api = $("#small .scrollable").data("scrollable");
	api.addItem(galItem.clone().end());
	centerSmallImg();
}

function scroller(){
	dragBigImg();
	var nextLink = $('a.next'),
		prevLink = $('a.prev');
	if(isiTouchDevice()){
		function ajaxCall(dir, old, divHeight, direction){
			$.ajax({
				url: dir,
				success: function(data){
					$('.scrollable').removeData();
					
					var galItem = $(data).find('div.items > div');
						aLeft =  $(data).find('a.left').attr('href'),
						aRight =  $(data).find('a.right').attr('href');
					galItem.height(divHeight);
					nextLink.attr('href', aRight);
					prevLink.attr('href', aLeft);
					getItemGal (dir, old, direction);
					addItem(galItem);
				}
			});
		}
		$('div.items').addSwipeEvents().bind('swipeleft', function(e) {
			var dir = nextLink.attr('href'),
				old = $('.items > div'),
				direction = 'left',
				divHeight = $('.items div').height();
				ajaxCall(dir, old, divHeight, direction);
	   });
	   $('div.items').addSwipeEvents().bind('swiperight', function(e) {
			var dir = prevLink.attr('href'),
				old = $('.items > div'),
				direction = 'right',
				divHeight = $('.items div').height();
				ajaxCall(dir, old, divHeight, direction);
	   });
	}
	$('a.browse').click(function(e){
		e.preventDefault();
		
		var trigger = $(this),
			dir = trigger.attr('href'),
			old = $('.items > div'),
			divHeight = $('.items div').height();
		$.ajax({
			url: dir,
			success: function(data){
				$('.scrollable').removeData();
				
				var galItem = $(data).find('div.items > div');
					aLeft =  $(data).find('a.left').attr('href'),
					aRight =  $(data).find('a.right').attr('href');
				galItem.height(divHeight);
				nextLink.attr('href', aRight);
				prevLink.attr('href', aLeft);
				getItemGal (dir, old);
				addItem(galItem);
			}
		});
	});		
}
function getItemGal (dir, old, direction){
	$('#big #product').hide().find('img').css({
		marginLeft: -$('#big #product').find('img').width() / 2
	});
	//$('.scrollable .items div:eq(0)').find('img').fadeIn();
	
	$(".scrollable").scrollable({
		onAddItem: function(e, index){
			var items = this.getItems(),
				$this = items.eq(index);
			$('.items div > img').hide();
			var windowWidth =
			$('body').append('<div id="mask" style="position:absolute; top:0; left:0; width:'+$(window).width()+'px; height:'+$(window).height()+'px;z-index:999;"></div>')
			switch (direction){
				case 'left':
					$('.items').animate({
						left: -429
					}, function(){
						getBigImg($this, items, index);
						
					});
				break;
				case 'right':
					$('.items').animate({
						left: 429
					}, function(){
						getBigImg($this, items, index);
						
					});
				break;
				default:
					$('.items').animate({
						left: -429
					}, function(){
						getBigImg($this, items, index);
						
					});
				
			}
			
			old.remove();
			
		},
		onSeek: function (e, index) {
			var items = this.getItems(),
				$this = items.eq(index);
				
		}
	});
}

function getBigImg($this, items, index){
	
	var loading = $('img#imgLoad');
	loading.show();
	index.find('img').fadeIn('fast', function () {
		var title = index.find('img').attr('title'),
			imgSrc = index.find('img').attr('src').replace('small', 'big'),
			description = index.find('.description').html(),
			newImg = $('<img src="' + imgSrc + '" alt="' + title + '" title="' + title + '" />');
		$('#big #product').find('img').fadeOut().remove();
		$('#big #product').append(newImg);
		newImg.hide().load(function () {
			var marginLeft = $(this).width() / 2;
			$(this).css({
				marginLeft: -marginLeft,
				top: -100
			}).fadeIn('slow', function () {
				$(loading).hide();
				dragBigImg();
				$('#mask').remove();
				
			});
		});
		$('#big #product').find('.description').html(description);
		$('#big #product').fadeIn('slow');
		//bag image rollover
		imgBagRollover();
		
	});
}

function imgBagRollover() {
	var imgBag = $('.model').find('img.bag');
	imgBag.mouseover(function(){
		$(this).attr('src', '/images/bag.png');
	}); 
	imgBag.mouseout(function(){
		$(this).attr('src', '/images/bag_off.png');
	});
}



/*function scroller() {
	$('#big #product').find('img').css({
		marginLeft: -$('#big #product').find('img').width() / 2
	});
	$('.scrollable .items div:eq(0)').find('img').fadeIn();
	dragBigImg();
	
	
	$(".scrollable").scrollable({
		onSeek: function (e, index) {
			var loading = $('img#loading');
			loading.css({top:'20px', left:'20px', margin: '0'});
			$('#big #product').fadeOut('fast');
			$('#big #product').find('img').fadeOut('fast').css({
				top: -100
			});
			$('#big').find(loading).show();
			var items = this.getItems(),
				$this = items.eq(index);
			$this.find('img').fadeIn('fast', function () {
				var title = $this.find('img').attr('title'),
					imgSrc = $this.find('img').attr('src').replace('small', 'big'),
					description = items.eq(index).find('.description').html();
				$('.scrollable .items div').removeClass('active');
				$this.addClass('active');
				
				var newImg = $('<img src="' + imgSrc + '" alt="' + title + '" title="' + title + '" />');
				$('#big #product').find('img').remove();
				$('#big #product').append(newImg);
				newImg.hide().load(function () {
					var marginLeft = $(this).width() / 2;
					$(this).css({
						marginLeft: -marginLeft,
						top: -100
					}).fadeIn('slow', function () {
						$(loading).hide();
						dragBigImg();
					});
				});
				$('#big #product').find('.description').html(description);
				$('#big #product').fadeIn('slow');
				//bag image rollover
				var imgBag = $('.model').find('img.bag');
					
				imgBag.mouseover(function(){
					$(this).attr('src', '/images/bag.png');
				}); 
				imgBag.mouseout(function(){
					$(this).attr('src', '/images/bag_off.png');
				});
			});
		}
	});
	$('a.browse').removeClass('disabled');
}
*/
function resizeImg() {
	var pageW = $('#container').width(),
		pageH = $(window).height() - 138,
		sizedImg = $('#main > .f-left > img');
	$('#main > #content_default_l').append('<img src="/images/loading.gif" title="loading" alt="loading" id="loading"  />' );
	$('#loading').css({top:'50%', left:'50%', margin: '-33px 0 0 -248px'});
	
	$('#main > .f-left > img').hide().load(function () {
		var imgSize = {
			width: $('#main > .f-left > img').width(),
			height: $('#main > .f-left > img').height()
		};
		$('#main > .f-left > img').css({
			width: pageW,
			marginTop: (imgSize.height / 2 * -1) + 31
		}).fadeIn();
		$('#main > #content_default_l img#loading').remove();
		
	});
	$(window).resize(function(e) {
		var pageW = $('#container').width(),
		pageH = $(window).height() - 138,
		sizedImg = $('#main > .f-left > img');
        var imgSize = {
			width: sizedImg.width(),
			height: sizedImg.height()
		};
		sizedImg.css({
			width: pageW,
			marginTop: (imgSize.height / 2 * -1) + 31
		});
    });
}

function sizes() {
/*var pageH = $(window).height() ,
		pageW = $('#container').width();*/
	var pageW = 0,
		pageH = 0;
	if (typeof (window.innerWidth) === 'number') {
		//Non-IE
		pageW = window.innerWidth;
		pageH = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		pageW = document.documentElement.clientWidth;
		pageH = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		pageW = document.body.clientWidth;
		pageH = document.body.clientHeight;
	}
	if (pageW <= 960) {
		pageW = 960;
	}
	if (pageH < 640) {
		pageH = 640;
	}
	//standard
	$('#content_default_l ').width(pageW);
	$('#content_default_r, #content_default_l').height(pageH - 138);
	//
	$('#myM_l').height(pageH - 108);
	$('#myM_r').height(pageH - 118);
	$('#main').height(pageH - 110);
	$('#main.resources').height('auto');
	$('#big, #small, #small  .items div, #news-l, #store-l, #store-r').height(pageH - 138);
	$('#news-r').height(pageH - 218);
	$('#news-l,  #myM_l, #store-l, #map').width($('#container').width() - 640); //set the width of the container
	
	// For use within normal web clients 
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	if(isiPad){
		
		$('#store-l,#map').width($('#container').width() - 390);
	}
	
	$('#risorse_r').width(($('#container').width() / 2) - 1);
	$('#risorse_l').width(($('#container').width() / 2));
	$('#paleBg').height(pageH - 316);
	//interna
	
	$('.scrollable').height(pageH - 109);
	$('#big').width(pageW - 430);
	if ($('#big').width() < 600) {
		$('#big').width(600);
	}
	//
	$('#map').width(pageW - 640); //store
	//home box
	homeSize(pageH, pageW);
	//menu interno
	initMenu(pageH, pageW);
	centerSmallImg();
	centerBigImg();
}

function homeSize(pageH, pageW) {
	pageW = $('#container').width();
	var boxW = [pageW - 1] / 2,
		boxH = [pageH - 109] / 2,
		imgW = [pageW - 1] / 2,
		mLeft = -[pageW - 1] / 4,
		mTop = (imgW * 22 / 100);
	$('.boxHome, .boxHome .defDiv').width(boxW);
	$('.boxHome, .boxHome .defDiv').height(boxH);
	$('.boxHome img').css({
		marginLeft: mLeft,
		width: imgW,
		top: -mTop
	});
	var overDiv = $('.overDiv').css({
		width: boxW,
		height: boxH
	});
	var blockLink = $('.defDiv');
	$('.boxHome').hover(function () {
		
		if($.browser.msie){
			$(this).find('.overDiv').css({
				display: 'block'
			});	
		}
		$(this).find('.overDiv').css({
			display: 'table-cell'
		});
		$(this).find(blockLink).hide();
	}, function () {
		$(this).find('.overDiv').hide();
		$(this).find(blockLink).show();
	});
}

function isiTouchDevice() {
	var userAgent = navigator.userAgent;
	return (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i) || userAgent.match(/iPad/i));
}



function initMenu(pageH, pageW) {
	var classPage = $('#main').attr('class');
	if (classPage === 'home' || classPage === 'contatti' || classPage === 'resources' || classPage === 'mymalo') {
		$('nav > ul').addClass('rich');
	} else {
		$('nav > ul').addClass('simple');
	}
	//rich menu
	var li = $('nav > ul.rich > li'),
		subM = $('nav ul.rich ul'),
		subLi = $('nav ul.rich ul li'),
		subW = subM.innerWidth();
	subM.hide();
	
	if (li.attr('id') === 'collezioniit') {
		var linkUomo = $('li#collezioniit').find('ul li:eq(1) a').attr('href'),
			linkDonna = $('li#collezioniit').find('ul li:eq(0) a').attr('href');
		$('li#collezioniit').append('<a id="donna" href="' + linkDonna + '"></a><a id="uomo" href="' + linkUomo + '"></a>');
	}else if(li.attr('id') === 'collezionien'){
		var linkUomo = $('li#collezionien').find('ul li:eq(1) a').attr('href'),
			linkDonna = $('li#collezionien').find('ul li:eq(0) a').attr('href');
		$('li#collezionien').append('<a id="women" href="' + linkDonna + '"></a><a id="men" href="' + linkUomo + '"></a>');

	}
	
	li.hover(function () {
		var toLeft = $(this).offset();
		$(this).addClass('selected');
		$(this).find('ul').stop('true', 'true').fadeIn();
		if((subW + toLeft.left) > pageW){
		 $(this).find('ul').addClass('reverse');
		}
	}, function () {
		$(this).removeClass('selected');
		$(this).find('ul').stop('true', 'true').hide();
		if($(this).find('ul').hasClass('reverse')){
			$(this).find('ul.reverse').removeClass('reverse');
		}
	}); 
	//menu sizes
	var navWidth = $('nav').width();
	$('nav').css({
		marginLeft: -navWidth / 2
	});
	if(isiTouchDevice()){
		$('nav').css({
			marginLeft: (-navWidth / 2) - 30
		});
	}
	if ($('nav ul').hasClass('simple')) {
		$('#main').height(pageH - 139).css({
			marginTop: '29px'
		});
	}
	var menuLeft = $('nav ul').offset();
	$('nav ul.simple ul').css({
		width: pageW,
		left: -menuLeft.left
	});
	
	//service menu 
	$('ul#serviceBar li').hover(function(){
		$(this).addClass('selected');
	}, function(){
		$(this).removeClass('selected');
	});
	
}


function getNews() {
	$.ajax({
		beforeSend: function () {
			$('.loader').show();
		},
		url: urlnews,
		success: function (data) {
			news = data;
			drawGallery();
		},
		complete: function () {
			$('.loader').hide();
		}
	});
}

function getPress() {
	$.ajax({
		beforeSend: function () {
			$('.loader').show();
		},
		url: urlpress,
		success: function (data) {
			news = data;
			drawGallery();
		},
		complete: function () {
			$('.loader').hide();
		}
	});
}


function getStores() {
	//if($('.gallery').length > 0 ){
		$.ajax({
			beforeSend: function () {
				$('.loader').show();
			},
			url: '/it/stores/stores-data-world',
			success: function (data) {
				stores = data;
				drawStoresGallery();
			},
			complete: function () {
				$('.loader').hide();
			}
		});
	//}
}

function drawStoresGallery() {
	
	var wrapper = $('#paleBg #malo_gallery'),
		number = stores.number;
	//wrapper.empty();
	var list = [],
		overlay = [];
	$.each(stores, function(key, val){
		if(val.thumb)	{
			list.push('<a rel="#over'+val.id+'"><img src="'+val.thumb+'" alt="'+val.city+'" /></a>');
			overlay.push('<div class="apple_overlay" id="over'+val.id+'"><img alt="'+val.city+'" src="'+val.image+'" /><div class="details"><a class="close">close</a><h2>'+val.city+'</h2><p></p></div></div>');
		}
			
	});
	wrapper.append(list.join(''));
	$('body').append(overlay.join(''));
	wrapper.find('a[rel]').overlay({
		mask:{
			color: '#222222', 
			opacity:0.8
		}
	});
	var triggerOverlay = wrapper.find('a[rel]');
	/*triggerOverlay.click(function(){
		var divId = $(this).attr('rel').split('over')[1];
		$('body').append(overlay[divId], function(){
			wrapper.find('a[rel="'+divId+'"]').overlay();
		});
		
	});*/
	
}

function drawGallery() {
	var wrapper = $('#news-l ul'),
		number = news.number;
	wrapper.empty();
	$('#news-l').width($('#container').width() - 640); //set the width of the container
	$('#scrollbar').width([$('#container').width() - 1] - 640); //set the width of the bar with scrolling buttons
	var defaultW = 318,
		//default width
		defaultH = 450,
		//default height
		cols = Math.floor($('#news-l').width() / defaultW);
	if (cols < 2) {
		$.imageParams.newWidth = $('#news-l').width() / 2;
		cols = 2;
	} else {
		diff = $('#news-l').width() - (cols * defaultW);
		plusPixel = diff / cols;
		$.imageParams.newWidth = plusPixel + defaultW;
	}
	var val;
	
	var rows = Math.ceil(number / cols);
	$.imageParams.newHeight = $.imageParams.newWidth / defaultW * defaultH;
	var startY = 0;
	for (var i = 0, elements = 1; i < rows; i++) {
		startX = 0;
		for (var a = 0; a < cols; a++) {
			val = news[elements + ""];
			if(val){
				var list, 
					time = '<time>' + val.datatime + '</time>',
					imgItem = '<img src="' + val.image + '" alt="" title="" class="img_item" />',
					boxTitle = '<h2>' + val.title + '</h2>',
					boxItem = '<a href="#"style="width:' + $.imageParams.newWidth + 'px"><div class="news_title" >' + time + boxTitle + '</div></a>';
				list += '<li id="n' + elements + '" style="width:' + $.imageParams.newWidth + 'px;height:' + $.imageParams.newHeight + 'px;top:' + startY + 'px; left:' + startX + 'px" >' + imgItem + boxItem + '</li>';
				startX += $.imageParams.newWidth;
				elements++;				
			}			
		}
		startY += $.imageParams.newHeight;
	}
	$(list).hide();
	
	wrapper.height( rows * $.imageParams.newHeight + 'px'); //altezza del wrapper
	$(list).fadeIn().appendTo(wrapper);
	//stato hover del box
	wrapper.find('li a').each(function () {
		$(this).hover(function () {
			$(this).addClass('active');
		}, function () {
			$(this).removeClass('active');
		});
	});
	
	openNews(wrapper);
	//set list to top 0 after resize
	wrapper.stop().animate({
		top: '0px'
	});
}


function openNews(wrapper) {
	var newsItem = wrapper.find('li'),
		video = $('<div id="video"/>'),
		time = $('#news-r').find('time'),
		newsDiv = $('#textContent'),
		newsObj;
	//img for over state
	$.overSelected = {
		layer: $('<img class="over" src="/images/news_over.png" alt="" />').css({
			width: $.imageParams.newWidth,
			height: $.imageParams.newHeight
		}),
		arrow: $('<img class="arrow" src="/images/news_arrow.png" alt="" />')
	};
	wrapper.find('li:eq(0)').addClass('selected').append($.overSelected.layer).append($.overSelected.arrow);
	newsItem.click(function () {
		newsItem.removeClass('selected');
		$.overSelected.layer.remove();
		$.overSelected.layer.remove();
		$(this).addClass('selected').append($.overSelected.layer).append($.overSelected.arrow);
		var newsNumb = $(this).attr('id').split('n')[1];
		var pageName = $('#main').attr('class');
		$.ajax({
			url: pageName + '/' + pageName + '-data',
			dataType: 'json',
			success: function (data) {
				var videoSrc = data[newsNumb].video,
					text = data[newsNumb].textcontent,
					time = '<time>' + data[newsNumb].datatime + '</time>',
					title = '<h1>' + data[newsNumb].title + '</h1>',
					flash;
				//if ($(document).hasClass('no-video')) {
					flash = '<div id="video"><object width="100%" height="100%" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  id="player1" name="player1"><param name="movie" value="/images/player/player.swf"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="flashvars" value="viral.onpause=false&file=/images/player/video.mp4"><embed id="player1" name="player1" src="/images/player/player.swf" width="100%" height="100%" allowscriptaccess="always" allowfullscreen="true" flashvars="viral.onpause=false&file=' + videoSrc + '" /></object></div>';
				//} else {
					//flash = '<video controls="controls" poster="" width="600" height="321"><source src="' + videoSrc + '" /></video>';
				//}
				//time = data[newsNumb].title
				newsDiv.hide();
				if (videoSrc !== '') {
					newsObj = time + title + flash + text;
				} else {
					newsObj = time + title + text;
				}
				newsDiv.empty().append(newsObj).fadeIn(function () {
					pageScroll();
				});
			}
		});
	});
}

function pageScroll() {
	var textH = $('#textContent').height() - 50,
		containH = $('#textContent').parent().height();
	if (textH > containH) {
		$('#scroll').show();
		
		
		initScrollDeafultPage();
	} else {
		$('#scroll').hide();
		$('#paleBg').height($('#paleBg').height() + 40);
	}
}

//triggers per lo scroll

function initScrollbarElments() {
	
	var scrollDown = $('.scrollDown'),
		scrollUp = $('.scrollUp');
	scrollDown.scrolling('down', $('#news-l > ul.zero'));
	scrollUp.scrolling('up', $('#news-l > ul.zero'));
	
}

function initScrollDeafultPage(){
	$.imageParams = {
		newWidth: 0,
		newHeight: 50
	};
	
	$('#scroll #up, .scroll #up, #scroll .up').scrolling('up', $('#textContent, .textContent'));
	$('#scroll #down, .scroll #down, #scroll .down').scrolling('down', $('#textContent, .textContent'));
}
//scrolling
$.fn.scrolling = function (direction, toScroll, scrollSize) {
	var $trigger = $(this);
	var scrollSize = $.imageParams.newHeight || "50px";
	
	switch (direction) {
	case 'down':
		$trigger.click(function (event) {
			var maxTop = toScroll.height() - [$(toScroll).parent().height() - 80];
			event.preventDefault();
			event.stopPropagation();
			var toTop = toScroll.position().top * -1;
			if (toTop + $.imageParams.newHeight >= maxTop) {
				$(toScroll).stop().animate({
					top: -maxTop + 'px'
				});
			} else {
				$(toScroll).stop(true, true).animate({
					top: "-=" + $.imageParams.newHeight //scrollSize
				}, {
					duration: 1000,
					specialEasing: {
						top: 'easeOutCirc'
					}
				});
			}
		});
		break;
	case 'up':
		$trigger.click(function (event) {
			var maxTop = toScroll.height() - [$(toScroll).parent().height() - 30];
			var toTop = toScroll.position().top * -1;
			event.preventDefault();
			event.stopPropagation();
			if (toTop - $.imageParams.newHeight <= 0) {
				$(toScroll).stop().animate({
					top: 0
				});
			} else {
				$(toScroll).stop(true, true).animate({
					top: "+=" + $.imageParams.newHeight
				}, {
					duration: 1000,
					specialEasing: {
						top: 'easeOutCirc'
					}
				});
			}
		});
		break;
	default:
		return false;
	}
}


//upload custom
$.fn.customUpload = function () {
	var $this = $(this),
		$val = $this.val(),
		$button = $this.parent().siblings('.button');
	if ($val !== '') {
		$button.text('File caricato!').css('color', 'green');
	}
};
$.fn.customSelect = function () {
	if (!$.browser.opera) {
		// select element styling
		$('select').each(function () {
			var value = $(this).find('option:first').text();
			var classSel = $(this).attr('class');
			if ($('option:selected', this).val() !== '') {
				value = $('option:selected', this).text();
			}
			$(this).css({
				'z-index': 10,
				'opacity': 0,
				'filter': 'alpha(opacity=0)',
				'-ms-filter':"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"
				
			}).after('<span class="select ' + classSel + '">' + value + '</span>').change(function () {
				val = $('option:selected', this).text();
				$(this).next().text(val);
			})
		});
	}
}
//map store
function initializeMap() {
	var latlng = new google.maps.LatLng(45.469151, 9.198031);
	var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map"), myOptions);
	geocoder = new google.maps.Geocoder();
	var marker = new google.maps.Marker({
		position: latlng,
		title:"Milano, Via della Spiga, 7"
	});
	marker.setMap(map);
	var popGallery = '<div id="popup"><h1>Malo Milano</h1><p>Via della Spiga, 7</p><div id="gallery"><div class="mapGallery"><div class="items"><a rel="#pop1"><img alt="Milano" src="/uploads/store_files/def4b482ac6d4c0ae824ea4bbaa87e913d9d8264.jpg"></a><a rel="#pop2"><img alt="Milano" src="/uploads/store_files/e0a76e9ad944c7856059ca691370a8fda2c8e2f7.jpg"></a><a rel="#pop3"><img alt="Milano" src="/uploads/store_files/81e9e6fdf3429bbd7f1c1838c03efa68f2a20980.jpg"></a></div></div></div></div>';
	
	var infowindow = new google.maps.InfoWindow({
		content: popGallery
	});
	//google.maps.event.addListener(marker, 'click', function() {
	  infowindow.open(map,marker);
	  var divOverlay = '<div id="pop1" class="apple_overlay"><img alt="" src="/uploads/store_files/def4b482ac6d4c0ae824ea4bbaa87e913d9d8264.jpg"><div class="details"><h1>Malo Milano</h1><p>Via della Spiga, 7</p></div><a class="close">close</a></div><div id="pop2" class="apple_overlay"><img alt="" src="/uploads/store_files/e0a76e9ad944c7856059ca691370a8fda2c8e2f7.jpg"><div class="details"><h1>Malo Milano</h1><p>Via della Spiga, 7</p></div><a class="close">close</a></div><div id="pop3" class="apple_overlay"><img alt="" src="/uploads/store_files/81e9e6fdf3429bbd7f1c1838c03efa68f2a20980.jpg"><div class="details"><h1>Malo Milano</h1><p>Via della Spiga, 7</p></div><a class="close">close</a></div>';
		
		$('body').append(divOverlay);
	  $('.mapGallery').find('a[rel]').live('click', function (e) {
			e.preventDefault();
			var clickLink = $(this).overlay({
				mask:{
					color: '#222222', 
					opacity:0.8
				},
				onBeforeLoad: function() {
					var wrap = this.getOverlay().find("body");
					wrap.load(this.getTrigger().attr("href"));
				}
			 });
			$(this).overlay().load();  //initiates overlay
			clickLink.load();  //loads above overlay settings
			return false;
		});
	  
	//});

}

function codeAddress(storeAddress, popGallery) {
	
	geocoder.geocode( { 'address': storeAddress}, function(results, status) {
	  if (status === google.maps.GeocoderStatus.OK) {
	  	map.setCenter(results[0].geometry.location);
		var marker = new google.maps.Marker({
			map: map,
			position: results[0].geometry.location,
			title: storeAddress
		});
		var infowindow = new google.maps.InfoWindow({
			content: popGallery
		});
		 infowindow.open(map,marker);
	 	//scrollable per la gallery
		
		//$('#popup #gallery').scrollable();
		$('.mapGallery').find('a[rel]').live('click', function (e) {
			e.preventDefault();
			var clickLink = $(this).overlay({
				mask:{
					color: '#222222', 
					opacity:0.8
				},
				onBeforeLoad: function() {
					var wrap = this.getOverlay().find("body");
					wrap.load(this.getTrigger().attr("href"));
				}
			 });
			$(this).overlay().load();  //initiates overlay
			clickLink.load();  //loads above overlay settings
			return false;
		});
		
	  } else {
		alert("Questo indirizzo non esiste: "+' '+storeAddress );
	  }
	});
}


function selectStore(){
	var storeItem = $('#store-r ul.zero li');
	storeItem.click(function(e){
		$('.apple_overlay').remove();
		e.stopPropagation();
		addressKey = $(this).attr('id');
		storeAddress = googleData[addressKey].city + " " + googleData[addressKey].address;
		//Gallery pop google map
		var counter = 0;
		var pics = [],
			divOverlay = [],
			gallery;
		if(jQuery.isPlainObject( googleData[addressKey].gallery )){
			$.each(googleData[addressKey].gallery.image, function(key, val){
				counter++;
				pics.push('<a  rel="#pop'+counter+'"><img src="'+val+'" alt="'+googleData[addressKey].city+'" /></a>');
				divOverlay.push('<div class="apple_overlay" id="pop'+counter+'"><img src="'+val+'" alt=""  /><div class="details"><h1>Malo '+googleData[addressKey].city+'</h1><p>'+googleData[addressKey].address+'</p></div><a class="close">close</a></div>');
					gallery = pics.join('');
			});
			
			$('body').append(divOverlay.join(''));
			popGallery = '<div id="popup"><h1>Malo '+googleData[addressKey].city+'</h1><p>'+googleData[addressKey].address+'</p><div id="gallery"><!--<a class="prev browse left"></a>--><div class="mapGallery"><div class="items">'+gallery+'</div></div><!--<a class="next browse right"></a>--></div>';
		}else{
			popGallery = '<div id="popup"><h1>Malo '+googleData[addressKey].city+'</h1><p>'+googleData[addressKey].address+'</p></div>';
		}
		if(storeItem.hasClass('selected')){
			storeItem.removeClass('selected');
		}
		$(this).addClass('selected');
		codeAddress(storeAddress, popGallery);
	});
}
function locateStore(){
	var list = [],
		storeItem = $('#store-r ul.zero li'),
		storeList = $('#store-r ul.zero'),
		storeForm = $('form[name="store_finder"]'),
		selectCountry = $('#storeFinder_nation_id'),
		selectCity = $('#storeFinder_city'),
		send = storeForm.find('input.submit'),
		textContent = $('#store-r #textContent'),
		storeAddress;
	$.ajax({
		url: 'stores/stores-data',
		dataType: 'json',
		success: function(data){
			globalData = data;
			googleData = new Array();
			$.each(globalData, function(key, val){
				$.each(val, function(key, val){
					key = "";
					$.each(val, function(){
						if(val.id) {
							key = val.id;
						}
					});
					googleData[key] = val;
				});
			});
		}
	});
	
	$('#storesWrap').height($(window).height() - 314);
	selectStore();	
	pageScroll();
	function buildList(){
		if(jQuery.isEmptyObject(list)){
			storeList.html('<li><h2>Non ci sono Malo stores nella tua città</h2></li>');
			storeList.show();
			$('#selectStore').hide();
			return false;
		}else{
			
			storeList.html(list.join(''));
			storeList.show();
			$('#selectStore').hide();
		}
		selectStore();
		pageScroll();
	}
	storeForm.submit(function(){
		list = [];
		$('span.select').text(selectCountry.find('option:first').text());
		var citySel = selectCity.val();
		textContent.css({top:0});
		$.each(globalData, function(i,c){
			$.each(c, function(key, val){
				if( val.city.toLowerCase() === citySel.toLowerCase()){
					list.push('<li id="'+val.id+'"><h2>'+val.city+'</h2><p>'+val.address+'<br>'+val.city+'</p></li>');
				}
			});	
		});
		buildList();	
		return false;
	});
	selectCountry.change(function(e){
		list = [];
		selectCity.val('');
		var country = selectCountry.find('option:selected').text();
		textContent.css({top:0});
		$.each(globalData[country], function(i,c){
			$(c).each(function(key, val){
				list.push('<li id="'+val.id+'"><h2>'+val.city+'</h2><p>'+val.address+'<br>'+val.city+'</p></li>');
				
			});	
		});
		buildList();
		return false;
	});
}




