/**
 * 
 * 
 */
var docH;
var docW;
var b_W_size=552;
var b_H_size=495;

var anchor=self.document.location.search.substring(1);
var tmp=anchor.split('&');

var GET={};

for (elem in tmp)
{
	var key_val=tmp[elem].split('=');
	GET[key_val[0]]=key_val[1];
}

function popup(page,name) {
    var generator = window.open(page, name, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, height='+($(window).height()*0.9)+',width='+($(window).width()*0.6)+',top='+($(window).height()*0.1)+',left='+($(window).height()*0.2));
    if (generator != null) {
        return true;
    }
    else {
        alert('Popup should be enabled.');
        return false;
    }

}

function checkNext(id,init)
{
	var control=$('#'+id+' .current').attr('ref')==$('#'+id).children().last().attr('ref');
	if (init)
	{
		control=control || $('#'+id+' .current').next().attr('ref')==$('#'+id).find('div').last().attr('ref');
	}
	if (control)
	{
		if ($('#txt_next a span').css('color')!="rgb(181, 181, 181)" || init)
		{
			$('#img_next a img').attr('src','images/down_off.png');
			$('#txt_next a span').html('NEXT');
			$('#txt_next a span').css('color','#B5B5B5');
			Cufon.replace('#txt_next a span', {fontFamily: "HelvNeue" });
		}
	}
	else
	{
		if($('#txt_next a span').css('color')!="rgb(51, 51, 51)" || init)
		{
			$('#img_next a img').attr('src','images/down_on.png');
			$('#txt_next a span').html('NEXT');
			$('#txt_next a span').css('color','');
			Cufon.replace('#txt_next a span', {fontFamily: "HelvNeue" });
		}
	}
}

function checkPrev(id,init)
{
	var control=$('#'+id+' .current').attr('ref')==$('#'+id).children().first().attr('ref');
	if (init)
	{
		control=control || $('#'+id+' .current').prev().attr('ref')==$('#'+id).find('div').first().attr('ref');
	}
	if (control)
	{
		if ($('#txt_prev a span').css('color')!="rgb(181, 181, 181)" || init)
		{
			$('#img_prev a img').attr('src','images/up_off.png');
			$('#txt_prev a span').html('PREVIOUS');
			$('#txt_prev a span').css('color','#B5B5B5');
			Cufon.replace('#txt_prev a span', {fontFamily: "HelvNeue" });
		}
	}
	else
	{
		if($('#txt_prev a span').css('color')!="rgb(51, 51, 51)" || init)
		{
			$('#img_prev a img').attr('src','images/up_on.png');
			$('#txt_prev a span').html('PREVIOUS');
			$('#txt_prev a span').css('color','');
			Cufon.replace('#txt_prev a span', {fontFamily: "HelvNeue" });
		}
		
	}
}

function loadDesign(toLoad)
{
	var imgW=0;
	if (toLoad.length)
	{
		var imgThumb=toLoad.attr('mini');
		toLoad.css('background-image','url('+imgThumb.replace('/design/','/design/mini/')+')');
//		var imgThumb=toLoad.attr('mini');
//		toLoad.css('background-image','url('+imgThumb+')');
		
//		$('#design_gallery .dg_elem.current').removeClass('current');
//		toLoad.addClass('current');
		
		$('#description').html('');
		
		var text_div=$('<div id="content_text"/>');
		
		
	//	$('#description').append(text_div);
		
		
		if(toLoad.attr('section')=='Creazioni')
		{
			var imgName=toLoad.attr('mini');
			$('#img_placeholder img:first').css('opacity','0.5');
			$('#img_placeholder img:first').attr('src',imgName);
			$('#img_placeholder img:first').load(function()
			{
				$('#img_placeholder img:first').css('opacity','1');
			});
			var overlayPage=Math.ceil((toLoad.index()+1)/8);
			$('<div class="simplePagerNav"> <a href="#" rel='+overlayPage+'></a></div>').find('a').click();
			$('#curr_page').html(overlayPage);
			if (overlayPage+1<=totPages)
			{
				$('#next_gallery_page a').attr('rel',overlayPage+1);
			}
			if (overlayPage-1>0)
			{
				$('#prev_gallery_page a').attr('rel',overlayPage-1);
			}
			var href=toLoad.find('a').attr('href').replace(/\&/gi,'%26');
			href=href.replace('design.html','');
			$('#footer_fb a').attr('href',fbBaseUrl+'creazioni.html'+href);
		//	Cufon.replace('#curr_page h1', {fontFamily: "HelvNeue"});
		}
		else
		{
			imgW=toLoad.attr('imgW');
			imgH=toLoad.attr('imgH');
			var img_div=$('<div id="content_img"/>');
			img_div.css('width',imgW);
			var img=$('<img src="'+toLoad.attr('mini')+'" alt=""/>');
            img_div.append(img);
			$.ajax({
			    url:'content/image/design/'+toLoad.attr('anno')+'_'+toLoad.attr('section').toLowerCase()+'.png',
			    type:'HEAD',

			    success:
			        function()
			        {
			    		var img_title=$('<img src="content/image/design/'+toLoad.attr('anno')+'_'+toLoad.attr('section').toLowerCase()+'.png" alt=""/>');
			    		img_div.prepend(img_title);
			        }
			});
			
	//		var img_title=$('<img src="content/image/design/'+toLoad.attr('anno')+'_'+toLoad.attr('section').toLowerCase()+'.png" alt=""/>');
			
			
			
			$('#description').prepend(img_div);
	//		img_div.html(toLoad.find('.design_description').text());
		}
		
		var last=$('#design_gallery .current');
		if (last.length)
		{
			changeThumbTextColorDesign(last,'remove');
			last.css('background-image','');
		}
		changeThumbTextColorDesign(toLoad,'add');
		
		
		text_div.html(toLoad.find('.design_description').html());
		
		if (imgW)
		{
			text_div.css('width',600-20-imgW-10);
		}
//		$('#content_text').append(toLoad.find('.design_description').html());
		
//		var tot=0;
//		$('#description').append(text_div);
//		text_div.append(toLoad.find('.design_description').html());
		
		$('#description').append(text_div);
		
//		var elemento = $('#description').jScrollPane();
//		var api=elemento.data('jsp');
		
//		api.reinitialise();
/*		$('#content_text').children().each(function(i,el)
		{
			var H;
			H=$(el).height();
			tot+=H;
			if (i+1==$('#content_text').children().length)
			{
				$('#content_text').css('height',tot);
				
			}
		});
	*/	
		
		
//		text_div.css('height',tot);
//		alert(tot);
		$(document).attr('title','Camparisoda - '+toLoad.attr('anno')+' - '+toLoad.attr('section')+' - '+toLoad.find('a').text());
//		_gaq.push(['_trackPageview', '/mailto/hello'])
		_gaq.push(['_trackPageview','/design/'+toLoad.find('a').text()]);
		checkPrev('design_gallery');
		checkNext('design_gallery');
//		$('#description').jScrollPane();
		return true;
	}
	return false;
}

function loadPhoto(toLoad)
{
	if (toLoad.length)
	{
		$('#heritage_gallery .hg_elem.current').removeClass('current');
		toLoad.addClass('current');
		
		$('#anno_box').html(toLoad.attr('anno'));
		$('#titolo_box').html(toLoad.attr('title'));
		
		Cufon.replace('#titolo_box,#anno_box', {fontFamily: "HelvNeue" });
		
		var imgName=toLoad.attr('ref');
		$('#img_placeholder img:first').css('opacity','0.5');
		$('#img_placeholder img:first').attr('src',imgName);
		$('#img_placeholder img:first').load(function()
				{
			$('#img_placeholder img:first').css('opacity','1');
				});
		var overlayPage=Math.ceil((toLoad.index()+1)/8);
	
		$('<div class="simplePagerNav"> <a href="#" rel='+overlayPage+'></a></div>').find('a').click();
		$('#curr_page').html(overlayPage);
		if (overlayPage+1<=totPages)
		{
			$('#next_gallery_page a').attr('rel',overlayPage+1);
		}
		if (overlayPage-1>0)
		{
			$('#prev_gallery_page a').attr('rel',overlayPage-1);
		}
		Cufon.replace('#curr_page', {fontFamily: "HelvNeue"});
		checkPrev('heritage_gallery');
		checkNext('heritage_gallery');
		$(document).attr('title','Camparisoda - Heritage - '+toLoad.attr('anno')+' - '+toLoad.attr('title'));
		_gaq.push(['_trackPageview','/photo/'+toLoad.attr('title')]);
		return true;
	}
	return false;
}

function loadVideo(toLoad)
{
	if (toLoad.length)
	{
		var imgThumb=toLoad.attr('thumb');
		toLoad.css('background-image','url('+imgThumb+')');
		$('#anno_box').html(toLoad.find('.elem_anno').text());
		$('#titolo_box').html(toLoad.find('.elem_titolo').text());
		
		Cufon.replace('#titolo_box,#anno_box', {fontFamily: "HelvNeue" });
		
		var ref=toLoad.attr('ref');
        
		$('video').remove();
        var newVideo=$('<video controls="controls"><source src=".mov"><!-- fallback --><p>Il tuo browser non supporta i video HTML5.</p></video>');
        if (!iphone)
        	newVideo.append('<source src=".ogg">'); 
        
		newVideo.find('source').each(function(i,src)
		{
			var res='';
			var srcsrc=$(src).attr('src');
			res+=ref+srcsrc.substring(srcsrc.lastIndexOf('.'));
			$(src).attr('src',res);	
		});
		$('#video').prepend(newVideo);

        $('video').attr('poster',imgThumb);

		var last=$('#media_gallery .current');
		if (last.length)
		{
			changeThumbTextColor(last,'remove');
			last.css('background-image','');
		}
		changeThumbTextColor(toLoad,'add');
		var overlayPage=Math.ceil((toLoad.index()+1)/9);
		$('<div class="simplePagerNav"> <a href="#" rel='+overlayPage+'></a></div>').find('a').click();
		$('#curr_page').html(overlayPage);
		if (overlayPage+1<=totPages)
		{
			$('#next_gallery_page a').attr('rel',overlayPage+1);
		}
		if (overlayPage-1>0)
		{
			$('#prev_gallery_page a').attr('rel',overlayPage-1);
		}
		Cufon.replace('#curr_page', {fontFamily: "HelvNeue"});
		checkPrev('media_gallery');
		checkNext('media_gallery');
		$('#video').show();
		$(document).attr('title','Camparisoda - Film - '+toLoad.find('.elem_anno').text()+' - '+toLoad.find('.elem_titolo').text());
		_gaq.push(['_trackPageview','/photo/'+toLoad.find('.elem_titolo').text()]);
        
        
		return true;
	}
	else
		return false;
}

function loadVideoPiacere(toLoad)
{
	if (toLoad.length)
	{
		//var imgThumb=toLoad.attr('thumb');


		var ref=toLoad.attr('ref');

		$('video').remove();
        var newVideo=$('<video controls="controls">				<source src=".m4v">				<source src=".ogg">                <!-- fallback -->                <p>Il tuo browser non supporta i video HTML5.</p>			</video>');

		newVideo.find('source').each(function(i,src)
		{
			var res='';
			var srcsrc=$(src).attr('src');
			res+=ref+srcsrc.substring(srcsrc.lastIndexOf('.'));
			$(src).attr('src',res);
		});
		$('#video').prepend(newVideo);

        //$('video').attr('poster',imgThumb);


		$('#video').show();

		_gaq.push(['_trackPageview','/videoPiacere/'+newVideo.find('source:first').src()]);

		return true;
	}
	else
		return false;
}

function changeThumbTextColorDesign(thumb,ev)
{
//	var titolo=thumb.find('h1:first');
//	var color='';
//	titolo.html('<a href="'+thumb.find('a').attr('href')+'">'+titolo.text()+'</a>');

	if (ev=='add')
	{
		//color="white";
		//thumb.find('.helvneue a').css('color','white');
		thumb.addClass('current');
	}
	if (ev=='remove')
	{	
//		color="";
		//thumb.find('.helvneue a').css('color','');
		thumb.removeClass('current');
	}
/*	var opt={};
	if (color!='')
	{
		opt['color']=color;
	}
	opt['fontFamily']="HelvNeue";
	Cufon.replace('#'+$(thumb).attr('id')+' .helvneue:first', opt);
	*/
}

function changeThumbTextColor(thumb,ev)
{
	var anno=thumb.find('.elem_anno');
	anno.html(anno.text());
	var titolo=thumb.find('.elem_titolo');
	titolo.html(titolo.text());
	if (ev=='add')
	{
		thumb.css('color','white');
		thumb.addClass('current');
	}
	if (ev=='remove')
	{	
		thumb.css('color','');
		thumb.removeClass('current');
	}
	Cufon.replace('.mg_elem[ref='+titolo+'] .elem_anno,.mg_elem[ref='+titolo+'] .elem_titolo', {fontFamily: "HelvNeue" });
}
function getSelectedValue(selector)
{
    return $("#"+selector).find("dt a span.value").html();
}

function createDropDown(selectId)
{
    var source = $("#"+selectId);
    var selected = source.find("option[selected]");
    var options = $("option", source);

    var dl=$('<dl id="'+selectId+'" class="dropdown"></dl>');
    if (source.hasClass('mini'))
    {
    	dl.addClass('mini');
    }
    
    if (selected.text()=="")
        selected= source.find('option:first');
    if (source.hasClass('mini'))
    {
    	var tmp=selected.html().split(';');
    	dl.append('<dt><a href="#"><span id="anno">' + tmp[0] + '</span><span id="titolo">' + tmp[1] + '</span><span class="value">' + selected.val() + '</span></a></dt>');
    }
    else
    {
    	dl.append('<dt><a href="#">' + selected.html() + '<span class="value">' + selected.val() + '</span></a></dt>');
    }
    
    dl.append('<dd><ul></ul></dd>');
//'+$(this).find('img').parent().html()+'
    options.each(function()
    {
    	var string="";
    	if (source.hasClass('mini'))
    	{
    		var tmp=$(this).html().split(';');
    		string=tmp[0];
    	}
    	else
    		string=$(this).html();
        $("ul",dl).append('<li><a href="#">' +
            string + '<span class="value">' +
            $(this).val() + '</span></a></li>');
    });
    source.parent().prepend(dl);
    source.remove();
    
    $("#"+selectId+".dropdown dt a").live('click',function()
    {
        $("#"+selectId+".dropdown dd ul").toggle();
        
    });

    $("#"+selectId+".dropdown dd ul li a").live('click',function()
    {
        var text = $(this).find('cufontext:first').text();
        if ($("#"+selectId).hasClass('mini'))
        {
        	var tmp = $(this).find('.value cufontext').text().split(';');
        	text='<span id="anno">' + tmp[0] + '</span><span id="titolo">' + tmp[1] + '</span>';
        }
        text=text+'<span class="value">'+text+'</span>';
        
        $("#"+selectId+".dropdown dt a").html(text);
        $("#"+selectId+".dropdown dd ul").hide();
        $("#"+selectId+".dropdown dt").change();
        if ($("#"+selectId).hasClass('mini'))
        {
        	Cufon.replace('#titolo,#anno', {fontFamily: "HelvNeue" });
        }
        else
        	Cufon.replace('.dropdown dt a', {fontFamily: "HelvNeue"});
    });
}

function createDropDownMod(selectId)
{
    var source = $("#"+selectId);
    var selected = source.find("a[selected]");
    var options = $("a", source);

    var dl=$('<dl id="'+selectId+'" class="dropdown"></dl>');
    
    if (selected.text()=="")
        selected= source.find('li:first');

   	dl.append('<dt><a href="#">' + selected.text() + '<span class="value">' + selected.text() + '</span></a></dt>');

    
    dl.append('<dd><ul></ul></dd>');
//'+$(this).find('img').parent().html()+'
    options.each(function()
    {
    	var string="";
   		string=$(this).html();
        $("ul",dl).append('<li><a href="#">' + string + '<span class="value">' + $(this).html() + '</span></a></li>');
    });
    source.parent().prepend(dl);
    source.remove();
    
    $("#"+selectId+".dropdown dt a").live('click',function()
    {
        $("#"+selectId+".dropdown dd ul").toggle();
        
    });

    $("#"+selectId+".dropdown dd ul li a").live('click',function()
    {
        var text = $(this).find('cufontext:first').text();
        if ($("#"+selectId).hasClass('mini'))
        {
        	var tmp = $(this).find('.value cufontext').text().split(';');
        	text='<span id="anno">' + tmp[0] + '</span><span id="titolo">' + tmp[1] + '</span>';
        }
        text=text+'<span class="value">'+text+'</span>';
        
        $("#"+selectId+".dropdown dt a").html(text);
        $("#"+selectId+".dropdown dd ul").hide();
        $("#"+selectId+".dropdown dt").change();
        if ($("#"+selectId).hasClass('mini'))
        {
        	Cufon.replace('#titolo,#anno', {fontFamily: "HelvNeue" });
        }
        else
        	Cufon.replace('.dropdown dt a', {fontFamily: "HelvNeue"});
        return false;
    });
}

function setCenter(elem,win,callback,position)
{
		var center={};
		var myH=elem.outerHeight();
		var myW=elem.outerWidth();
//		alert(myH);
//		alert(myW);
		var padreH=win.height();
		var padreW=win.width();
		center.h=padreH/2-myH/2;
		center.w=padreW/2-myW/2;
		if (position!='top') position='bottom';
		elem.css(position,center.h+'px');
		elem.css('left',center.w+'px');
		if(typeof callback == 'function')
		{
	        callback.call();
	    }
		return center;
}

function posBg(){
    
    var scartoLeft = (($('#background').attr('w')-$(window).width()))/2;
    // se immagine piu larga
    //if (scartoLeft >= 0){
        //la centro in larghezza
        //$('#background').css('left',-2*scartoLeft);
    //}

    var scartoTop = (($('#background').height()-$(window).height())/2);
    // se immagine piu alta
    //if (scartoTop >= 0){
        //$('#background').height('100%');
        //la centro in altezza
        //$('#background').css('top',-scartoTop);
    //}
    //else if (scartoLeft >= 0){
            //la centro in larghezza
            //$('#background').css('left',-2*scartoLeft);
        //}
    //}
    
}

function reimposta()
{
	//$(window).height($(window).height()+60);
	
	docH=$(window).height();
	docW=$(window).width();
	
	//$('#logo').height(docH);

//	$('#background').css('bottom','-240px');
	if (iphone)
	{
		hideURLbar();
	}
    $('body').css('height',docH);
    

	
}

function homeAnimation(){
    $('#red_sign,#triangolo,#bottiglia,#age,#play_video,#menu,#tappo,#menu_row,#menu_window,#button_menu,#right_arrow,#left_arrow').addClass('top');
    $('#age_msg').removeClass('top');
}

function fixArrow(menu_move){
    if(menu_move < parseInt($('.menu_item').length - parseInt($('#menu_window').width() / $('.menu_item').outerWidth())))
        $('#right_arrow').css('background-image','url("images/dx_menu_on.png")');
    else
        $('#right_arrow').css('background-image','url("images/dx_menu_off.png")');

    if(menu_move > 0)
        $('#left_arrow').css('background-image','url("images/sx_menu_on.png")');
    else
        $('#left_arrow').css('background-image','url("images/sx_menu_off.png")');
}

function pulsateMenu(obj){
    $(obj).toggleClass('pulsate');    
    setTimeout(function(){pulsateMenu(obj)},1000);
}


$(document).ready(function(){
	
    Cufon.replace('.helvneue', {fontFamily: "HelvNeue"});
	Cufon.replace('.gotham', {fontFamily: "Gotham"});
    Cufon.replace('.helvneue h1', {fontFamily: "HelvNeue"});
	Cufon.replace('.gotham h1', {fontFamily: "Gotham"});
    Cufon.replace('.helvneue h2', {fontFamily: "HelvNeue"});
	Cufon.replace('.gotham h2', {fontFamily: "Gotham"});
    Cufon.replace('.helvneue h3', {fontFamily: "HelvNeue"});
	Cufon.replace('.gotham h3', {fontFamily: "Gotham"});

	var ua = navigator.userAgent,
	myEvent = (ua.match(/iPad/i)) ? "touchstart" : "click";
	
	docH=$(window).height();
	docW=$(window).width();

    reimposta();
    

    $('#background').load(function(){
        $(this).attr('w',$(this).attr('width'));
        $(this).attr('h',$(this).attr('height'));
        //e io li rimuovo
        $(this).removeAttr('width');
        $(this).removeAttr('height');
        /*
        //conversione dell'img in div con sfondo
        $(this).after($('<div id="bg" />'));
        $('#bg').css('height',docH);
        $('#bg').css('width',docW);
        $('#bg').css('background-image','url('+$(this).attr('src')+')');
        $(this).remove();
        */
        posBg();
    });

    $('#button_menu').click(function() {
        window.location="homepage.html";
        //$('#menu,#menu_row,#menu_window,#button_menu,#right_arrow,#left_arrow').toggleClass('top');
    });

    var menu_move = 0;
    fixArrow(menu_move);

    $('#right_arrow').click(function() {
        if(menu_move < parseInt($('.menu_item').length - parseInt($('#menu_window').width() / $('.menu_item').outerWidth()))){
            $('#menu_row').animate({'left' : parseInt($('#menu_row').css('left'))-$('.menu_item').outerWidth()});
            menu_move++;
            fixArrow(menu_move);
        }
    });

    $('#left_arrow').click(function() {
        if(menu_move > 0){
            $('#menu_row').animate({'left' : parseInt($('#menu_row').css('left'))+$('.menu_item').outerWidth()});
            menu_move--;
            fixArrow(menu_move);
        }
    });
    
//	$('*').load(function(){	
	
        $(window).resize(function(){
            reimposta();
            fixArrow(menu_move);            
        }); // RESIZE PAGINA

        // Tell Safari not to move the window.
        //$('body').bind('touchmove', function(event){ event.preventDefault(); });
/*
        window.onorientationchange = function(){
            reimposta();            
        }; // CAMBIO ORIENTAMENTO DISPOSITIVI MOBILE
*/
  //  });
	
	$('#sub_menu_media_sel').live('change',function()
	{
		var a={};
		a['FILM']="?section=film";
		a['HERITAGE']="?section=heritage";
/*		a['DESIGN']="design.php";
		a['CONCEPT']="concept.php";
		a['CREAZIONI']="architettura.php";
*/		var myLoc;
		myLoc=window.location.pathname.replace('#','');
		myLoc=myLoc.substring(myLoc.lastIndexOf('/')+1);
//		alert(myLoc);
		var loc=a[getSelectedValue('sub_menu_media_sel')];
		if (myLoc!=loc)
			window.location=loc;
	});
	
	$('#freccia,#freccia_left,#freccia_right').live('click',function()
	{
		if ($(this).attr('id')=='freccia_left')
		{
			$(this).parent().find('#sub_menu_design_sel dt a').click();
		}
		else
			if ($(this).attr('id')=='freccia_right')
		{
			$(this).parent().find('#box_section_sel dt a').click();
		}
		else
		{
			$(this).parent().find('dt a').click();
		}

	});
    
});

