/* jquery tip: to add an effect on all browsers BUT IE:
if(!$('.ie').length){
  //do something
}
*/

jQuery(function($){
  /* **********************
  FUNCTION DECLARATIONS
  ********************** */
  
  /* ************************ Read More ************************ */
  readMore = function(){
    $('.textMore').hide();
    $('.fr .textMore').after('<p class="readmore"><a href="#">Suite &raquo;</a></p>');
    $('.en .textMore').after('<p class="readmore"><a href="#">Read More &raquo;</a></p>');
  
    $('div.text > p.readmore a').click(function(){
      var $textMore = $(this).parents('.text').find('.textMore');
    
      if($textMore.length){
        if($('.ie').length){
          $textMore.show();
        }
        else{
          $textMore.css({opacity: '0'}).slideDown(250).fadeTo(500, 1);
        }
      
        $(this).parent().hide();
        return false;
      }
    });
  }
  
  /* ************************ Change image opacity on hover ************************ */
  changeImageOpacity = function(options){
    var defaultArgs = {
		  'elem' : [],
		  'amount' : '0.8',
		  'imgClass':	'',
		  'noImg': false,
		  'noImgSelector': ''
	  }
	  
	  for(var i in defaultArgs){
		  if(typeof options[i] == "undefined"){
		    options[i] = defaultArgs[i];
		  }
	  }
	  
	  var $elem = options['elem'];
    var amount = options['amount'];
    var imgClass = options['imgClass'];
    var noImg = options['noImg'];
    var noImgSelector = options['noImgSelector'];
    
    $elem.find('a').hover(function(){
      if(noImg && noImgSelector == ''){
        $(this).stop().fadeTo(250,amount);
      }
      else{
        $(this).find(noImgSelector != '' ? noImgSelector : 'img').stop().fadeTo(250,amount);
      }
    }, function(){
      if(noImg && noImgSelector == ''){
        $(this).stop().fadeTo(250,1);
      }
      else{
        $(this).find(noImgSelector != '' ? noImgSelector : 'img').stop().fadeTo(250,1);
      }
    });
  }
  
  /* ************************ Makes an element follow when we scroll ************************ */
  moveUpDown = function(options){
    var defaultArgs = {
		  'elem' : [],
		  'paddingTop' : 10,
		  'stop': ''
	  }
	  
	  for(var i in defaultArgs){
		  if(typeof options[i] == "undefined"){
		    options[i] = defaultArgs[i];
		  }
	  }
	  
	  var $elem = options['elem'];
    var paddingTop = options['paddingTop'];
    var stopScroll = options['stop'];
    
    var elemHeight = $elem.height();
    var startScroll = $elem.offset().top - paddingTop;
    
    $(window).scroll(function(){
      var globalScroll = $(this).scrollTop();
      
      if(globalScroll >= startScroll && globalScroll <= ($(document).height() - stopScroll - elemHeight)){
        $elem.css({
          top: (parseInt(globalScroll) - parseInt(startScroll))
        });
      }
      else if(globalScroll > ($(document).height() - stopScroll - startScroll - elemHeight)){
        $elem.css({
          top: ($(document).height() - stopScroll - startScroll - elemHeight)
        });
      }
      else{
        $elem.css({
          top: 0
        });
      }
    });
  }
  
  /* ************************ Submit btns - use js version (replace the default input by a "cooler" button) ************************ */
  switchSubmitBtns = function(){
    $('.quickform form .frmbtn input').remove();
    $('.quickform form .frmbtn div').show();
  }
  
  /* ************************ Main nav animation ************************ */
  mainnavAnim = function(){
    /* ************************ Main nav slider ************************ */
    mainnavMove = function($trigger){
      var thumbPosLeft = $trigger.position().left;
      var thumbPadLeft = $trigger.css('padding-left');
      var sliderPosLeft = thumbPosLeft + parseInt(thumbPadLeft.substr(0, thumbPadLeft.length-2));
      var sliderWidth = $trigger.width();
      
      $slider.animate({
        'left': sliderPosLeft + 'px',
        'width': sliderWidth + 'px'
      }, 500);
    }
    
    mainnavShowSlider = function($trigger){
      if($slider.width() <= 0){
        var thumbPosLeft = $trigger.position().left;
        var thumbPadLeft = $trigger.css('padding-left');
        var sliderPosLeft = thumbPosLeft + parseInt(thumbPadLeft.substr(0, thumbPadLeft.length-2));
        var sliderWidth = $trigger.width();
      
        $slider.css({
          'left': thumbPosLeft + parseInt(thumbPadLeft.substr(0, thumbPadLeft.length-2)) + parseInt($trigger.width() / 2)
        }).animate({
          'left': sliderPosLeft + 'px',
          'width': sliderWidth + 'px'
        }, 500);
      }
      
      mainnavMove($trigger);
    }
    
    mainnavHideSlider = function($trigger){
      var thumbPosLeft = $trigger.position().left;
      var thumbPadLeft = $trigger.css('padding-left');
      
      $slider.stop().animate({
        'left': thumbPosLeft + parseInt(thumbPadLeft.substr(0, thumbPadLeft.length-2)) + parseInt($trigger.width() / 2),
        'width': '0'
      }, 100, function(){
        $slider.css({'left': '0'});
      });
    }
    
    $('#mainnav').append('<span class="slider"></span>');
    
    var $slider = $('#mainnav .slider');
    var mainnavHasCurrent = false;
    var $mainnavCurrent = $('#mainnav .navLists li.current');
    
    if($mainnavCurrent.length){
      mainnavHasCurrent = true;
      mainnavShowSlider($mainnavCurrent);
    }
    
    $('#mainnav .navLists li').hover(function(){
      var $thisItem = $(this);
      
      if(mainnavHasCurrent){
        mainnavHasCurrent = false;
      }
      else if($slider.width() > 0){
        clearTimeout(menuStop);
      }
      
      mainnavShowSlider($thisItem);
    }, function(){
      var $thisItem = $(this);
      
      $slider.stop();
      
      menuStop = setTimeout(function(){
        if($mainnavCurrent.length){
          mainnavShowSlider($mainnavCurrent);
        }
        else{
          mainnavHasCurrent = true;
          mainnavHideSlider($thisItem);
        }
      });
    });
  }
  
  /* ************************ Header slides ************************ */
  allowSlideSwitch = 1;
  
  /* Ajax load */
  loadHeaderSlides = function(){
    $('#headerslidesWrap').load('/fr/inc_headerslides.spy #headerslides', function(){
      if(!$('body.talltop').length){
        $('body').addClass('talltop');
      }
      
      $('#headerslidesWrap').show();
      $('#headerslidesWrap').append('<div class="flag"></div>');

      if($('.ie').length){
        $('#headerslidesWrap').prepend('<div id="headerslidesBG"></div>');
        $('#headerslidesWrap .flag').show();
      }
      else{
        $('#headerslidesWrap .flag').fadeTo(500,1);
      }
      
      $('#headerslidesWrap').fadeTo(500,1, function(){
        var currentSlide = 0;
        var nextSlide = currentSlide + 1;
        startHeaderSlides(currentSlide, nextSlide);
        
        if($('.ie').length){
          $('#headerslidesThumbs').show();
        }
        else{
          setTimeout(function(){
            $('#headerslidesThumbs').fadeTo(500,1);
          }, 1000);
        }
      });
    });
  }
  
  /* change slide */
  switchHeaderSlides = function(current, next){
    hideHeaderSlide(current);
    
    setTimeout(function(){
      showHeaderSlide(next);
    }, 750);
  }
  
  /* make next slide appear */
  showHeaderSlide = function(next){
    var carTop = '30px';
    var shadowBottom = '34px';
    
    if(next == 1){
      carTop = '20px';
      shadowBottom = '39px';
    }
    else if(next == 2){
      carTop = '25px';
      shadowBottom = '31px';
    }
    else if(next == 3){
      carTop = '26px';
      shadowBottom = '35px';
    }
    
    $('#headerslides' + next + ' .headerslidesContent').animate({
      'left':'70px'
    },1000,'easeOutExpo',function(){
      $(this).css({'z-index':'50'});
      
      if($('.ie').length){
        $('#headerslides').css({'z-index':'50'});
      }
    });
    
    $('#headerslides' + next + ' .car').animate({
      'top':carTop
    },1000,'easeOutBounce');
    
    if($('.ie').length){
      $('#headerslides' + next + ' .carshadow').animate({
        'bottom':shadowBottom
      },1000,'easeOutBounce',function(){
        allowSlideSwitch = 1;
      });
    }
    else{
      $('#headerslides' + next + ' .carshadow').animate({
        'bottom':shadowBottom,
        'opacity':1
      },1000,'easeOutBounce',function(){
        allowSlideSwitch = 1;
      });
    }
  }
  
  /* hide visible slide */
  hideHeaderSlide = function(current){
    $('#headerslides' + current).animate({
      'left':'980px'
    },750,'easeInExpo',function(){
      $('#headerslides' + current + ' .headerslidesContent').css({
        'left':'-420px',
        'z-index':'0'
      });
      
      if($('.ie').length){
        $('#headerslides').css({'z-index':'0'});
      }
    
      $('#headerslides' + current + ' .car').css({
        'top':'-300px'
      });
      
      if($('.ie').length){
        $('#headerslides' + current + ' .carshadow').css({
          'bottom':'-200px'
        });
      }
      else{
        $('#headerslides' + current + ' .carshadow').css({
          'bottom':'-200px',
          'opacity':0
        });
      }
      
      $('#headerslides' + current).css({
        'left':'0'
      });
    });
  }
  
  /* start the slideshow by showing the first slide */
  startHeaderSlides = function(current, next){
    showHeaderSlide(current);
    
    $('#headerslidesThumbs li a').click(function(){
      if(allowSlideSwitch){
        allowSlideSwitch = 0;
      
        var $triggerItem = $(this).parent();
        var $triggerID = $triggerItem.attr('id');
        var triggerNum = parseInt($triggerID.substring($triggerID.length-1));
      
        if(current != triggerNum){
          $('#headerslidesThumbs li').removeClass('current');
          $triggerItem.addClass('current');
        
          next = triggerNum;
          switchHeaderSlides(current, next);
        
          current = next;
        }
        else{
          allowSlideSwitch = 1;
        }
      }
      
      $(this).blur();
      
      return false;
    });
  }
  
  /* ************************ Custom form validation ************************ */
  customForm = function(){
    var couponformSubmit = true;
    
    if(window.RegExp){
      var regexAlpha = /^[A-Za-zÀàÂâÉéÈèÊêËëÎîÏïÔôÖöÙùÛûÇç \-\'\.]+$/;
      var regexEmailNo = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
      var regexEmailYes = /^.+\@(\[?)[A-Za-z0-9\-\.]+\.([A-Za-z]{2,4}|[0-9]{1,3})(\]?)$/;
      
      var regexNotEmpty = /^.+$/;
      var regexOnlySpace = /^ +$/;
    }
    
    /* #quickcoupon validation */
    couponValidation = function(elem){
      var $formElem = elem;
      
      if(!couponformSubmit) return false;
      couponformSubmit = false;
      
      if(!regexNotEmpty.test($('#couponName').val()) || regexOnlySpace.test($('#couponName').val())){
        $('#couponName').parent().find('.quickformError').fadeIn(250);
      }
      else{
        $('#couponName').parent().find('.quickformError').hide();
      }
      
      if(!regexNotEmpty.test($('#couponPhone').val()) || regexOnlySpace.test($('#couponPhone').val())){
        $('#couponPhone').parent().find('.quickformError').fadeIn(250);
      }
      else{
        $('#couponPhone').parent().find('.quickformError').hide();
      }
      
      if(!(!regexEmailNo.test($('#couponEmail').val()) && regexEmailYes.test($('#couponEmail').val()))){
        $('#couponEmail').parent().find('.quickformError').fadeIn(250);
      }
      else{
        $('#couponEmail').parent().find('.quickformError').hide();
        
        if($('#couponEmail').val() != $('#couponEmail2').val()){
          $('#couponEmail2').parent().find('.quickformError').fadeIn(250);
        }
        else{
          $('#couponEmail2').parent().find('.quickformError').hide();
        }
      }
      
      if($formElem.find('.quickformError:visible').length){
        couponformSubmit = true;
        return false;
      }
      else{
        return true;
      }
    }
    
    if($('#quickcoupon').length){
      $('#quickcoupon form').submit(function(){
        return couponValidation($(this));
      });
    
      $('#quickcoupon form .frmbtn a').click(function(){
        $(this).blur();
      
        $('#quickcoupon form').submit();
      
        return false;
      });
    }
  }
  
  /* ************************ Featured Promos (activated through loadHeaderSlides) ************************ */
  featPromos = function(){
    var $featpromosImg = $('#homepromos .homefeatContent .featpromosImage');
    var $featpromosGen = $('#homepromos .homefeatContent .featpromosGen');
    var $featpromosVeh = $('#homepromos .homefeatContent .featpromosVeh');
    var resizeTempPos = 0;
    
    /*
    resizePromos = function(width,height,$image){
      var maxWidth = width;
      var maxHeight = height;
      var tempWidth = 0;
      var tempHeight = 0;
      var realImgWidth = 0;
      var realImgHeight = 0;
      var imageSRC = $image.attr('src');
      
      $('<img/>') // Make in memory copy of image to avoid css issues
        .attr('src', imageSRC)
        .load(function(){
          realImgWidth = this.width;   // Note: $(this).width() will not work for in memory images.
          realImgHeight = this.height;
          
          var tempRatio = realImgWidth / realImgHeight;
          
          if(realImgWidth > maxWidth){
            tempWidth = maxWidth;
            tempHeight = tempWidth / tempRatio;
          }
          if(tempHeight != 0 && (tempHeight > maxHeight)){
            tempHeight = maxHeight;
            tempWidth = tempHeight * tempRatio;
          }
          if(tempHeight == 0 && (realImgHeight > maxHeight)){
            tempHeight = maxHeight;
            tempWidth = tempHeight * tempRatio;
          }
        
          if(tempWidth != 0 || tempHeight != 0){
            $image.width(tempWidth + 'px');
            $image.height(tempHeight + 'px');
          }
          
          $image.attr('src',imageSRC);
        });
    }
    */
    
    /*
    resizeMultiPromos = function(imageList){
      imgObjectList = new Array();
      for(a=0; a<imageList.length; a++){
        imgObjectList[a] = new Image();
        
        $(imgObjectList[a]).load(function(){
          tempRatio = this.width / this.height;
          if (this.width > this.maxWidth){
            tempWidth = this.maxWidth;
            tempHeight = tempWidth / tempRatio;
          }
          if (tempHeight != 0 && (tempHeight > this.maxHeight)){
            tempHeight = this.maxHeight;
            tempWidth = tempHeight * tempRatio;
          }
          if (tempHeight == 0 && (this.height > this.maxHeight)){
            tempHeight = this.maxHeight;
            tempWidth = tempHeight * tempRatio;
          }
          if (tempWidth != 0 || tempHeight != 0){
            document.getElementById('featpromosPic'+this.num).style.width = tempWidth;
            document.getElementById('featpromosPic'+this.num).style.height = tempHeight;
          }
          
          document.getElementById('featpromosPic'+this.num).src = this.src;
        });
        
        imgObjectList[a].maxWidth = imageList[a][0];
        imgObjectList[a].maxHeight = imageList[a][1];
        imgObjectList[a].src = imageList[a][2];
        imgObjectList[a].num = parseInt(imageList[a][3].substr(imageList[a][3].length-1));
      }
    }
    */
    resizePromos = function(maxwidth,maxheight,image,imgId){
      maxWidth = maxwidth;
      maxHeight = maxheight;
      tempWidth = 0;
      tempHeight = 0;
      var promoImage = new Image();
      
      promoImage.onload = function(){ 
        tempRatio = promoImage.width / promoImage.height;
        
        if (promoImage.width > maxWidth){
          tempWidth = maxWidth;
          tempHeight = tempWidth / tempRatio;
        }
        if (tempHeight != 0 && (tempHeight > maxHeight)){
          tempHeight = maxHeight;
          tempWidth = tempHeight * tempRatio;
        }
        if (tempHeight == 0 && (promoImage.height > maxHeight)){
          tempHeight = maxHeight;
          tempWidth = tempHeight * tempRatio;
        }
        if (tempWidth != 0 || tempHeight != 0){
          document.getElementById(imgId).style.width = tempWidth;
          document.getElementById(imgId).style.height = tempHeight;
        }
        document.getElementById(imgId).src = image;
      }
      promoImage.src = image;
    }
    
    if($featpromosImg.length){
      $featpromosImg.each(function(){
        if($(this).find('.img img').length){
          resizePromos('153','150',$(this).find('.img img').attr('src'),$(this).find('.img img').attr('id'));
        }
      });
    }
    
    if($featpromosGen.length){
      $featpromosGen.each(function(){
        if($(this).find('.img img').length){
          resizePromos('153','81',$(this).find('.img img').attr('src'),$(this).find('.img img').attr('id'));
        }
      });
    }
    
    if($featpromosVeh.length){
      $featpromosVeh.each(function(){
        if($(this).find('.img img').length){
          resizePromos('153','81',$(this).find('.img img').attr('src'),$(this).find('.img img').attr('id'));
        }
      });
    }
    
    /*
    if($featpromosImg.length){
      $featpromosImg.each(function(){
        if($(this).find('.img img').length){
          $promolist[$promolist.length] = ['153','150',$(this).find('.img img'),$(this).find('.img img').attr('id')];
        }
      });
    }
    
    if($featpromosGen.length){
      $featpromosGen.each(function(){
        if($(this).find('.img img').length){
          $promolist[$promolist.length] = ['153','81',$(this).find('.img img'),$(this).find('.img img').attr('id')];
        }
      });
    }
    
    if($featpromosVeh.length){
      $featpromosVeh.each(function(){
        if($(this).find('.img img').length){
          $promolist[$promolist.length] = ['153','81',$(this).find('.img img'),$(this).find('.img img').attr('id')];
        }
      });
    }
    
    resizeMultiPromos($promolist);
    */
    
    
    /*
    if($featpromosImg.length){
      $featpromosImg.each(function(){
        if($(this).find('.img img').length){
          resizePromos('153','150',$(this).find('.img img'));
        }
      });
    }
    
    if($featpromosGen.length){
      $featpromosGen.each(function(){
        if($(this).find('.img img').length){
          resizePromos('153','81',$(this).find('.img img'));
        }
      });
    }
    
    if($featpromosVeh.length){
      $featpromosVeh.each(function(){
        if($(this).find('.img img').length){
          resizePromos('153','81',$(this).find('.img img'));
        }
      });
    }
    */
  }
  
  /* ************************ Coupon Popup ************************ */
  couponPopup = function(){
    $('body').prepend('<div id="dlr_couponBg"></div>');
    
    if($('.nocouponpopbody').length){
      doNotSetListener = 1;
    }
  
    var couponMain = new dlr_buildPopup('couponMain', 'noCoupon', 1, 10);
    
    $('#couponMain .closebtn a').click(function(){
      couponMain.setCookie(0, 0);
      
      $(this).blur();
      
      return false;
    });
    
    $('.couponRepop a').click(function(){
      couponMain.showBox();
      
      $(this).blur();
      
      return false;
    });
  }
  
  /* -------------------------------------------------------------------------------------------- */
  
  /* **********************
  FUNCTION CALLS
  ********************** */
  
  $('body').addClass('js');
  
  readMore();             //Read More
  mainnavAnim();          //Main nav animation
  
  if($('.quickform').length){
    customForm();         //Custom form validation
  }
  
  if($('.homebody').length){
    loadHeaderSlides();   //Header slides
  }
  
  if($('#homepromos .homefeatContent').length){
    featPromos();         //Activates the js for the featured promos
  }
  
  if($('.newcarsinv').length){
    changeImageOpacity({  //Change opacity of an image on hover
      'elem' : $('.newcarsinv'),
      'amount' : '0.7'
    });
  }
  
  if($('#popGallery').length){
    moveUpDown({  //Makes an element follow when we scroll
      'elem' : $('#popGallery')
    });
  }
  
  if($('#sidebarScroll').length){
    moveUpDown({  //Makes an element follow when we scroll
      'elem' : $('#sidebarScroll'),
      'stop' : '500'
    });
  }
  
  if($('#couponMain').length){
    switchSubmitBtns();   //Submit btns - use js version
    couponPopup();        //Activates the coupon popup
  }
});
