﻿$(window).load(function(){  
   if($('.hp').is('body')){
    $('#logo').pngFix();
    $('#menutop_hp').pngFix();
    $('#p_overlay').pngFix();
    $('#claim_hp').pngFix();
    $('#nh_style').pngFix();
    $('#cfooter').pngFix();
   }
   else{
    $(document).pngFix();
   }
});

$(document).ready(function(){
  if($(".poland_map").is('div')){handlePolandMap();}
  if($("#top").is('div')){ handleTop(); }
  if($("#footer").is('div') || $("#footer_hp").is('div')){ handleFooter(); }
  if($("#bookmark").is('p')){ handleBookmarks(); }
  if($("#print").is('p')){ handlePrint(); }
  if($("#menutop_hp").is('div')){ handleMenuTopHp(); }
  if($("#hp_swtab").is('ul')){ switchTabSW(); }// identificazione home page .. hp
  if($("#nh_style").is('p')){ handleHpLayer(); }
  if($("#p_overlay").is('div')){ handleOverlay(); }
  if($("#boxes_hp").is('div')){ $("#boxes_hp .boxhp:last").css('margin','0') }
  if($("#MapEdit").is('div')){ getMousePos(); }
  if($("#MapEditHp").is('div')){ getMousePosHp(); }
  //if($(".box_cd").is('div')){ $(".box_cd").corner('5px'); }
  if($(".prod_line").is('div')){ handleMainProd(); }
  //if($(".minisheet").is('div')){ $(".minisheet").corner('5px cc:#fff'); }
  if($("#container").is('div')){ handleColumns(); }
  //if($("#dealer_f").is('iframe')){ handleColumns(); }
  if($(".accordion").is('ul')){ handleAccordion(); }
  //if($(".c_ringtones").is('div')){ handleRgtAccordion(); }
  if($("#img_hotspots").is('div')){ productsMapsHp.init(); }
  if($("#map").is('div')){ productsMaps.init(); }
  if($("#mapworld").is('div')){ productsMapsWorld.init(); }
  if($("#slider").is('div')){ handleSliders('#slider'); }
  if($(".myfav").is('div')){  
    initMyfavourite('.c_myfav');
    initMyfavourite('.c_rv');
    initMyfavourite('.c_also');
  }
  if($(".sct_title").is('h1') || $(".sct_title").is('h2') || $(".sct_title").is('h3')){  
    handleSifr();
  }
  if($(".subsct_title").is('h1') || $(".subsct_title").is('h2')){
    handleSifr();
  }
  if($("#techinfo").is('div')){ handleTableExp(); }
  if($("#techspec").is('div')){ handleTableExpand(); }
  if($("#media_slider").is('div')){ handleSliders('#media_slider'); }
  if($("#nhp_media_slider").is('div')){ handleSliders('#nhp_media_slider'); }
  if($("#ps_slider").is('div')){ handleSliders('#ps_slider'); }
  if($(".c_media_dwl").is('div')){ handleMediaHover(); }
  if($(".nhp_c_media_dwl").is('div')){ handleNhpMediaHover(); }
  if($(".selectyear").is('div')){ handleSelectYear(); }
  if($(".ps").is('body')){ handlePsColDx(); }
  if($(".we").is('body')){ handleWeColDx(); }
  if($(".tab_loan").is('div')){ switchTab(); }
  if($('#p_ssp').is('div')){ loadProdGallery(); }
  if($('#tst_gallery').is('div')){ loadTestimonialGallery(); }
  if($('#nhp_c_flash').is('div')){ loadNhpeopleGallery(); }
  if($('#add_fav').is('a')){ addMyFav.init(); }
  if($('#de_results').is('div')){ MyDealer.init(); }
  if($('.c_rv').is('div')){ RecentlyVisited.init(); }
  if($('#cfooter').is('div')){ openPopup(); }
  if($('.thb_video').is('a')){ handleVideoLayer() }
  if($('#c_contacts').is('div')){ checkMandatoryData(); }
  if($('#sitemap').is('div')){
    //hideMenu();
    //activeMenu();
  }
  if($('#c_tool_sel').is('div')){ checkFlash(); }
  if($('.video_open').is('p')){ openVideo(); }
  if($('.ps_box_txt').is('div')){ trimTextPsbox(); }
  if($('.p_box_model').is('div')){ trimTextPbox(); }
  //if($('.dealers_iframe').is('div')){ printDealersIframe(); }
  //if($('#hp_weather_wrap').is('div')){ printWeatherIframe(); }
  if($('.open_legend').is('div')){openLegend();}
  if($("#c_colsx").is('div')){colSxHeight();}
  if($("#sendfriend").is('p')){sendfriend();}
});


/*dealer poland*/
function handlePolandMap(){
	$('.poland_map area').click(function(){
		var province = $(this).attr('href');
		$('.poland_map img').attr({'src':'/SiteCollectionImages/dealerslocator/poland/pl_'+province+'.jpg'});
		var provinceName = $(this).attr('alt');
		$('.provincia input').val(provinceName);
		return false;
	})
}
/*fine dealre poland*/

/* gerstione cookie */
/* oggetto generico */
var prefs = {
    data: {},
    load: function (c_name) {
      var stringInCookie = ""
      if (document.cookie.length>0){
    var allCookie = document.cookie.split(";");
    for (var i = 0; i < allCookie.length; i++){
      var name = allCookie[i].split("=");
      if (name[0].replace(/^\s+|\s+$/g,'') == c_name.replace(/^\s+|\s+$/g,'')) {
        stringInCookie = unescape(name[1])  
      }
    }

   }
   return stringInCookie;
    },
    save: function (name, expires, path) {    
        var d = expires || new Date(2020, 02, 02);
        var p = path || '/';
        document.cookie = name+'='+ escape((this.data))
                          + ';path=' + p
                          + ';expires=' + d.toUTCString();  
    }
}
/* oggetto generico end */

/* dealer */
var MyDealer = {
  fav:{items:[{dealerName:"",address:"",city:"",postalCode:"",phone:"",fax:"",mail:"",dwsURL:""}]},

  load:function(){
    var coockieDealer = prefs.load('NH_dealer');

    if(coockieDealer=='' || coockieDealer=='undefined'){
      prefs.data = JSON.stringify(this.fav);
      prefs.save('NH_dealer',new Date(2020, 02, 02),'/');  
      coockieDealer = prefs.load('NH_dealer');      
    }
    coockieDealer =  coockieDealer.replace(/"dealerName"/g,"dealerName");
    coockieDealer =  coockieDealer.replace(/"address"/g,"address");
    coockieDealer =  coockieDealer.replace(/"city"/g,"city");        
    coockieDealer =  coockieDealer.replace(/"postalCode"/g,"postalCode");  
    coockieDealer =  coockieDealer.replace(/"phone"/g,"phone");  
    coockieDealer =  coockieDealer.replace(/"fax"/g,"fax");  
    coockieDealer =  coockieDealer.replace(/"mail"/g,"mail");  
    coockieDealer =  coockieDealer.replace(/"dwsURL"/g,"dwsURL");      
    coockieDealer =  coockieDealer.replace(/"items"/g,"items");        
    
    this.fav.items = eval(coockieDealer);
  },
  
  /* aggiunge elemento in coda ai favorite*/
  Set:function(newdealerName, newaddress, newcity, newpostalCode, newphone, newfax, newmail, newdwsURL){
            this.fav.items[0].dealerName       = newdealerName;
            this.fav.items[0].address          = newaddress;   
            this.fav.items[0].city             = newcity;      
            this.fav.items[0].postalCode       = newpostalCode;
            this.fav.items[0].phone            = newphone;     
            this.fav.items[0].fax              = newfax;       
            this.fav.items[0].mail             = newmail;      
            this.fav.items[0].dwsURL       = newdwsURL;    
  
    this.save();        
  },
  
  save:function(){
    prefs.data = JSON.stringify(this.fav);
    prefs.save('NH_dealer',new Date(2020, 02, 02),'/');  
  },

  init:function(){
    this.diplay();
  },

  diplay:function(){
    var temp = this.load();
    if (this.fav.items[0].dealerName != null){  
      writeDealerData(this.fav.items[0].dealerName,this.fav.items[0].postalCode,this.fav.items[0].city,this.fav.items[0].address,this.fav.items[0].phone,this.fav.items[0].mail);
    }else{
      return;
    }    
  }
}

function writeDealerData(name,postalcode,city,address,phone,mail){
  $('#dealerbox').html('');
  $('#dealerbox').html('<h2>'+name+'</h2><p>'+postalcode+' '+city+'</p>');
  $('.btn_refine a img').attr({src:'/PublishingImages/cnhimg/btns/btn_more.gif'});
  $('.btn_refine').attr('id','btn_more')
  $('#btn_more a').attr({href:'#'});
  $('#btn_more').css('z-index','500').click(function(){
      $('.txtbox_op').animate({height: '80px'},"slow");
      $(this).parent('.img_box').siblings('.txtbox').animate({height: '80px'},"slow");
      $('#dealerbox').append('<div id="more_dealer_data"><p>address</p><p>phone</p><p><a href="mailto:'+mail+'">'+mail+'</a></p></div>')
      $('.btn_close').show()
      $('#btn_more').hide();      
      return false;
  });
  
  $('.btn_close').click(function(){      
      $('.txtbox_op').animate({height: '36px'},"slow");
      $(this).parent('.img_box').siblings('.txtbox').animate({height: '36px'},"slow");
      $('#more_dealer_data').html('');
      $('#more_dealer_data').remove()
      $('.btn_close').hide()
      $('#btn_more').css('bottom','5px').show();
    
      return false;
  });  

}
/* dealer end */


/* myfav start*/
/* myfav start*/
var addMyFav = {

  fav:{items:[{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""}]},
  
  load:function(){
    var coockieFav = prefs.load('NH_favourites');
      coockieFav =  coockieFav.replace(/"pathThb"/g,"pathThb");
      coockieFav =  coockieFav.replace(/"title"/g,"title");
      coockieFav =  coockieFav.replace(/"items"/g,"items");
      coockieFav =  coockieFav.replace(/"lnk"/g,"lnk");

    if(coockieFav=='' || coockieFav=='undefined'){
      prefs.data = JSON.stringify(this.fav);
      prefs.save('NH_favourites',new Date(2020, 02, 02),'/');  
      coockieFav = prefs.load('NH_favourites');      
      coockieFav =  coockieFav.replace(/"pathThb"/g,"pathThb");
      coockieFav =  coockieFav.replace(/"title"/g,"title");
      coockieFav =  coockieFav.replace(/"items"/g,"items");
      coockieFav =  coockieFav.replace(/"lnk"/g,"lnk");

    }
    this.fav.items = eval(coockieFav);
  },
  init:function(){
    $('#add_fav').click(function(){
      var url = location.href;
      var splurl = url.split("/");
      var start = url.indexOf(splurl[3]);
      var newLink = "/"+url.substr(start,url.length);
      addMyFav.add($('#thbFav').val(),$('#titleFav').val(),newLink);
      return false;      
    });
    $('.remove_fav').click(function(){
      var el1 = $(this).siblings('.fav_img').children('img').attr('src');
      var el2 = $(this).siblings('.fav_txt').children('h1').children('a').html();
      var el3 = $(this).siblings('.fav_txt').children('h1').children('a').attr('href');
      addMyFav.remove(el1,el2,el3);
      return false;      
    });    
    this.display();
  },  
  /* aggiunge elemento in coda ai favorite*/
  add:function(newPathThb, newTitle, newLnk){
    for(var i=0; i<this.fav.items.length ; i++){
      if ( this.fav.items[i].title == newTitle) { break; }
      fraseAdd = $('#add_fav img').attr('alt');
      if ( this.fav.items[i].title == fraseAdd || this.fav.items[i].title == "" ){
          this.fav.items[i].pathThb = newPathThb;
          this.fav.items[i].title = newTitle;
          this.fav.items[i].lnk = newLnk;
          break;
      }
    }    
    this.save();
    this.display();
  },
  
  save:function(){
    prefs.data = JSON.stringify(this.fav);
    prefs.save('NH_favourites',new Date(2020, 02, 02),'/');
  },  
  /* rimuove e compatta i favorite */
  remove:function(removePathThb, removeTitle, removeLink){
    var numPlaceHolder = 6;
    var tempFavPathThb = new Array (numPlaceHolder);
    var tempFavPathTitle = new Array (numPlaceHolder);
    var tempFavLnk = new Array (numPlaceHolder);  

    for (var i=0; i<numPlaceHolder;i++)    {
      tempFavPathThb[i] = '/PublishingImages/cnhimg/products/placeholder_fav.gif';
      fraseAdd = $('#add_fav img').attr('alt');
      tempFavPathTitle[i] = fraseAdd;
      tempFavLnk[i] = '#';
    }

    var countTempFav = 0;

    for(var i=0; i<this.fav.items.length ; i++){        

      if ( (this.fav.items[i].title != "") && (this.fav.items[i].title != removeTitle) )  {
        tempFavPathThb[countTempFav] = this.fav.items[i].pathThb;
        tempFavPathTitle[countTempFav] = this.fav.items[i].title ;
        tempFavLnk[countTempFav] = this.fav.items[i].lnk ;
        countTempFav++;        
      }
    }    

    for(var i=0; i<this.fav.items.length ; i++){        
              this.fav.items[i].pathThb = tempFavPathThb[i];
              this.fav.items[i].title = tempFavPathTitle[i];
              this.fav.items[i].lnk = tempFavLnk[i];
    }    
    
    for(var i=0; i<this.fav.items.length ; i++){
    }

    this.save();
    this.display();
  },

  display:function(){
    var temp = this.load();
    for(var i=0;i<this.fav.items.length;i++){
      if((this.fav.items[i].pathThb)!=''){
          $('.c_myfav .fav_img img').eq(i).attr('src',this.fav.items[i].pathThb)
      }
      if(this.fav.items[i].title!=''){
          $('.c_myfav .fav_txt h1 a').eq(i).html(this.fav.items[i].title);
      }
      if(this.fav.items[i].lnk!=''){
          $('.c_myfav .fav_img a').eq(i).attr('href',this.fav.items[i].lnk);        
          $('.c_myfav .fav_txt a').eq(i).attr('href',this.fav.items[i].lnk);        
      }
    }
      
  }
}
/*fine admyfav */

/*recently visited*/
var RecentlyVisited = {
  visited:{items:[{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""},{pathThb:"",title:"",lnk:""}]},
  
  load:function(){
    var coockieRec = prefs.load('NH_recently');
      coockieRec =  coockieRec.replace(/"pathThb"/g,"pathThb");
        coockieRec =  coockieRec.replace(/"title"/g,"title");
      coockieRec =  coockieRec.replace(/"items"/g,"items");
      coockieRec =  coockieRec.replace(/"lnk"/g,"lnk");

    if(coockieRec=='' || coockieRec=='undefined'){
      prefs.data = JSON.stringify(this.visited);
      prefs.save('NH_recently',new Date(2020, 02, 02),'/');  
      coockieRec = prefs.load('NH_recently');      
      coockieRec =  coockieRec.replace(/"pathThb"/g,"pathThb");
        coockieRec =  coockieRec.replace(/"title"/g,"title");
      coockieRec =  coockieRec.replace(/"items"/g,"items");
      coockieRec =  coockieRec.replace(/"lnk"/g,"lnk");

    }
    this.visited.items = eval(coockieRec);

    
    
  },
  init:function(){
    var temp = this.load();
    var url = location.href;
    var splurl = url.split("/");
    var start = url.indexOf(splurl[3]);
    var newLink = "/"+url.substr(start,url.length);    
    RecentlyVisited.add($('#thbFav').val(),$('#titleFav').val(),newLink);    
    //this.display();
  },
  
  /* aggiunge elemento in coda ai favorite*/
  add:function(newPathThb, newTitle, newLnk){
    fraseAdd = $('#btn_recently').attr('name'); // ugo
    for(var i=0; i<this.visited.items.length ; i++){
        if ( this.visited.items[i].title == fraseAdd || this.visited.items[i].title == "" ){
            this.visited.items[i].pathThb = newPathThb;
            this.visited.items[i].title = newTitle;
            this.visited.items[i].lnk = newLnk;
            break;        
        }
    }    
    this.save();
    this.display();
    
  },
  save:function(){
    prefs.data = JSON.stringify(this.visited);
    prefs.save('NH_recently',new Date(2020, 02, 02),'/');  
  },

  display:function(){    
    var temp = this.load();
    if (this.visited.items) {
    for(var i=0;i<this.visited.items.length;i++){
      if((this.visited.items[i].pathThb)!=''){
          $('.c_rv .fav_img img').eq(i).attr('src',this.visited.items[i].pathThb)
      }
      if(this.visited.items[i].title!=''){
          $('.c_rv .fav_txt h1 a').eq(i).html(this.visited.items[i].title);
      }
      if(this.visited.items[i].lnk!=''){
          $('.c_rv .fav_img a').eq(i).attr('href',this.visited.items[i].lnk);        
          $('.c_rv .fav_txt a').eq(i).attr('href',this.visited.items[i].lnk);
      }
    }
    }
      
  }
}
/*fine recently visited*/
/*fine gestione cookie */

function handleSifr(){
  sIFR.replaceElement(named({sSelector:"body h1.sct_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#c3c3c3", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:""}));  
  sIFR.replaceElement(named({sSelector:"body h2.sct_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#b2bbc4", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=right"}));
  sIFR.replaceElement(named({sSelector:"body h3.sct_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#727272", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=right"}));
  sIFR.replaceElement(named({sSelector:"body h4.sct_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#727272", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:""}));
  sIFR.replaceElement(named({sSelector:"body h1.subsct_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#0d5ca0", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:""}));
  sIFR.replaceElement(named({sSelector:"body h2.subsct_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#6699ff", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:""}));
  sIFR.replaceElement(named({sSelector:"body h1.subsctr_title", sFlashSrc:"/PublishingImages/cnhimg/swf/gillsans.swf", sColor:"#0d5ca0", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=right"}));
    
}
  

function handleTop(){
  $('#market>li').hover(function(){
    $(this).children('ul').fadeIn('fast');
    return false;
    },
    function(){
      $(this).children('ul').fadeOut('fast');    
  })
}

function handleMenuTopHp(){
  $("#menutop_hp>ul>li").hover(function(){
    $(this).children('a').css({backgroundImage:'url(/PublishingImages/cnhimg/hp/bg_menu_hover.gif)',color:'#0d5ca0'});
    $(this).children('ul').css('display','block');
    $('#img_hotspots').css('z-index','1');
  },
  function(){
    $(this).children('a').css({backgroundImage:'url(/PublishingImages/cnhimg/hp/menu_dots.gif)',color:'#fff'});
    $(this).children('ul').css('display','none');
    $('#img_hotspots').css('z-index','500');
  });
 
  $("#menutop_hp>ul>li>ul>li").hover(function(){
    $(this).addClass('on');
  },
  function(){
    $(this).addClass('on');
 });
}

/*
function handleMenuTopHp(){
  $("#menutop_hp>ul>li").hover(function(){
    $(this).children('ul').children('li').hover(function(){
      $(this).addClass('on');
    },
    function(){
      $(this).removeClass('on');
    })
    $(this).children('a').css({backgroundImage:'url(/PublishingImages/cnhimg/hp/bg_menu_hover.gif)',color:'#0d5ca0'});
    $(this).children('ul').css('display','block').animate({opacity: 1}, 300);
    //$("#menutop_hp>ul>li>ul>li").pngFix();
    },
    function(){
    $(this).children('a').css({backgroundImage:'url(/PublishingImages/cnhimg/hp/menu_dots.gif)',color:'#fff'});
    $(this).children('ul').animate({opacity: 0}, 300,function(){
      $(this).css('display','none');
    });
  });
}
*/

/*  EFFETTO PER BOTTONE NHSTYLE SU OMINI IN HOME PAGE  */
var secs = 1;
var timerID = null;
var timerRunning = false;
var delay = 300;
function handleHpLayer(){
	$('#lnh_link_hp').hover(function(){
    StartTheTimer();
  }, function(){
    StopTheClock();
		if($.browser.msie){
			$('#lnh_style').css('display','none');
		}
		else{
		  $('#lnh_style').fadeOut('slow');
		}
  });
}
function StartTheTimer(){
  if (secs==0){
    StopTheClock()
    secs = 2;
    nh_style();
  }
  else {
    self.status = secs
    secs = secs - 1
    timerRunning = true
    timerID = self.setTimeout("StartTheTimer()", delay);
  }
}
function StopTheClock(){
  if(timerRunning)
  clearTimeout(timerID)
  timerRunning = false
}
function nh_style(){
  $('#lnh_content').pngFix();
  $('#lnh_opacity').css({width: $('#layout').width(),height: $('#layout').height()});
  $('#lnh_content').css({width: $('#layout').width(),height: $('#layout').height()}).click(function(e){
    var elClicked=e.target;
    if(elClicked.tagName=='DIV'){
      if($.browser.msie){
        $('#lnh_style').css('display','none');	
      }
      else{
        $('#lnh_style').fadeOut('slow');	
      }
    }
  });
  if($.browser.msie){
    $('#lnh_style').css('display','block');
  }
  else{
    $('#lnh_style').fadeIn('slow');
  }
}
/*  FINE EFFETTO PER BOTTONE NHSTYLE SU OMINI IN HOME PAGE  */
function handleOverlay(){
  
  $('#p_overlay').hover(function(){                   
    $('#p_overlay a').css({zIndex:'100'}).fadeIn('slow');
    },
    function(){
    $('#p_overlay a').fadeOut('slow');  
  });  
}

function handleColumns(){
  if($('#coldx').height() != null){
    var hDx = $('#coldx').height();
    var hSx = $('#c_colsx').height();
    if($('.people_home_flash').is('div') & (hDx > hSx)){f
      $('#c_colsx').css({height:(hDx+125-419),minHeight:(hDx+125-419)});
    }
    else{
      if (hDx > hSx ) {
        $('#c_colsx').css({height:(hDx+125),minHeight:(hDx+125)});
      }
    }
  }
}

function handleMainProd(){ 
 $(".prod_line").each(function(){
  var par = $(this).parents();
  var rp = false;
  $(par).each(function(){
   if($(this).attr('class')=="RightProdBox"){        
    rp = true;   
   }      
  })
  if(rp==true){
   $(this).children('.thb_prod').children('.thb_resize').css({right:'0'});
  }
  else{
   $(this).children('.thb_prod').children('.thb_resize').css({left:'0'});
  }
 });
 $(".thb_prod").hover(function(){
  $(this).css('z-index','100');
  $(this).parent().css('z-index','100');
  $(this).children(".thb_small").children('h1').hide();
  $(this).children(".thb_resize").show();
  },
  function(){
  $(this).css('z-index','1');
  $(this).parent().css('z-index','1');
  $(this).children(".thb_resize").hide();
  $(this).children(".thb_small").children('h1').show();
 })
}

function handleFooter(){
  $('#cfooter ul li:last').css('border','0')
}

function handleBookmarks(){  
  $('#bookmark a').click(function(){
    var title = $("title").html();
    var url = window.location;              
    if (window.sidebar) { // Firefox 
      window.sidebar.addPanel(title, url,"");
    }
    else if( window.external ) { // IE 
      window.external.AddFavorite( url, title); 
    }
    else if(window.opera && window.print) { // Opera 
      return true; 
    }
  })
}

function handlePrint(){
  $('#print a').click(function(){
    self.print();
    return false;
  })
}
//  ACCORDION
function handleAccordion(){
  $('.accordion_frm').accordion({
      active: false,
      autoheight: true,
      header: '.btn_accordion',
      collapsible: true
  });
  $('.accordion_hat').accordion({
      autoheight: true,
      header: '.btn_accordion'
      
  });
  $('.accordion_haf').accordion({
      autoheight: false,
      header: '.btn_accordion'
  });
  $('.accordion_haf2').accordion({
      autoheight: false,
      header: '.btn_accordion2'
  });  
  $('.accordion_actf').accordion({
      autoheight: false,
      active: false,
      header: '.btn_accordion'
  });  
  

  $('.btn_accordion').click(function(){                     
    if($(this).attr('id')=='btn_favourite'){      
      $('#add_fav').css('z-index','100').show();            
    }
    else{
      $('#add_fav').hide();
    }
  });
}


function handleRgtAccordion(){
  /*
  $('.rt_main_accordion').accordion({
      autoheight: false,
      header: '.accordion_tab'
  });
  $('.rt_l2_accordion').accordion({
      autoheight: false,
      header: '.accordion_tab_2'
  });

  $('.rt_l3_accordion').accordion({
      autoheight: false,
      header: '.accordion_tab_3',
      active:false
  });
*/
}

//  END ACCORDION
/* gestisce mappa con hotspot per overview prodotto */

var productsMapsHp = {
  init : function(){
      $.ajax({ 
        type: "GET",
        dataType :"xml",
        url: document.getElementById('xmlPointsUrl').value,
        success: function(msg){ 
            var i=1;
            $(msg).find('spot').each(function(){
              var pos = 'left:7px;';
              var url = $(this).attr('url');
              var title = $('title').html();
              var myWidth = $(this).attr('width');
              var myHeight = $(this).attr('height');
              var FVersion = $(this).attr('FVersion');
              
              if($(this).attr('type') == "0"){
                $('#img_hotspots').append('<p id="spot_' + i + '" class="map_spot" style="top:' + $(this).attr('top') + 'px;left:' + $(this).attr('left') + 'px;z-index:250"><span class="bg_hotspot">&nbsp;</span><a href="' + $(this).attr('url') + '" style="' + pos + '">' + $(this).attr('txt') + '</a></p>');
              }
              else if($(this).attr('type') == "1"  ||  $(this).attr('type') == "2"){
                $('#img_hotspots').append('<p  class="map_spot_video" style="top:' + $(this).attr('top') + 'px;left:' + $(this).attr('left') + 'px;z-index:200"><span class="bg_hotspot">&nbsp;</span><a src="' + $(this).attr('url') + '" mywidth = "' + myWidth + '" myheight = "' + myHeight + '" FVersion = "' + FVersion + '" style="' + pos + '; cursor: pointer;display:none;"><img src=' + $(this).attr('imgPreview') + ' /></a></p>');
              }
              
              i++;
            });
            $('.map_spot_video').find('a').click(function(){
              var videoPath = $(this).attr('src');
              var myWidth = $(this).attr('mywidth');
              var myHeight = $(this).attr('myheight');
              var FVersion = $(this).attr('FVersion');
              myVar = videoPath;
              myType = myVar.substring(myVar.length - 3, myVar.length);
              if (myType == "flv" || myType == "swf"){
                showVideo(videoPath,myWidth,myHeight,FVersion);
              } else {
                showImage(videoPath,myWidth,myHeight);
              }
            })

        }
      });
      productsMapsHp.events();
  },
  events : function(){  
        
    $('#hotspots_hp').hover(function(){
      $('#img_hotspots p a').css('display','none');
      $('#img_hotspots p a img').css('display','none');

      $('#img_hotspots p').hover(function(){
        $(this).children('a').show();
        $(this).children('a').children('img').show();
      },
      function(){
        $(this).children('a').hide();
        $(this).children('a').children('img').hide();
      });
    },
      function(){
        
      });
  }
}
//################################################
var productsMaps = {
  init : function(){
      $.ajax({ 
        type: "GET",
        dataType :"xml",
        url: document.getElementById('xmlPointsUrl').value,
        success: function(msg){ 
            var i=1;
            $(msg).find('spot').each(function(){
              var myWidth = $(this).attr('width');
              var myHeight = $(this).attr('height');
              var FVersion = $(this).attr('FVersion');
              if($(this).attr('type')=="0"){
                if($(this).attr('left')>=320){
                    var pos = 'right:7px;';
                  }
                  else{
                    var pos = 'left:7px;';
                  }
                  $('#map').append('<p id="spot_'+i+'" class="map_spot" style="top:'+$(this).attr('top')+'px;left:'+$(this).attr('left')+'px;z-index:200"><span><img src="/PublishingImages/cnhimg/products/bg_hotspot.png" /></span><a href="'+$(this).attr('url')+'" style="'+pos+'">'+$(this).attr('txt')+'</a></p>');
                }
                else if($(this).attr('type')=="2" || $(this).attr('type')=="1" ){
                  var pos = 'left:7px;';
                  var url = $(this).attr('url');
                  $('#map').append('<p id="spot_'+i+'" class="map_spot_video" style="top:' + $(this).attr('top') + 'px;left:'+$(this).attr('left') + 'px;z-index:200"><span><img src="/PublishingImages/cnhimg/products/bg_hotspot.png" /></span><a mywidth = "' + myWidth + '" myheight = "' + myHeight + '" FVersion = "' + FVersion + '" src="' + $(this).attr('url') + '" style="' + pos + '; cursor: pointer;display:none;"><img src=' + $(this).attr('imgPreview') + ' /></a></p>');
                }
                $(document).pngFix();
                i++;
            });
            
            $('.map_spot_video').find('a').click(function(){
              var videoPath = $(this).attr('src');
              var myWidth = $(this).attr('mywidth');
              var myHeight = $(this).attr('myheight');
              var FVersion = $(this).attr('FVersion');
              myVar = videoPath;
              myType = myVar.substring(myVar.length - 3, myVar.length);
              if (myType == "flv" || myType == "swf"){
                showVideo(videoPath,myWidth,myHeight,FVersion);
              } else {
                showImage(videoPath,myWidth,myHeight);
              }
            })
            
          }
      });
      
      productsMaps.events();
        
  },
  events : function(){  
    $('#detail_top').hover(function(){
      $('#map p').css('display','block');
      $('#map p a').css('display','none');
      $('#map p a img').css('display','none');

        $('#map p').hover(function(){
          $(this).children('a').show();
          $(this).children('a').children('img').show();
          $(this).css('z-index','9000');
        },
        function(){
          $(this).children('a').hide();
          $(this).children('a').children('img').hide();
          $(this).css('z-index','200');
        });
      },
      function(){

    });
  }
}
//################################################
var productsMapsWorld = {
  init : function(){    
    $.ajax({ 
      type: "POST", 
      url: "/Documents/world_spots.xml", 
      data: "", 
      success: function(msg){
        var i = 1;
        $(msg).find('spot').each(function(){
          var top = $(this).attr('top');
          var left = $(this).attr('left');
          var color = $(this).attr('color');
          var title = $(this).find('mytitle').text();
          var image = $(this).find('myimage').text();
          var txt = $(this).find('mytxt').text();
          $('#mapworld').append('<p id="spot_'+i+'" class="mapworld_spot" style="top:'+top+'px;left:'+left+'px;"><img src="/PublishingImages/cnhimg/we/intheworld_bullet_'+color+'.png" />');
          productsMapsWorld.events("spot_"+i,title,image,txt);
          i = i+1;
        });
      }
    });
  },
  events : function(spot,title,image,txt){
    $(document).pngFix();
    $('#'+ spot).click(function(){
      $('#mapworld').append('<div class="mapworld_box"><p class="mapworld_image"><img src="/PublishingImages/cnhimg/we/locations/' + image + '.jpg" /></p><p class="mapworld_title">' + title + '</p><p class="mapworld_txt">' + txt + '</p><p class="mapworld_close"><a href="#">&nbsp;&nbsp;&nbsp;&nbsp;</a></p></div>' );
      $('.mapworld_close').click(function(){
        $('.mapworld_box').remove();
        return false;
      });
    });

  }
}
function openVideo(){
  $('.video_open img').click(function(){
    videoPath = $(this).parent().find('span').text();
    myWidth = $(this).parent().find('span').attr("mywidth");
    myHeight = $(this).parent().find('span').attr("myheight");
    FVersion = $(this).parent().find('span').attr("fversion");
    showVideo(videoPath, myWidth, myHeight, FVersion);
  });
}


function showVideo(videoPath, myWidth, myHeight, FVersion){
  makeBg();
  if (typeof(FVersion) == 'undefined' || FVersion == 'undefined') {
    FVersion = "9.0.0";
  } else {
    FVersion = FVersion + ".0.0"
  }
  if (typeof(myWidth) == 'undefined') { myWidth = "400"; }
  if (typeof(myHeight) == 'undefined') { myHeight = "310"; }
  
  myMargin = getScrollXY();
  myMargin = myMargin[1] + 20;
  $('#swf_layer').append('<div id="c_swf_wrap"><p><img src="/PublishingImages/cnhimg/swf/playerFLV/btn_close.gif" alt=""/></p><div id="c_swf"></div></div>');
  //$('#swf_layer').append('<div id="c_swf_wrap"><p>Close</p><div id="c_swf"></div></div>');
  $('#c_swf_wrap').css({width: myWidth + 'px', margin: myMargin + 'px auto 0'});
  $('#c_swf_wrap p').css({cursor:'pointer',color:'#ffffff',textAlign:'right'});
  
  var myLang = ((window.location.href).split("/"))[4];
  switch (myLang) {
  case "it":
    fraseFlash = "<div style='background:#fff; padding: 15px;'>Per visualizzare questo contenuto hai bisogno di Adobe Flash Player 9.<br/><a href='http://get.adobe.com/flashplayer/'>Clicca qui per aggiornare il tuo player.</a></div>";
    break;
  case "en":
    fraseFlash = "<div style='background:#fff; padding: 15px;'>To view this content you need Adobe Flash Player 9.<br/><a href='http://get.adobe.com/flashplayer/'>Click here to update your player.</a></div>";  
    break;
  case "fr":
    fraseFlash = "<div style='background:#fff; padding: 15px;'>Pour visualiser ce contenu, vous avez besoin du logiciel Adobe Flash Player 9.<br/><a href='http://get.adobe.com/flashplayer/'>Cliquez ici pour mettre ÃƒÆ’Ã†â€™  jour votre lecteur.</a></div>";   
    break;
  case "pt":
    fraseFlash = "<div style='background:#fff; padding: 15px;'>Para visualizar este conteÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Âºdo vocÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Âª precisa ter o Adobe Flash Player 9.<br/><a href='http://get.adobe.com/flashplayer/'>Clique aqui para actualizar o seu leitor.</a></div>";   
    break;
  default:
    fraseFlash = "<div style='background:#fff; padding: 15px;'>To view this content you need Adobe Flash Player 9.<br/><a href='http://get.adobe.com/flashplayer/'>Click here to update your player.</a></div>";  
  }

  $('#c_swf').append(fraseFlash);
  
  myVar = videoPath;
  myType = myVar.substring(myVar.length - 3, myVar.length);
  
  if (myType == 'flv') {
    var flashvars = {file: videoPath,bufferlength : 5, autoplay : 1};
  	var params = { scale:'noScale', salign:'lt', menu:'false' , wmode:'transparent' , bgcolor:'ffffff' };
  	var attributes = {}
    swfobject.embedSWF('/PublishingImages/cnhimg/swf/playerFLV/flvplayer.swf', "c_swf", myWidth, myHeight, FVersion, false, flashvars, params, attributes );
  } else {
    var flashvars = {};
  	var params = { scale:'noScale', salign:'lt', menu:'false' , wmode:'transparent' , bgcolor:'ffffff' };
  	var attributes = {}
    swfobject.embedSWF(videoPath, "c_swf", myWidth, myHeight, FVersion, false, flashvars, params, attributes );
  }
  
  $('#c_swf_wrap p').click(function(){
    removeBg();
  });
  
}

function showImage(videoPath, myWidth, myHeight){
  makeBg();
  if (typeof(myWidth) == 'undefined') { myWidth = "400"; }
  if (typeof(myHeight) == 'undefined') { myHeight = "310"; }
  myMargin = getScrollXY();
  myMargin = myMargin[1] + 20;
  $('#swf_layer').append('<div id="c_swf_wrap"><p><img src="/PublishingImages/cnhimg/swf/playerFLV/btn_close.gif" alt=""/></p><div id="c_swf"><img src="' + videoPath + '"/></div></div>');
  //$('#swf_layer').append('<div id="c_swf_wrap"><p>Close</p><div id="c_swf"></div></div>');
  $('#c_swf_wrap').css({width: myWidth + 'px', margin: myMargin + 'px auto 0'});
  $('#c_swf_wrap p').css({cursor:'pointer',color:'#ffffff',textAlign:'right'});
  
  $('#c_swf_wrap p').click(function(){
    removeBg();
  });  
}
function makeBg(){
  $('h1').hide();
  $('h2').hide();
  $('h3').hide();
  $('h4').hide();
  $('body').append('<div id="op_layer"></div>');
  $('body').append('<div id="swf_layer"></div>');
  
	bodyH = $('body').height();
	layoutH = $('#layout').height();
	bodyH > layoutH ? myH = bodyH : myH = layoutH;

  $('#op_layer').css({position:'absolute', left:'0', top:'0', zIndex:500, height:myH, width:$('body').width(), background:'#000', filter:'alpha(opacity=70)', opacity:0.7})
  $('#swf_layer').css({position:'absolute', left:'0', top:'0', zIndex:1000, height:myH, width:$('body').width()});
}
function removeBg(){
  $('#op_layer').remove();
  $('#swf_layer').remove();
  $('#c_swf_wrap').remove();
  $('#c_swf').remove();
  $('h1').show();
  $('h2').show();
  $('h3').show();
  $('h4').show();
}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}



/* gestisce slider my favourites colonna dx prodotti */
function initMyfavourite(container){
  
  $(container).siblings('a.btn_barup').click(function(){
                            
    var els=$(this).siblings(container).children('div').length;  
    var mxl=$(this).siblings(container).height();              
    mf_slmove(container,'up',els,mxl-229);
    return false;
  });  
  $(container).siblings('a.btn_bardown').click(function(){
                    
    var els=$(this).siblings(container).children('div').length;  
    var mxl=$(this).siblings(container).height();
    mf_slmove(container,'dwn',els,mxl-229);
    return false;
  });
}

var mf_dist=1;
var rv_dist=1;
var al_dist=1;
function mf_slmove(cont,dir,els,mxl){
  if(cont=='.c_myfav'){
    (dir=='up'?sign='+':sign='-');
    var stepper=Math.round(mxl/els);
    if(dir=='up'){
      if(mf_dist>=1) {
        $(cont).animate({top:(14)});
        return
      };
      mf_dist+=stepper+109;
    }
    if(dir=='dwn'){
      if(mf_dist!=1&&mf_dist<=(sign+mxl)) return;
      mf_dist+=-stepper-109;
    }
    $(cont).animate({top:(mf_dist)});
    if(mf_dist>=1) {
      $(cont).animate({top:(14)});
      return;
    }
  }
  else if(cont=='.c_rv'){
    (dir=='up'?sign='+':sign='-');
    var stepper=Math.round(mxl/els);
    if(dir=='up'){
      if(rv_dist>=1) {
        $(cont).animate({top:(14)});
        return
      };
      rv_dist+=stepper+109;
    }
    if(dir=='dwn'){
      if(rv_dist!=1&&rv_dist<=(sign+mxl)) return;
      rv_dist+=-stepper-109;
    }
    $(cont).animate({top:(rv_dist)});
    if(rv_dist>=1) {
      $(cont).animate({top:(14)});
      return;
    }
  }
  else if(cont=='.c_also'){
    (dir=='up'?sign='+':sign='-');
    var stepper=Math.round(mxl/els);
    if(dir=='up'){
      if(al_dist>=1) {
        $(cont).animate({top:(14)});
        return
      };
      al_dist+=stepper+109;
    }
    if(dir=='dwn'){
      if(al_dist!=1&&al_dist<=(sign+mxl)) return;
      al_dist+=-stepper-109;
    }
    $(cont).animate({top:(al_dist)});
    if(al_dist>=1) {
      $(cont).animate({top:(14)});
      return;
    }
  }
  
}

function handleTableExp(){
  $('table.model_spec .header a').click(function(){                           
    var elClass = $(this).parent().parent().attr('class');
    if($(this).attr('class')=='open'){
      $(this).attr('class','close');
      $(this).children('img').attr('src','/PublishingImages/cnhimg/btns/btn_expand.gif');
      $("."+elClass).find('span').css('display','none');
      //$("."+elClass).children('span').css('display','none');
    }
    else if($(this).attr('class')=='close'){
      $(this).attr('class','open');
      $(this).children('img').attr('src','/PublishingImages/cnhimg/btns/btn_collapse.gif');
      $("."+elClass).find('span').css('display','block');
      //$("."+elClass).children('span').css('display','inline');
    }
    return false;
  });
}

function handleTableExpand(){  
  if($('.model_spec').height()>407){
    $('#c_techspec').css('height','407px');  
    $('#btn_expand_table a').show();  
    $('#btn_expand_table a').click(function(){
    if($(this).attr('class')=='expand'){                  
      var tabHeight = $('.model_spec').height();      
      $('#c_techspec').animate({height: tabHeight},'slow');
      $(this).attr('class','collapse');      
      if(currLang == null || currLang==""){
      $(this).children('img').attr('src','/PublishingImages/cnhimg/btns/btn_chiudi_tabella_en.gif');
      }else{
      $(this).children('img').attr('src','/PublishingImages/cnhimg/btns/btn_chiudi_tabella_'+currLang+'.gif');
      }
      
    }
    else if($(this).attr('class')=='collapse'){
      $('#c_techspec').animate({height: '407'},'slow');
      $(this).attr('class','expand');
      if(currLang == null || currLang==""){
        $(this).children('img').attr('src','/PublishingImages/cnhimg/btns/btn_espandi_tabella_en.gif');
      }
      else{
        $(this).children('img').attr('src','/PublishingImages/cnhimg/btns/btn_espandi_tabella_'+currLang+'.gif');
      }
      
    }
    return false;    
  });
  }
  else{
    $('#c_techspec').css('height',$('.model_spec').height());
  }
}
function handleMediaHover(){
  $('.media_dwl').each(function(){
    $(this).children().children(':first').children('.media_hover').css('left','-10px');
  });
  $('.box_media').hover(function(){
    $(this).css('z-index','100');
    $(this).children('.media_hover').css('z-index','100');
    $(this).children('.media_hover').fadeIn('fast');
  },
  function(){
    $(this).css('z-index','1');
    $(this).children('.media_hover').fadeOut('fast');
  });
}

function handleNhpMediaHover(){
  $('.nhp_media_dwl').each(function(){
    $(this).children(':first').children('.nhp_media_hover').css('left','-25px');
        
  });
  $('.nhp_box_media').hover(function(){
    $(this).css('z-index','100');
    $(this).children('.nhp_media_hover').css('z-index','100');
    $(this).children('.nhp_media_hover').fadeIn('fast');
  },
  function(){
    $(this).css('z-index','1');
    $(this).children('.nhp_media_hover').fadeOut('fast');
  });
}

/*gestisce sliders tabs*/
function handleSliders(container){
  var $panels = $(container+' .scrollContainer > div');
  var $container = $(container+' .scrollContainer');
  // if false, we'll float all the panels left and fix the width 
  // of the container
  var horizontal = true;
  // float the panels left if we're going horizontal
    if (horizontal) {
      $panels.css({
      'float' : 'left',
      'position' : 'relative' // IE fix to ensure overflow is hidden
      });  
      // calculate a new width for the container (so it holds all panels)
      $container.css('width', $panels[0].offsetWidth * $panels.length);
    }
// collect the scroll object, at the same time apply the hidden overflow
// to remove the default scrollbars that will appear
  var $scroll = $(container+' .scroll').css('overflow', 'hidden');
// per applicare bottoni di navigazione left + right
  /*$scroll
    .before('<img class="scrollButtons left" src="images/scroll_left.png" />')
    .after('<img class="scrollButtons right" src="images/scroll_right.png" />');*/
  // gestisce navigazibne
  function selectNav() {
    $(this).parents('ul:first').find('a').removeClass('selected').end().end().addClass('selected');
  }
  $(container+' .navigation').find('a').click(selectNav);
  // trova il link con target e seleziona il pannello
  function trigger(data) {
    var el = $(container+' .navigation').find('a[href$="' + data.id + '"]').get(0);
    selectNav.call(el);
  }
  if (window.location.hash) {
    trigger({ id : window.location.hash.substr(1) });
  } else {
    $('ul.navigation a:first').click();
  }
  // offset is used to move to *exactly* the right place, since I'm using
  // padding on my example, I need to subtract the amount of padding to
  // the offset.  Try removing this to get a good idea of the effect
  var offset = parseInt((horizontal ? 
    $container.css('paddingTop') : 
    $container.css('paddingLeft')) 
    || 0) * -1;
  var scrollOptions = {
    target: $scroll, // the element that has the overflow
    // can be a selector which will be relative to the target
    items: $panels,
    navigation: '.navigation a',
    // selectors are NOT relative to document, i.e. make sure they're unique
    prev: 'img.left', 
    next: 'img.right',
    // allow the scroll effect to run both directions
    axis: 'xy',
    onAfter: trigger, // our final callback
    offset: offset,
    // duration of the sliding effect
    duration: 500,
    // easing - can be used with the easing plugin: 
    // http://gsgd.co.uk/sandbox/jquery/easing/
    easing: 'swing'
  };
  // apply serialScroll to the slider - we chose this plugin because it 
  // supports// the indexed next and previous scroll along with hooking 
  // in to our navigation.
  $(container).serialScroll(scrollOptions);
  // now apply localScroll to hook any other arbitrary links to trigger 
  // the effect
  $.localScroll(scrollOptions);
  // finally, if the URL has a hash, move the slider in to position, 
  // setting the duration to 1 because I don't want it to scroll in the
  // very first page load.  We don't always need this, but it ensures
  // the positioning is absolutely spot on when the pages loads.
  scrollOptions.duration = 1;
  $.localScroll.hash(scrollOptions);
  
  
  if ($('#hp_stock_wrap').is('div')){

    var boxNumber = $('.scrollContainer').find('.panel').length;
    var idNumber = 1;
    $('#commoditiesName').html($('#hpstock_' + idNumber + ' .commoditiesNameLabel').attr('value'));
    $('#commoditiesFrom').html($('#hpstock_' + idNumber + ' .commoditiesFromLabel').attr('value'));

    $('.scrollContainer').find('.panel').each(function(){
      $(this).attr({id:'hpstock_' + idNumber});
      idNumber = idNumber + 1;
    });
    $('.pag_indietro').click(function(){
      var oldHrefIndietro = $('.pag_indietro').attr('href').split('_');
      var newHrefIndietro = Math.floor(oldHrefIndietro[1])-1;
      var currentBox = newHrefIndietro + 1;

      if (newHrefIndietro==0){newHrefIndietro=1};
      if (newHrefIndietro==1){
        var newHrefAvanti = 2;
      }else {
        var newHrefAvanti = newHrefIndietro + 2;
      };
      $('.pag_avanti').attr('href','#hpstock_' + newHrefAvanti);
      $('.pag_indietro').attr('href','#hpstock_' + newHrefIndietro);

      $('#commoditiesName').html($('#hpstock_' + currentBox + ' .commoditiesNameLabel').attr('value'));
      $('#commoditiesFrom').html($('#hpstock_' + currentBox + ' .commoditiesFromLabel').attr('value'));


    });
    $('.pag_avanti').click(function(){
      var oldHrefAvanti = $('.pag_avanti').attr('href').split('_');
      var newHrefAvanti = Math.floor(oldHrefAvanti[1])+1;
      var currentBox = newHrefAvanti - 1;
      if (newHrefAvanti>boxNumber){newHrefAvanti=boxNumber};
      if (newHrefAvanti==boxNumber){
        var newHrefIndietro = boxNumber-1;
      }else {
        var newHrefIndietro = newHrefAvanti - 2;
      };
      $('.pag_avanti').attr('href','#hpstock_' + newHrefAvanti);
      $('.pag_indietro').attr('href','#hpstock_' + newHrefIndietro);

      $('#commoditiesName').html($('#hpstock_' + currentBox + ' .commoditiesNameLabel').attr('value'));
      $('#commoditiesFrom').html($('#hpstock_' + currentBox + ' .commoditiesFromLabel').attr('value'));

    });
  };

  if ($('.paginatore').is('div')){
    var boxNumber = $('.scrollContainer').find('.panel').length;
    $('.pag_indietro').click(function(){
      var oldHrefIndietro = $('.pag_indietro').attr('href').split('_');
      var newHrefIndietro = Math.floor(oldHrefIndietro[1])-1;
      if (newHrefIndietro==0){newHrefIndietro=1};
      if (newHrefIndietro==1){
        var newHrefAvanti = 2;
      }else {
        var newHrefAvanti = newHrefIndietro + 2;
      };
      $('.pag_avanti').attr('href','#models_' + newHrefAvanti);
      $('.pag_indietro').attr('href','#models_' + newHrefIndietro);
    });
    
    $('.pag_avanti').click(function(){
      var oldHrefAvanti = $('.pag_avanti').attr('href').split('_');
      var newHrefAvanti = Math.floor(oldHrefAvanti[1])+1;
      if (newHrefAvanti>boxNumber){newHrefAvanti=boxNumber};
      if (newHrefAvanti==boxNumber){
        var newHrefIndietro = boxNumber-1;
      }else {
        var newHrefIndietro = newHrefAvanti - 2;
      };
      $('.pag_avanti').attr('href','#models_' + newHrefAvanti);
      $('.pag_indietro').attr('href','#models_' + newHrefIndietro);
    });     
   };
}

function handleSelectYear() {
  $(".selectyear").hover(function(){
    $('.selectyear ul').css('display','block');
  },function(){ 
    $('.selectyear ul').css('display','none');
  });
}

function handlePsColDx(){
  if($('#ps_download').is('div')){
    $('#c_coldx').css({height:'495px',minHeight:'495px',paddingTop:'330px'});
  }
}
function handleWeColDx(){
  if($('.box_cd.colddx_new_trans').is('div')){
    $('#c_coldx').css({height:'645px',minHeight:'645px',paddingTop:'180px'});
  }
  else if($('#ps_download').is('div')){
    $('#c_coldx').css({height:'535px',minHeight:'535px',paddingTop:'290px'});
  }
}
function switchTab() {
  $(".tab_btn span").click(function(){
    var tab = $(this).attr("id");
    $(".tab_tab").css("display","none");
    $("#" + tab + "_tab").css("display","block");
    $(".tab_btn span").removeClass('on');
    $(this).addClass('on');
  });
}

function loadProdGallery(){
$('#p_ssp').media({ 
    width:     520, 
    height:    386, 
    autoplay:  true, 
  attrs:     {wmode : 'transparent',scale:'noscale',bgcolor : 'none'}, 
  params:    {wmode : 'transparent',scale:'noscale',bgcolor : 'none'},  
    src:       'swf/prod_gallery.swf',
    flashvars:  {}, 
    caption:   false
}); 
}

function loadTestimonialGallery(){
$('#tst_gallery').media({ 
    width:     520, 
    height:    386, 
    autoplay:  true, 
  attrs:     {wmode : 'transparent',scale:'noscale',bgcolor : 'none'}, 
  params:    {wmode : 'transparent',scale:'noscale',bgcolor : 'none'},  
    src:       'swf/testimonial_gallery.swf',
    flashvars:  {}, 
    caption:   false
});
}

function loadNhpeopleGallery(){
$('#nhp_c_flash').media({ 
    width:     520, 
    height:    300, 
    autoplay:  true, 
    attrs:     {wmode : 'transparent',scale:'noscale',bgcolor : 'none'}, 
    params:    {wmode : 'transparent',scale:'noscale',bgcolor : 'none'},  
    src:       'swf/nh_people.swf',
    flashvars:  {}, 
    caption:   false
});
}


// BEGIN - g.rogato * 07.04.2009
// select current weather subframe
function getWeatherIdx() {
    var today = new Date();
    var hour  = today.getHours();
    var index = 1;
   
         if (hour >= 0 && hour <=  6) index = 1;
    else if (hour >= 7 && hour <= 13) index = 2;
    else                              index = 3;
   
    return index;
}
 
function hasWeatherURL(url) {   
   var reWeather = new RegExp("#hpweather_", "g");  
   return reWeather.test(url);
}

function getWeatherURL() {   
   var random = Math.floor(Math.random() * 1024)
   var url    = $('#marketUrlHp').html() + "&random=" + random + "#hpweather_" + getWeatherIdx();
   return url;
}
// END   - g.rogato * 07.04.2009

function switchTabSW() {

   $('#hp_swtab_stock').click(function(){
    $('#hp_swtab').css('background-position','0 0');
    $('#hp_weather_wrap').css('display','none');
    $('#hp_stock_wrap').css('display','block');
    
    
  });
  
  $('#hp_swtab_weather').click(function(){
    $('#hp_swtab').css('background-position','-235px 0');
    $('#hp_stock_wrap').css('display','none');
    $('#hp_weather_wrap').css('display','block');
    
    // BEGIN: setting weather time frame
    var src = $('iframe#frm_weather').attr("src");
    if (!hasWeatherURL(src)) {        
        $('iframe#frm_weather').attr("src", getWeatherURL());
    }   
    // END  : setting weather time frame
  });
  
}

function getMousePos(){
   var top = $('#map').offset().top
   var left = $('#map').offset().left
   var wpzBorder = 74;
   var pointOffset = 15;
  $('#detail_top').hover(function(){
    
     var mouseX = 0;   
     var mouseY = 0;
   $('#tip').css('display','block');
     $().mousemove( function(e) {
        mouseX = parseInt(e.pageX - left - pointOffset);
         mouseY = e.pageY - top - wpzBorder - pointOffset;    
       $('p.x').html('left: '+mouseX);
       $('p.y').html('top: '+mouseY);    
      });
},function(){  
  $('#tip').css('display','none');
    $().unbind( "mousemove" );  
  })
}

function getMousePosHp(){
   var top = $('#img_hotspots').offset().top
   var left = $('#img_hotspots').offset().left   
   var wpzBorder = 74;
   var pointOffset = 42;

  $('#hotspots_hp').hover(function(){    
     var mouseX = 0;   
     var mouseY = 0;
   $('#tip_hp').css('display','block');
     $('#hotspots_hp').mousemove( function(e) {
        mouseX = parseInt(e.pageX - left) - 15;
        mouseY = e.pageY - wpzBorder - top - 15;    
       $('p.x').html('left: '+mouseX);
       $('p.y').html('top: '+mouseY);    
      });
},function(){  
  $('#tip_hp').css('display','none');
    $().unbind( "mousemove" );  
  })
}

function openPopup(){
  $('#cfooter ul li a').click(function(){
    switch($(this).attr('id')){
      case "lnk_contacts":
      newWindow=window.open('popup/contacts.html','contacts','height=718,width=818,scrollbars=yes');
      if(!newWindow){alert('Attenzione: popup bloccati dal browser!')}
      break;
      case "lnk_terms":
      newWindow=window.open('popup/terms_conditions.html','Terms_of_use','height=718,width=818,scrollbars=yes');
      if(!newWindow){alert('Attenzione: popup bloccati dal browser!')}
      break;
      case "lnk_legal_notices":
      newWindow=window.open('popup/legal_notices.html','Legal_Notices','height=718,width=818,scrollbars=yes');
      if(!newWindow){alert('Attenzione: popup bloccati dal browser!')}
      break;
      case "lnk_privacy":
      newWindow=window.open('popup/privacy.html','privacy','height=800,width=818,scrollbars=yes');
      if(!newWindow){alert('Attenzione: popup bloccati dal browser!')}
      break;
      case "lnk_credits":
      newWindow=window.open('popup/credits.html','privacy','height=718,width=818,scrollbars=yes');
      if(!newWindow){alert('Attenzione: popup bloccati dal browser!')}
      break;    
    }
  
  })
}

function handleVideoLayer(){
  $('.thb_video').click(function(){
    var winX = window.innerWidth;
    var winY = window.innerHeight;
    var winx = winX/2
    
    var video_op_layer = document.createElement('div');
    video_op_layer.setAttribute('id','video_op_layer')
    var video_content_layer = document.createElement('div');
    video_content_layer.setAttribute('id','video_content_layer')
    var cvideo = document.createElement('div');
    cvideo.setAttribute('id','c_video')
    $(cvideo).css({})
    $(video_op_layer).css('height', $('#layout').height())
    $(video_op_layer).css('width', $(window).width())
    $(video_content_layer).css('height', $('#layout').height())
    $(video_content_layer).css('width', $(window).width());
    
    
    $('.sct_title').css('display','none');
    $('.subsct_title').css('display','none');
    $('#prod_navigator').css('display','none');
    
    $(video_content_layer).append(cvideo);
    $('#layout').append(video_op_layer);
    $('#layout').append(video_content_layer);
            
    $(cvideo).media({ 
        width:     343, 
        height:    276, 
        autoplay:  true,
        params:     {bgcolor : '#ffffff'},  
        attrs:     {bgcolor : '#ffffff'}, 
        src:         "swf/video_nh.swf",
        flashvars:  { height : 276,width :343,frontcolor : 0x666666,backcolor : 0xFFFFFF,lightcolor : 0xFFFFFF,overstretch : true,bufferlength : 5,usefullscreen : false, xmlFile:'xml/video.xml' }, 
        caption:   false
    });
    $("#c_video").css("position","relative");
    $("#c_video").append("<div id='video_content_chiudi'><img src='/PublishingImages/cnhimg/btns/btn_video_close.jpg' alt=''/></div>");
    $("#video_content_chiudi").css({
      position: "absolute",
      top: "-15px",
      right: "0"
    });
    $("#video_content_chiudi img").css("cursor","pointer");
    $("#video_content_chiudi img").click(function(){
      $("#video_op_layer").remove();
      $("#video_content_layer").remove();
    });
  })  
}

function checkMandatoryData(){
  $('#frm_contacts').submit(function(){
    formOk = true;
    if($('#cognome').val()==''){
      formOk = false
      $('#cognome').css('border','2px solid red;')
    }
    if($('#paese').val()==''){
      formOk = false
      $('#paese').css('border','2px solid red;')
    }
    if($('#commento').val()==''){
      $('#commento').css('border','2px solid red;')
      formOk = false
    }
    if($('#email').val()==''){
      $('#email').css('border','2px solid red;')
      formOk = false
    }
    if(formOk==false){
      $('#btn_send p').css('display','block')
    }
    
      return formOk
  })
}

function hideMenu() {
  $(".sitempap_block li ul").css("display","none");
  $(".sitempap_block li").each(function(){
      var hasli = $(this).find("li").length;
      if (hasli == 0) { $(this).find(">img").css("display","none")}
  });  
}

function activeMenu() {
  $(".sitempap_block li>img").click(function(){
    var img = $(this).attr('src');
    if (img == "/PublishingImages/cnhimg/shared/arrow_sm_1lev_on.gif"){
      $(this).parent().find(">ul").css("display","none");
      $(this).attr('src','/PublishingImages/cnhimg/shared/arrow_sm_1lev.gif');
    }
  if (img == "/PublishingImages/cnhimg/shared/arrow_sm_1lev.gif") {
      $(this).parent().parent().find('li').find('ul').css("display","none");
      $(this).parent().parent().find('li img').attr('src','/PublishingImages/cnhimg/shared/arrow_sm_2lev.gif');
      $(this).parent().find(">ul").css("display","block");
      $(this).attr('src','/PublishingImages/cnhimg/shared/arrow_sm_1lev_on.gif');
    }
    if (img == "/PublishingImages/cnhimg/shared/arrow_sm_2lev_on.gif"){
      $(this).parent().find(">ul").css("display","none");
      $(this).attr('src','/PublishingImages/cnhimg/shared/arrow_sm_2lev.gif');
    }
  if (img == "/PublishingImages/cnhimg/shared/arrow_sm_2lev.gif") {
      $(this).parent().parent().find('li').find('ul').css("display","none");
      $(this).parent().parent().find('li img').attr('src','/PublishingImages/cnhimg/shared/arrow_sm_2lev.gif');
      $(this).parent().find(">ul").css("display","block");
      $(this).attr('src','/PublishingImages/cnhimg/shared/arrow_sm_2lev_on.gif');
    }  
  });
}

function checkFlash() {
  var hasRequestedVersion = DetectFlashVer(9, 0, 0);
  if ( hasRequestedVersion  ) {  
  }
  else{
    $('#c_tool_sel').html('<div id="versionInfo" style="font-weight:bold;text-align:center;padding:100px 50px 0 50px"> Attenzione. Per visualizzare correttamente questa sezione &egrave; necessario avere installata una versione recente di flash player, scaricabile gratuitamente da <a href="http://get.adobe.com/it/flashplayer/"> questo link</a></div><div id="versionInfo" style="font-weight:bold;text-align:center;padding:100px 50px 0 50px"> You need the last versione of Adobe Flash Player. <a href="http://get.adobe.com/it/flashplayer/">Download it from here.</a></div>');
  }
}
function trimTextPsbox() {
  $('.ps_box_txt').each(function(){
    if ($(this).text().length > 100){
      myText = $(this).text().substring(0,97);
      $(this).text(myText + "...");
    }
  });
}
function trimTextPbox() {
  $('.p_txt_model').each(function(){
    if ($(this).text().length > 130){
      myText = $(this).text().substring(0,127);
      $(this).text(myText + "...");
    }
  });
}

function openLegend(){
  var legend_wrap = document.createElement('div');
  legend_wrap.setAttribute('id','legend_wrap')
  $('.open_legend a').click(function(){
  	$('#techspec').append(legend_wrap);
    var link = $(this).attr('href')
    $("#legend_wrap").load(link);
    return false;
  })
}

function sendfriend(){
  $('p#sendfriend').click(function(){
    var urlToSend = location.href;
    parent.location = 'mailto:?body=' + urlToSend;
    return false;
  });
}

function colSxHeight(){
  myHeight = $('#c_colsx').height();
  contHeight = $('#content').height();
  if (myHeight < contHeight){
    $('#c_colsx').css('min-height', contHeight+'px');
  };
}