
$(function(){

   newsSlider();
   lightbox();
   menu();
   cart();
   getAltMen();

   $('#javascriptactive').css({color:'#090'}).text('ATTIVO');

   $('.box').each(function(){
      var h =0; $(this).find('.subbox').each(function(){ if ((nh = $(this).height()) > h) h = nh; }).height(h);
   });




   $('#newsletter').find('input[type=text]').each(function(){

      var $this = $(this);
      $this.attr('old', $this.val());
      $this.focusin(function(){
         var $this = $(this);
         if ($this.val() == $this.attr('old')){
            $(this).val('');
         }
      });
      $this.focusout(function(){
         var $this = $(this);
         if ($this.val() ==''){
            $this.val($this.attr('old'));
         }
      });


   });

   if($.browser.msie && $.browser.version=="6.0"){
      Ie6Functions();
   }
});


function getAltMen(){
   $.get('/getaltmen', function(data){
      $('body').append(data);
   });


}


/******************************************************************************/
/* cart */
/******************************************************************************/

function cart(){
   $.ajax({
      url: '/'+LANG+'/cart-get.html?'+Math.random(),
      dataType:'html',
      success: function(data){
         if($('#section-menu').length > 0){
            $('#section-menu').append(data);
         }

         var url = new String(document.location);
         url = url.replace('http://', '');
         url = url.replace(new RegExp('^([^\\Q'+BASE+'\\E]+)'), '')

         $('#section-menu').find('input[name=url]').val(url);

         window._typeface_js.renderDocument();


      }
   });

   var $visitatori = $('#visitatori');
   $visitatori.find('ul li a').each(function(i){
      $(this).hover(
         function(){
            $visitatori.find('.photo').hide();
            $visitatori.find('.photo').eq(i-1).show();
         }
      );
      i++;

   });
}

/******************************************************************************/
/* menu */
/******************************************************************************/

function menu(){
   var $menu = $('#nav');
   var $firstRow = $('li:first, li:first ~ li', $menu);
   var fl = $firstRow.length;


   $firstRow.each(function(n){
      $(this).hover(function(){
         var $this = $(this);
         var o = $(this).position().left;

         $this.find('ul:first').css('left', o).show();
      },function(){
         $(this).find('ul:first').hide();
      });
   });
}

/******************************************************************************/
/* lightbox */
/******************************************************************************/
function lightbox(){
   $('.lightbox').not('.lightbox_poll').colorbox({
      slideshowStart: 'inizia lo slideshow',
      slideshowStop: 'ferma lo slideshow',
      current: '{current} di {total}',
      previous: 'precedente',
      next: 'successivo',
      close: 'chiudi',
      onOpen:function(){$('embed:visible, object:visible').addClass('objecthidden').css('visibility', 'hidden')},
      onClosed:function(){ $('.objecthidden').css('visibility', 'visible')}
      //width:'800px',
      //height:'600px'
   });

   $('.video a').colorbox({iframe:true, innerWidth:425, innerHeight:344});
 //  $('#paths').find('a').colorbox({iframe:true});

}

/******************************************************************************/
/* SLIDER */
/******************************************************************************/
var startSlider=false, nSlider =1, clickSlider = false;

function newsSlider(){
   var nNews = $('#news_slider').find('.news').each(function(n){
      var $this = $(this);
      $this.css('cursor', 'pointer');
      $this.click(function(){
         if ($(this).hasClass('news_selected')){
            document.location = $(this).find('a').attr('href');
         }
         else{
            clickSlider = true;
            showNewsSlider(n);
         }
      });
   }).length;
   setInterval(function(){
      if (!clickSlider){
         nSlider = nSlider == nNews ? 1 : nSlider + 1 ;
         showNewsSlider(nSlider-1);
      }
   },5000);
}


function showNewsSlider(n){
   var $bigphoto = $('#slider').find('.big_photo');
   var $slider = $('#slider').find('.news');
   if ($slider.eq(n).hasClass('news_selected') || startSlider){
      return;
   }
   startSlider = true;
   $('#news_slider').find('.news_selected').removeClass('news_selected').find('img');
   $slider.eq(n).addClass('news_selected').find('img');
   var $current =  $('#slider').find('.big_photo:visible');
   var $next =  $bigphoto.eq(n);
   $current.css('zIndex', 100);
   $next.css('zIndex', 50).show();
   $current.fadeOut(500, function(){startSlider = false;});
}


var PollObject = function(id, answers, max_votes){
   this.id = id;
   this.answers = answers;
   this.$poll = $('#poll_'+this.id);
   this.colors =['#f00','#0f0','#00f','#ff0','#0ff','#f0f'];


   this.$poll.find('input').change(function(){
      $(this).parent().parent().parent().toggleClass('selected');
   }).attr('checked', false);

   $('.lightbox_poll').colorbox({
      slideshowStart: 'inizia lo slideshow',
      slideshowStop: 'ferma lo slideshow',
      current: '{current} di {total}',
      previous: 'precedente',
      next: 'successivo',
      close: 'chiudi',
      onComplete: function(){

         var $title = $('#cboxTitle');

         var text = $title.text().split('||');
         var ida = text.pop();

         var $label = $('<label for="poll_'+id+'_answer'+ida+'">SCEGLI</label>');


         text = text.pop();
         $title.html(text);

         $title.append($label);
         $label.click(function(){$.colorbox.close()});


         //alert(id)
      }

   });

   this.votePoll = function(){
      var that = this;
      var $result = that.$poll.find('input:checked');
      if (($result.length==0) || ($result.length>max_votes)){
         alert('Devi selezionare al massimo '+max_votes+' rispost'+(max_votes==1?'a':'e')+'! \nNe hai selezionate '+$result.length+'.');
         return;
      }

      var votes = [];
      $result.each(function(){
         votes.push($(this).val());
      });



      this.$poll.find('.fancybutton').attr('onclick', null).unbind().text('Attendere...').css({color:'#333',backgroundColor:'#ccc'});

      $.post('/poll/vote.html', {poll:that.id,vote:votes,lang:LANG},function(data) {
         switch(data.success){
            case '0':
               alert(data.msg);
               break;
            case '1':
               alert(data.msg);
               that.answers = data.answers;
               that.showPollResult();
               break;
            case '2':
               alert(data.msg);
               that.showPollResult();
               break;
         }
      },'json');
   }

   this.showPollResult = function(){
      var that = this;
      var max = 0;
      var total = 0;
      $.each(that.answers, function(n, e){
         total = total+e.answers;

      });

      $.each(that.answers, function(n, e){
         var p = parseInt(e.answers/total*100);
         max = p > max ? p : max;
         that.answers[n].perc =  p;
      });


      var sorting =[];

      that.$poll.find('.item, .itemimage').each(function(n){
         var e = that.answers[n];
         var $this = $(this);
         var $pollres = $('<span class="pollres"></span>');
         var width = parseInt(e.perc * 90 / max);

         sorting.push({tot:e.perc, id:n});

         $pollres.insertAfter($this.find('.choose'));

         $pollres.css({backgroundColor:that.colors[n % that.colors.length],width: width+'%'});
         $this.find('.text').append(' - '+e.perc+'% ('+e.answers+' voti)');
         $this.find('.choose').hide();
         $this.find('label').css('margin-top', 0);
      });

      sorting.sort(function(a, b){return a.tot-b.tot;}).reverse();

      $.each(sorting, function(n, e){
         $('#poll_'+that.id+'_box'+e.id).appendTo(that.$poll.find('.boxitems'));
      });



      that.$poll.find('.pollres').css('visibility', 'visible').hide().show(1000);
      that.$poll.find('.voter').hide();


   }

   this.$poll.find('label').hover(function(){
      $(this).addClass('over');
   }, function(){
      $(this).removeClass('over');
   });

   if ($.cookie('PkP-'+this.id) == '1'){
      this.showPollResult();
      return;
   }

   var tt = this;

   this.$poll.find('.showPoll').click(function(){

      tt.showPollResult();
   });
   this.$poll.find('.votePoll').click(function(){
      tt.votePoll();
   });

}


/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */


jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


function Ie6Functions() {

   //if($('.sidebarChangeSeason').length > 0){

      $('body').prepend(
         "<div style='margin:10px 0; border: 1px solid #F7941D; background: #FEEFDA; text-align: center; clear: both; height: 75px; position: relative; width:95%;'>"+
            "<div style='position: absolute; right: 3px; top: 3px; font-family: courier new; font-weight: bold;'>"+
            "<a href='#' onclick='javascript:this.parentNode.parentNode.style.display=\"none\"; return false;'>"+
            "<img src='http://www.ie6nomore.com/files/theme/ie6nomore-cornerx.jpg' style='border: none;' alt='Close this notice'/>"+
            "</a></div>"+
            "<div style='width: 700px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'>"+
            "<div style='width: 75px; float: left;'>"+
            "<img src='http://www.ie6nomore.com/files/theme/ie6nomore-warning.jpg' alt='Warning!'/></div>"+
            "<div style='width: 320px; float: left; font-family: Arial, sans-serif;'>"+
            "<div style='font-size: 14px; font-weight: bold; margin-top: 12px;'>"+
            "Stai usando un browser obsoleto!"+
            "</div>        <div style='font-size: 12px; margin-top: 6px; line-height: 12px;'>"+
            "Per godere di tutte le nuove funzionalità di questo sito per favore aggiorna il tuo programma di navigazione."+
            "</div>      </div>      <div style='width: 75px; float: left;'><a href='http://www.firefox.com' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-firefox.jpg' style='border: none;' alt='Get Firefox 3.5'/></a></div>      <div style='width: 75px; float: left;'><a href='http://www.browserforthebetter.com/download.html' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-ie8.jpg' style='border: none;' alt='Get Internet Explorer 8'/></a></div>      <div style='width: 73px; float: left;'><a href='http://www.apple.com/safari/download/' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-safari.jpg' style='border: none;' alt='Get Safari 4'/></a></div>      <div style='float: left;'><a href='http://www.google.com/chrome' target='_blank'><img src='http://www.ie6nomore.com/files/theme/ie6nomore-chrome.jpg' style='border: none;' alt='Get Google Chrome'/></a></div>    </div>  </div>  "
         );
   //}



}