/***
  @author: Luca Capra <luca.capra@7loop.com>
  This code is released under a Creative Common Share-a-like license.
*/

var App = {fx: [], conf: {}};
var app_loader = function($) { for(var i in App.fx){ /*console.log(i);*/ App.fx[i]($); }};
jQuery( app_loader );
//////////////////////////

App.fx.bannerize = function($)
{

  var banner = $("#banner");
  if(!banner.size() || banner.hasClass("processed")) return;

  App.conf['banners'] = [];

  $(".banner a", banner).each(function(){

		var img = $("img", this);
    var src = img.attr("src");
    App.conf.banners.push( {

      ref: this,

      title: $(this).attr("title"),
      href: $(this).attr("href"),

      src: src,
      width: img.width(),
      height: img.height()
    });

    $(this).parent().hide();

  }).colorbox();


  var _slide = function( i )
  {
    container_height = 100; // CSS!
    timeout = 15000;
    curr = App.conf.banners[i];

    if($("#promo_slide").size())
      $("#promo_slide").remove();

    var div = $("<div id='promo_slide' style='background-position:0px 0px;'><a href='#'><img src='/images/spacer.gif' width='"+curr.width+"' height='"+curr.height+"' /></a></div>");
    div
      .prependTo("#banner");

    div
      .css({
        backgroundImage: "url("+curr.src+")",
        backgroundRepeat: "no-repeat"
      });

    div
      .animate({ backgroundPosition: "(0px -"+(curr.height - container_height)+"px)" }, {
        duration: timeout,
        complete: function(){
          
          i++;
          
          if(i == App.conf.banners.length)
            i = 0;
          
//           console.log(i);
          
          _slide( i );
        }
      })

      .find("a")
        .bind("mouseover mouseenter", function(){
//           console.log( $(curr.ref).parent() );
          $(curr.ref).parent()
          .css({
            position: "absolute",
            zIndex: 100,
            top: $("#banner").offset().top,
            left: $("#banner").offset().left
          }).show().bind("mouseout mouseleave", function(){
            $(this).hide()
          });
        })
        .click(function(){
          document.location = curr.href;
          return false;
        })
      ;

//       console.log( curr );




  };

  if(App.conf.banners.length > 0)
  {
    _slide( 0 );
  }

  banner.addClass("processed");

};


App.fx.mappa = function($)
{

  var mappa = $("#mappa_slice");
  if(!mappa.size() || mappa.hasClass("processed")) return;

  var sedi = $("div.sedi");

  sedi.hide();
  sedi.eq(0).fadeIn(600);
	
  $(".map-link").hoverIntent({
   over: function(){
		
		$("a.map-link.selected").removeClass("selected");
		$(this).addClass("selected");
		
    var lnk = $($(this).attr("href"));

    if(lnk.size()){
      sedi.hide();
      lnk.fadeIn(600);
    }
    return false;
  }
  , timeout: 300
  , out: function(){
//       sedi.show();
    }
  }).click(function(e){ return false; });

  $("div.sedi span.map a").click(function(){

    var iframestr = "<iframe style='z-index: 100; width: 100%; height: 100%;' src='"+
                              $(this).attr('href') + "&output=embed'></iframe>";
    var iframe = $("<div id='sede-map' style='z-index: 10'>"+ iframestr +"</div>");

    iframe
      .dialog({
        title: $(this).parent().parent().prev("h2").text()
        , width: 640
        , height: 480
        , zIndex: 80
      });

    return false;
  });

  if(document.location.hash )
  {
    try{
      if($(document.location.hash).size())
      {
        var link = $(document.location.hash);
        if(link.size()){
          $("#sedi .sedi").hide();
          link.show();  
        }
      }
    }
    catch(e){}
  }
  
  
  mappa.addClass("processed");
  
};

App.fx.patenti = function($)
{

  var patenti = $("#patenti");
  if(!patenti.size() || patenti.hasClass("processed")) return;

  var patenti_list = $("div.patente", patenti);

  patenti_list.hide().eq(0).show();

  var onclick=function()
  {
//     console.log($("a",this).attr('href'));
		var codpat = $("a", this).attr('href').substr(1);
    patenti_list.hide();
    $( 'h3#'+ codpat ).parent().fadeIn( 300 );

		var fotocont = $( 'h3#'+codpat ).parent().find(".veicoli.patenti."+codpat);
		if( (codpat.length == 1 || codpat == "patentino") && !fotocont.size())
		{
			$.get("/veicoli", function(data){
// 				console.log( codpat );
				
				var html = [ "<div class='veicoli patenti ", codpat ,"'>", $("div.veicoli.patente."+codpat, $(data)).html(), "</div>"].join('');
// 				console.log( html );
				
				$( 'h3#'+codpat ).parent().append(html);
			});
			

		}

    return false;
  }

  var patenti_links = $("div.patenti-list > ul > li", patenti);

  patenti_links.each(function(){

    var patenti_sublinks = $("ul li", this);
    patenti_sublinks.click(onclick).hide();

  }).click(onclick);

  var p_show = function(){
    var patenti_sublinks = $("ul li", this);
    patenti_sublinks.fadeIn( 200 );
  };

  patenti_links.hoverIntent({
    timeout: 200,
    over: p_show,
    out:function(){
      var patenti_sublinks = $("ul li", this);
      patenti_sublinks.fadeOut( 200 );
    }
  });

//   console.log(document.location);
  if(document.location.hash )
  {
    try{
      if($(document.location.hash).size())
      {
        var link = $(".patenti-list li a[href='"+document.location.hash+"']");
        if(link.size()){
//           console.log(link);
          link.trigger( "click" );
        }
      }
    }
    catch(e){}
  }
  
  patenti.addClass("processed");
  
};


App.fx.promos = function($)
{


  var promos = $("div.promos");
  if(!promos.size() || promos.hasClass("processed")) return;

  $("a.colorbox").colorbox({ title: function(){
    var title = "";
    try{
      title = $(this).attr("title");
      if(!title || title == '')
        title = $("img", this).attr("alt");
    }catch(e){
      title = "Promozione";
    }

    return title;

  } });

  promos.addClass("processed");
  
};

App.fx.homepage = function($)
{
  
  var home = $("#home-promo");
  if(!home.size() || home.hasClass("processed")) return;

  App.conf.selections = {};

  var _meta = {
    patenti: { 
      selector: "#patenti",
      description: "Seleziona una patente cliccando sulla categoria d'interessa e premi continua.",
      cb: function(){
          
          $("#patenti .patenti-list li a").bind("click", function(){

            setTimeout(function(){
              $("#home-promo").animate({height: ($("#patenti").height() + 50) }, 300);
              $("#page-content").animate({height: ($("#patenti").height() + 160)}, 100);
            }, 10);

            
          }).trigger("click");

          $("#patenti .patenti-list li a").bind("click", function(){
            App.conf.selections.patente = $($(this).attr('href')).text();
          });
          
      }
    }
    ,iscrizioni: {
      selector: "#iscrizioni",
      description: "I documenti richiesti per avviare le procedure di iscrizione alla patente di guida.",
      cb: function(){}
    }
    ,sedi: {
      selector: "#sedi_autoscuola",
      description: "Seleziona la sede più vicina a te per rendere più agevole l'accesso alla struttura ed ai corsi.",
      cb: function(){
        
        $("#mappa_slice").hide();

        setTimeout(function(){
          $("#home-promo").animate({height: ($("#sedi_autoscuola").height() + 150) }, 300);
          $("#page-content").animate({height: ($("#sedi_autoscuola").height() + 260)}, 100);
        }, 10);

        $($("#sedi_autoscuola a.map-link")).bind("click", function(){
          App.conf.selections.sede = $(this).attr("href").substr(1);
        });
        
      }
    }
    , contattaci: {
      selector: "#ContactAddForm",
      description: "Non perdere tempo! Inviaci subito la tua candidatura o la tua domanda.",
      cb:function(){
        setTimeout(function(){
          $("#home-promo").animate({height: ($("#ContactAddForm").height() + 50) }, 300);
          $("#page-content").animate({height: ($("#ContactAddForm").height() + 160)}, 100);
        }, 10);

        $(".home-gonext, .home-gonext-btn").remove();

//         console.log(App.conf.selections);

        var selz = App.conf.selections;
        var selid = "#ContactInteressatoA";
        if(selz.patente && $(selid).size())
          $(selid).val( selz.patente );

        var capitaliseFirstLetter = function (string)
        {
            return string.charAt(0).toUpperCase() + string.slice(1);
        }


        selid = "#ContactSedeDi";
        if(selz.sede && $(selid).size()){
//           console.log(capitaliseFirstLetter(selz.sede));
          $(selid).val(capitaliseFirstLetter(selz.sede));
//           $(selid).find("option").each(function(){
//             console.log($(this).text().toLowerCase(), selz.sede);
//             if($(this).text().toLowerCase() == selz.sede)
//               $(this).attr("seleceted", "seleceted");
//           });
        }
      }
      ,last: true
    }

// per la tua patente
    
    , recupero_punti: {
      selector: "#recupero-punti",
      description: "Se sei a corto di punti patente, l'autoscuola Alba offre corsi di recupero punti per tutte le esigenze.",
      cb:function(){

        setTimeout(function(){
          $("#home-promo").animate({height: ($("#recupero-punti").height() + 50) }, 300);
          $("#page-content").animate({height: ($("#recupero-punti").height() + 160)}, 100);
        }, 10);

        $(".home-gonext, .home-gonext-btn").remove();

        }
        ,noButtons: true
//       ,last: true
    }

    , rinnovo: {
      selector: ".pratica:eq(0)",
      description: "La patente stà per scadere? Ecco come fare.",
      cb:function(){

        setTimeout(function(){
          $("#home-promo").animate({height: ($(".pratica").height() + 50) }, 300);
          $("#page-content").animate({height: ($(".pratica").height() + 160)}, 100);
        }, 10);

        $(".home-gonext, .home-gonext-btn").remove();

        }
      ,noButtons: true
//       ,last: true
    }
    , smarrimento: {
      selector: ".pratica:eq(2)",
      description: "Le procedure da seguire in caso di smarrimento della patente.",
      cb:function(){
        
        setTimeout(function(){
          $("#home-promo").animate({height: ($(".home-content .pratica").height() + 120) }, 300);
          $("#page-content").animate({height: ($(".home-content .pratica").height() + 220)}, 100);
        }, 100);

        $(".home-gonext, .home-gonext-btn").remove();

      }
      ,noButtons: true
//       ,last: true    
    }
    ,conversioni: {
      selector: ".pratica:eq(3)",
      description: "Assistenza e consigli per la conversione della patente.",
      cb:function(){

        setTimeout(function(){
          $("#home-promo").animate({height: ($(".home-content .pratica").height() + 50) }, 300);
          $("#page-content").animate({height: ($(".home-content .pratica").height() + 160)}, 100);
        }, 100);

        $(".home-gonext, .home-gonext-btn").remove();

      }
      ,noButtons: true
//       ,last: true
    }
  };
  
  var li_a_list = $( "ul li a" , home);
  li_a_list.click(function(){
    
    var sec_title = $(this).text();
    var sec_description = "";
    
    $("div.welcome").hide();
    li_a_list.removeClass("active");
    $(this).addClass("active");
    
    var imeta = $(this).attr("_meta");
    imeta = _meta[ imeta ];
    
    if(imeta.description)
      sec_description = imeta.description;
    
    if(!imeta)
    {
      return true;
    }
    
    var jqurl = $(this).attr('href') +" "+ imeta.selector;
//     console.log(jqurl);
    var nextBtnClick = function(){

      if(imeta.next)
        imeta.next();

      var i=0;
      while(!li_a_list.eq(i).hasClass("active"))
        i++;
          
      li_a_list.eq(i+1).trigger("click");
    };

    if(!imeta.noButtons)
    {
      var nextBtn1 = $("<div class='home-gonext'><button class='home-gonext-btn'>Continua »</button></div>")
          .click(nextBtnClick);
      var nextBtn2 = $("<div class='home-gonext'><button class='home-gonext-btn'>Continua »</button></div>")
          .click(nextBtnClick);
    }
    
    
    
    var container = $("div.home-content div.div-content", home);
    container.load( jqurl, function(){
           
      
      if(imeta.cb)
        imeta.cb();
      
      app_loader($);

      $("<div class='intro-sec'><h1>"+sec_title+"</h1><div class='sec_description'>"+sec_description+"</div></div>").prependTo(container);
      
      if(!imeta.last && !imeta.noButtons){
        nextBtn1.prependTo(container);
        nextBtn2.appendTo(container);
      }
    
//       $("#selection_navi").remove();
//       
//       var sel_navi = $("<div id='selection_navi'></div>")
//         .append("<ol></ol>");
//       
//       if(App.conf.selections.patente)
//         sel_navi.append(["<li rel='patente'>", App.conf.selections.patente, "</li>"].join(''));
//       if(App.conf.selections.sede)
//         sel_navi.append(["<li rel='sede'>", App.conf.selections.sede, "</li>"].join(''));
//       
//       sel_navi.prependTo(container);
//       
//       console.log( App.conf.selections );
      
      return false;
    } );
    
    return false;
    
  });

  home.addClass("processed");

};


App.fx.domande_frequenti = function($)
{
  if(!$("#domande-frequenti").size() || $("#domande-frequenti").hasClass("processed")) return;

  $(".faq .r").hide();

  $(".faq .d")
    .css({
      cursor: "pointer"
    })
    .click(function(){

    $(this).next().toggle();

  });

  $("#domande-frequenti").addClass("processed");

}

App.fx.foto_veicoli = function($)
{
  var fveic = $("#veicoli:not(.processed)");
  if(!fveic.size()) return;

//   $(".foto").hide();
  
//   $(".patente").hoverIntent({
//     timeout: 300
//     , over: function(){
//       $(".foto", this).css({
//         position: "absolute",
//         backgroundColor: "black",
//         left: ($(this).offset().left + 50),
//         zIndex: 100
//       }).toggle(200);
//     }
//     , out: function(){
//       $(".foto", this).toggle(200);
//     }
//   });
  
  fveic.addClass("processed");

};

var slidetimeout, slidecounter=1;
App.fx.homepage_slider = function($)
{
  var slide = $("#home-promo div.foto-slide:not(.processed)");
  if(!slide.size()) return;
	
	var slidelist = $(".slide-foto", slide);
  slidelist.hide().eq(0).show();
	
// 	console.log(slide.offset().top);
	slidelist.css({
		position: "relative",
		top: "-300px",
		zIndex: 10
	});
	
	slide.prepend("<div class='slide-deco'><div>&nbsp;</div></div>");
	
	var do_slide = function(i){	
		
		var prev=slidelist.eq(i-1);
		prev.fadeOut(300);
		
		slidelist.eq(i).fadeIn(600);
	};
	
	var go_next = function()
	{
		if(slidecounter == slidelist.length ) slidecounter=0;

		do_slide( slidecounter );
		slidecounter++;

	}

	slidetimeout = setInterval( function(){ go_next(); }, 5000 );
	
	slide.click(function(){
		clearInterval( slidetimeout ); 
		go_next();
		slidetimeout = setInterval( function(){ go_next(); }, 5000 );
	});
	
  slide.addClass("processed");
};

App.fx.news_slider = function($)
{
  var news = $("#news-scroller:not(.processed)");
  if(!news.size()) return;
	
	var newslist = $(".news", news);	
	
	
	App.conf['news_slider'] = 0;
	var go_next = function(){
		App.conf.news_slider++;
		if(App.conf.news_slider == newslist.length)
		{
			news.animate({ top: "0px"});
			App.conf.news_slider = 0;
		}
  
  	var cnews = newslist.eq(App.conf.news_slider);
// 		console.log(cnews, cnews.offset().top);
		news.animate({ top: (news.offset().top - cnews.offset().top) + "px" }, 500);
	};
	
	setInterval( go_next, 8000 );
	
	news.addClass("processed");
};
