$(document).ready(function() {
    jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    }
   $("input#findText").click(function(){
       if($(this).val()=='Vehicle search...'){
           $(this).val('');
       }
   }); 
   $('a.toLightBox').lightBox();
   $(".showTab").click(function(){
       var tabTocheck = $(this).attr("id").replace("show","");
       var tabToHide = tabTocheck.replace(/[0-9$-]/g, "");
       $("div."+tabToHide).hide();
       $("div#"+tabTocheck).show();
       $(this).parent().parent().children().children('a').removeClass('active');
       $(this).addClass('active');
       return false;
   });
   
   // uwaga -> nadawanei scrolli dla hide nei działa -> najpierw dodajemy, potem chowamy
   $('.dataOfferScrollbar, .dataOfferScrollbar2').jScrollbar();
   
   $(".toHide").hide();
   
   $("div.start").show();
      
   $(".smallImageContainer a").click(function(){
       var src = $(this).children('img').attr('src');
       var srcToMiddle = src.replace("83", "278");
       srcToMiddle = srcToMiddle.replace("56", "200");
       $("div#bigImageContainer > a > img").attr('src',srcToMiddle);
       var srcToBig = src.replace("83", "");
       srcToBig = srcToBig.replace("56", "");
       $("div#bigImageContainer > a").attr('href',srcToBig);
       $(".smallImageContainer").removeClass('smallImageContainerSelected');
       $(this).parent().addClass('smallImageContainerSelected');
       var sIdImage = $(this).children("img").attr('id').replace('image_','');
       $("#imageSelected").html(sIdImage);
       return false;
   });
   
   //przesuwanie obrazków dla ofert
   $(".scrollImages").click(function(){
       var direction = $(this).attr('id');
       scrollImages(direction);
       return false;
   });
   
   //formularze
   
   //dla wyboru rodzaju auta
   $(".car_type").click(function(){
       getOfferTypes();
       loadMakes();
      loadModels();
       getMinPrice();
        getMaxPrice();
      $("span#budget").html("£"+$("input#minPrice").val()+" - " + "£"+$("input#maxPrice").val());
      loadFuelTypes();
      loadTransmissions();
      countCars();
      var url = getUrl(); 
      $("form#searchCars").attr('action',url);
    });
   
   $("select#carOfferType").change(function(){
      loadMakes();
      loadModels();
      getMinPrice();
      getMaxPrice();
      $("span#budget").html("£"+$("input#minPrice").val()+" - " + "£"+$("input#maxPrice").val());
      
      loadFuelTypes();
      loadTransmissions();
      countCars();
      var url = getUrl(); 
      $("form#searchCars").attr('action',url);
      var selectedOfferType = $("select#carOfferType").val();
      if(selectedOfferType=='leasingcars'){
        $("#budgetSlider").slider({step: 20});
      }
      else{
        $("#budgetSlider").slider({step: 100});
    }
   });
   
    $("select#make").change(function(){
      loadModels();
      getMinPrice();
      getMaxPrice();
      $("span#budget").html("£"+$("input#minPrice").val()+" - " + "£"+$("input#maxPrice").val());
      
      loadFuelTypes();
      loadTransmissions();
      countCars();
      var url = getUrl(); 
      $("form#searchCars").attr('action',url);
      
   });
   
    $("select#model").change(function(){
      getMinPrice();
      getMaxPrice();
      $("span#budget").html("£"+$("input#minPrice").val()+" - " + "£"+$("input#maxPrice").val());
      
      loadFuelTypes();
      loadTransmissions();
      countCars();
      var url = getUrl(); 
      $("form#searchCars").attr('action',url);
   });
   
   $("select#fuelType").change(function(){
      loadTransmissions(); 
      countCars();
      var url = getUrl(); 
      $("form#searchCars").attr('action',url);
   });
   
   $("select#transmission").change(function(){
      countCars();
      var url = getUrl(); 
      $("form#searchCars").attr('action',url);
   });
   
   $("select#orderby").change(function(){
      var url = getUrl();
      $(location).attr('href',url);
    });
    
    $("select#itemsperpage").change(function(){
      var url = getUrl();
      $(location).attr('href',url);
    });
    
    $("select#contractHireMileages").change(function(){
        loadContractHireYears();
        loadContractHirePrice();
        loadContractHireInitialPrice();
        calculateLeasingPrices();
    });
    
    $("select#contractHireYears").change(function(){
        loadContractHirePrice();
        loadContractHireInitialPrice();
        calculateLeasingPrices();
    });
    
    //oblicznie ceny dla new offer przy wyborze opcji płatnych
    $(".paintOptionPrice, .otherOptionPrice").click(function(){
        calculateNewPrices();
    })
    $(".paintOptionPriceLeasing, .otherOptionPriceLeasing").click(function(){
        calculateLeasingPrices();
    })
    
    $("a#toggleAdvancesSearch").click(function(){
        $("div#advancedSearch").toggle();
        return false;
    });
    
    //popup dla search
    $("#findText").click(function(){
        $("span#searchTextPopup").html($("input#findText").val());
        $("#findPopup").show();
    });
    
    $("#findText").keyup(function(){
        $("span#searchTextPopup").html($("input#findText").val()+' ');
    });
    
    $("a#closePopupSearch").click(function(){
        $("#findPopup").hide();
        return false;
    });
   
   $("a#nextSay").click(function(){
       nextSay();
       return false;
   });
   //fixPathImages(); wyłączam i naprawiam w modelu, przed załadowaniem
   
    $("input#Callme").click(function(){
        sendSepakToAHuman();
        return false;
    });
    
    $("input#Enquiresend").click(function(){
        sendEnquire();
        return false;
    });
    
    $("input#Booktestdrivesend").click(function(){
        sendBookTestDrive();
        return false;
    });
    
    $("input#Requestaquotesend").click(function(){
        sendRequestAQuote();
        return false;
    });
    
    $("input#Readytorodersend").click(function(){
        sendReadyToOrder();
        return false;
    });
    
     $("input#Partnershipsend").live("click", function(){
            sendPartnership();
            return false;
     });
     
     $("input#Ltdcompanysend").live("click", function(){
            sendLtdCompany();
            return false;
     });
     
     $("input#Privateindividualsend").live("click", function(){
            sendPrivateIndividual();
            return false;
     });
    
    $("input#Soletradersend").live("click", function(){
            sendSoleTrader();
            return false;
     });
     
    $("input.clearclick").click(function(){
        var sCheckVal = $(this).val();
        if(sCheckVal=='Enter your name' || sCheckVal=='Enter your number'){
            $(this).val('');
        }
    });
    
    //landing page dla new offer
     $("#landingForOffer #progressbar" ).progressbar({
        value: 0
     });
     
     $("#landingForOffer li.goNextStep").click(function(){
         goNextStep(this);
     });
     
     $("#landingForOffer a#nextStep").click(function(){
         goNextStep(this);
         return false;
     });
     
     $("#DataTab1 input:radio").removeAttr("checked","checked");
     $("#landingForOffer #question_1").show();
     $("#landingForOffer a#prevStep").click(function(){
         goPrevStep(this);
         return false;
     });
     $("#landingForOffer a#prevStep").hide();
     $("a#bookTestDrive").click(function(){
         $("div#requestAQuoteMain").hide();
         $("div#bookTestDriveMain").toggle();
         $("div#readyToOrderMain").hide();
         $("div#applyForCreditMain").hide();
     });
     $("a#requestQuote").click(function(){
         $("div#requestAQuoteMain").toggle();
         $("div#bookTestDriveMain").hide();
         $("div#readyToOrderMain").hide();
         $("div#applyForCreditMain").hide();
     });
     
     $("a#readyToOrder").click(function(){
         $("div#requestAQuoteMain").hide();
         $("div#bookTestDriveMain").hide();
         $("div#readyToOrderMain").toggle();
         $("div#applyForCreditMain").hide();
     });
     
     $("a#applyForCredit").click(function(){
         $("div#requestAQuoteMain").hide();
         $("div#bookTestDriveMain").hide();
         $("div#readyToOrderMain").hide();
         $("div#applyForCreditMain").toggle();
     });
     
     $("#book_date,#book_date_of_birth").datepicker();
     
     //loadApplyForCreditForm();
     
     $("#apply_customer_type").change(function(){
         loadApplyForCreditForm();
         $("div.applyForCreditErrorsTop, div.applyForCreditErrors").html('');
     });
     
     //ocenianie
     $("#stars-wrapper").stars({
         oneVoteOnly: true,
         callback: function(ui, type, value){
            saveVote(value);
        }
     });
     
     $('.removeFromGarage a').click(function(){
         removeFromGarage($(this).attr('id'));
         $(this).parent().parent().remove();
         return false;
     });
     
     $("select#ready_do_you_require_finance").change(function(){
         if($(this).val()=='Yes'){
             $("#readyToOrderMain").hide();
             $("#applyForCreditMain").show();
         }
     });
     
     $("input#[name=ready_do_you_have_a_part_exchange]").change(function(){
         if($(this).val()=='Yes'){
         $("#ready_part_exchange_make-label,#ready_part_exchange_make-element,#ready_part_exchange_model-label,#ready_part_exchange_make-element,#ready_part_exchange_model-label,#ready_part_exchange_model-element,#ready_part_exchange_mileage-label,#ready_part_exchange_mileage-element,#ready_part_exchange_reg_no-label,#ready_part_exchange_reg_no-element,#ready_part_exchange_car_info-label,#ready_part_exchange_car_info-element").show(); 
         }
         else{
            $("#ready_part_exchange_make-label,#ready_part_exchange_make-element,#ready_part_exchange_model-label,#ready_part_exchange_make-element,#ready_part_exchange_model-label,#ready_part_exchange_model-element,#ready_part_exchange_mileage-label,#ready_part_exchange_mileage-element,#ready_part_exchange_reg_no-label,#ready_part_exchange_reg_no-element,#ready_part_exchange_car_info-label,#ready_part_exchange_car_info-element").hide();
         }
     });
     $("#monthlyPrice").click(function(){
         $(".showTab").removeClass('active');
         $("#showDataTab5").addClass('active');
         $(".DataTab").hide();
         $("#DataTab5").show();
         $('html, body').animate({scrollTop: $("#showDataTab5").offset().top}, 500);
         return false;
     });
     
     if(sAction=='index'){
         if(iCountSpecialOffersNew>4){
             var $newCar = $('#specialNew');//we'll re use it a lot, so better save it to a var.
                $newCar.serialScroll({
                items:'div.specialOfferItem',
                prev:'img#scrollSpecialOffersLeftNew',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
                next:'img#scrollSpecialOffersRightNew',// Selector to the 'next' button (absolute too) 
                duration: 500,
                force:true,
                axis:'x',
                easing:'linear',
                constant:true,
                cycle:true,
                lazy:false,// NOTE: it's set to true, meaning you can add/remove/reorder items and the changes are taken into account.
                interval:10000, // yeah! I now added auto-scrolling
                step:4 // scroll 2 news each time
            }); 
         }

         if(iCountSpecialOffersLeasing>4){
             var $leasingCar = $('#specialLeasing');//we'll re use it a lot, so better save it to a var.
                $leasingCar.serialScroll({
                items:'div.specialOfferItem',
                prev:'img#scrollSpecialOffersLeftLeasing',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
                next:'img#scrollSpecialOffersRightLeasing',// Selector to the 'next' button (absolute too) 
                duration: 500,
                force:true,
                axis:'x',
                easing:'linear',
                constant:true,
                cycle:true,
                lazy:false,// NOTE: it's set to true, meaning you can add/remove/reorder items and the changes are taken into account.
                interval:10000, // yeah! I now added auto-scrolling
                step:4 // scroll 2 news each time
            }); 
         }

         if(iCountSpecialOffersCommercials>4){
             var $commercialCar = $('#specialCommercials');//we'll re use it a lot, so better save it to a var.
                $commercialCar.serialScroll({
                items:'div.specialOfferItem',
                prev:'img#scrollSpecialOffersLeftCommercials',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
                next:'img#scrollSpecialOffersRightCommercials',// Selector to the 'next' button (absolute too) 
                duration: 500,
                start: 0,
                force:true,
                axis:'x',
                easing:'linear',
                constant:true,
                cycle:true,
                lazy:false,// NOTE: it's set to true, meaning you can add/remove/reorder items and the changes are taken into account.
                interval:10000, // yeah! I now added auto-scrolling
                step:4 // scroll 2 news each time
            }); 
         }

         if(iCountSpecialOffersUsed>4){
             var $usedCar = $('#specialUsed');//we'll re use it a lot, so better save it to a var.
                $usedCar.serialScroll({
                items:'div.specialOfferItem',
                prev:'img#scrollSpecialOffersLeftUsed',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
                next:'img#scrollSpecialOffersRightUsed',// Selector to the 'next' button (absolute too) 
                duration: 500,
                force:true,
                cycle:true,
                axis:'x',
                easing:'linear',
                constant:true,
                lazy:false,// NOTE: it's set to true, meaning you can add/remove/reorder items and the changes are taken into account.
                interval:10000, // yeah! I now added auto-scrolling
                step:4 // scroll 2 news each time
            }); 
         }
     }
     $("#showAllUsedOptions").click(function(){
         $("#cutOptions").hide();
         $("#allOptions").show();
         return false;
     });
  });
  
  function saveVote(value){
    $.ajax({
        url: baseHref+"default/index/savevote",
        type: "POST",
        dataType: "html",
        data:$("#voteOffer").serialize()+"&value="+value,
        async:false,
        success: function(vote){
            $("#rateText").html(vote);
        }
    });
  }
  
  function sendPartnership(){
      $("div.applyForCreditErrors, div.applyForCreditErrorsTop").html("");
      var bEmptyErrors = false;
      var bPhoneErrors = false;
      var bEmailErrors = false;
      $(".errorLabel").removeClass('errorLabel');
      $(".sole_no_empty").each(
            function(){
                if(validate_text($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bEmptyErrors = true;
                }
            }
       );
           
       $(".sole_phone").each(
            function(){
                if(validate_phone($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bPhoneErrors = true;
                }
            }
       );
           
       $(".sole_email").each(
            function(){
                if(validate_email($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bEmailErrors = true;
                }
            }
       );
      if(bEmptyErrors == false && bPhoneErrors == false && bEmailErrors == false){
          $("form#Partnership").hide();
          $("#applyForCreditContainer div.tabLoader").show();
          $.ajax({
                url: baseHref+"default/index/sendmail",
                type: "POST",
                data: $("form#Partnership").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
                dataType: "html",
                async:false,
                success: function(data){
                     $("div#applyForCreditContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(bEmptyErrors==true){
              sErrors += 'You have to fill all fields! ';
          }
          if(bPhoneErrors==true){
              sErrors += 'Incorrect phone number! ';
          }
          if(bEmailErrors==true){
              sErrors += 'Incorrect e-mail address! ';
          }
          $("div.applyForCreditErrors, div.applyForCreditErrorsTop").html(sErrors);
          $("div.applyForCreditErrors, div.applyForCreditErrorsTop").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendLtdCompany(){
      $("div.applyForCreditErrors, div.applyForCreditErrorsTop").html("");
      var bEmptyErrors = false;
      var bPhoneErrors = false;
      var bEmailErrors = false;
      $(".errorLabel").removeClass('errorLabel');
      $(".sole_no_empty").each(
            function(){
                if(validate_text($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bEmptyErrors = true;
                }
            }
       );
           
       $(".sole_phone").each(
            function(){
                if(validate_phone($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bPhoneErrors = true;
                }
            }
       );
           
       $(".sole_email").each(
            function(){
                if(validate_email($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bEmailErrors = true;
                }
            }
       );
      if(bEmptyErrors == false && bPhoneErrors == false && bEmailErrors == false){
          $("form#Ltdcompany").hide();
          $("#applyForCreditContainer div.tabLoader").show();
          $.ajax({
                url: baseHref+"default/index/sendmail",
                type: "POST",
                data: $("form#Ltdcompany").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
                dataType: "html",
                async:false,
                success: function(data){
                     $("div#applyForCreditContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(bEmptyErrors==true){
              sErrors += 'You have to fill all fields! ';
          }
          if(bPhoneErrors==true){
              sErrors += 'Incorrect phone number! ';
          }
          if(bEmailErrors==true){
              sErrors += 'Incorrect e-mail address! ';
          }
          $("div.applyForCreditErrors, div.applyForCreditErrorsTop").html(sErrors);
          $("div.applyForCreditErrors, div.applyForCreditErrorsTop").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendSoleTrader(){      
      $("div.applyForCreditErrors, div.applyForCreditErrorsTop").html("");
      var bEmptyErrors = false;
      var bPhoneErrors = false;
      var bEmailErrors = false;
      $(".errorLabel").removeClass('errorLabel');
      $(".sole_no_empty").each(
            function(){
                if(validate_text($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bEmptyErrors = true;
                }
            }
       );
           
       $(".sole_phone").each(
            function(){
                if(validate_phone($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bPhoneErrors = true;
                }
            }
       );
           
       $(".sole_email").each(
            function(){
                if(validate_email($(this).val(),'')==false){
                     sElemGetId = $(this).attr('id');
                     sElemNewId = sElemGetId+'-label';
                    $("#"+sElemNewId).addClass('errorLabel');
                    bEmailErrors = true;
                }
            }
       );
      if(bEmptyErrors == false && bPhoneErrors == false && bEmailErrors == false){
          $("form#SoleTrader").hide();
          $("#applyForCreditContainer div.tabLoader").show();
          $.ajax({
                url: baseHref+"default/index/sendmail",
                type: "POST",
                data: $("form#SoleTrader").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
                dataType: "html",
                async:false,
                success: function(data){
                     $("div#applyForCreditContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(bEmptyErrors==true){
              sErrors += 'You have to fill all fields! ';
          }
          if(bPhoneErrors==true){
              sErrors += 'Incorrect phone number! ';
          }
          if(bEmailErrors==true){
              sErrors += 'Incorrect e-mail address! ';
          }
          $("div.applyForCreditErrors, div.applyForCreditErrorsTop").html(sErrors);
          $("div.applyForCreditErrors, div.applyForCreditErrorsTop").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendEnquire(){
      $("div.enquireErrors").html("");
      if(validate_email($("input#Your_email_address").val())==true && validate_phone($("input#Your_Best_Contact_number").val())==true && validate_text($("input#Your_first_name").val(),'')==true && validate_text($("input#Your_surname").val(),'')==true &&  validate_text($("select#Preffered_contact_time").val(),'')==true){
          $("form#Enquire").hide();
          $("#enquiryFormContainer div.tabLoader").show();
          $.ajax({
            url: baseHref+"default/index/sendmail",
            type: "POST",
            data: $("form#Enquire").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
            dataType: "html",
            async:false,
            success: function(data){
                 $("div#enquiryFormContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(validate_phone($("input#Your_Best_Contact_number").val())==false){
              sErrors += 'Incorrect phone number! ';
          }
          
          if(validate_email($("input#Your_email_address").val())==false){
              sErrors += 'Incorrect e-mail address! ';
          }
          
          if(validate_text($("input#Your_first_name").val(),'')==false || validate_text($("input#Your_surname").val(),'')==false || validate_text($("input#Preffered_contact_time").val(),'')==false){
              sErrors += 'You have to fill all fields! ';
          }
          
          $("div.enquireErrors").html(sErrors);
          $("div.enquireErrors").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendBookTestDrive(){
      $("div.bookTestDriveErrors").html("");
      if(validate_email($("input#book_email").val())==true && validate_phone($("input#book_best_contact_number").val())==true && validate_text($("input#book_full_name").val(),'')==true && validate_text($("input#book_date").val(),'')==true &&  validate_text($("input#book_date_of_birth").val(),'')==true &&  validate_text($("select#book_best_contact_time").val(),'')==true &&  validate_text($("select#book_date_of_birth").val(),'')==true){
          $("form#BookTestDrive").hide();
          $("#bookTestDriveContainer div.tabLoader").show();
          $.ajax({
            url: baseHref+"default/index/sendmail",
            type: "POST",
            data: $("form#BookTestDrive").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
            dataType: "html",
            async:false,
            success: function(data){
                 $("div#bookTestDriveContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(validate_phone($("input#book_best_contact_number").val())==false){
              sErrors += 'Incorrect phone number! ';
          }
          
          if(validate_email($("input#book_email").val())==false){
              sErrors += 'Incorrect e-mail address! ';
          }
          
          if(validate_text($("input#book_full_name").val(),'')==false || validate_text($("select#book_best_contact_time").val(),'')==false || validate_text($("input#book_date").val(),'')==false || validate_text($("select#book_time").val(),'')==false || validate_text($("input#book_date_of_birth").val(),'')==false){
              sErrors += 'You have to fill all fields! ';
          }
          
          $("div.bookTestDriveErrors").html(sErrors);
          $("div.bookTestDriveErrors").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendRequestAQuote(){
      $("div.requestAQuoteErrors").html("");
      if(validate_email($("input#request_email").val())==true && validate_phone($("input#request_best_contact_number").val())==true && validate_text($("input#request_full_name").val(),'')==true && validate_text($("select#request_best_contact_time").val(),'')==true &&  validate_textarea($("textarea#request_questions").val(),200)==true){
          $("form#RequestAQuote").hide();
          $("#requestAQuoteContainer div.tabLoader").show();
          $.ajax({
            url: baseHref+"default/index/sendmail",
            type: "POST",
            data: $("form#RequestAQuote").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
            dataType: "html",
            async:false,
            success: function(data){
                 $("div#requestAQuoteContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(validate_phone($("input#request_best_contact_number").val())==false){
              sErrors += 'Incorrect phone number! ';
          }
          if(validate_email($("input#request_email").val())==false){
              sErrors += 'Incorrect e-mail address! ';
          }
          
          if(validate_text($("input#request_full_name").val(),'')==false || validate_text($("select#request_best_contact_time").val(),'')==false ){
              sErrors += 'You have to fill all fields! ';
          }
          if(validate_textarea($("textarea#request_questions").val(),200)==false){
              sErrors += 'Questions should have max 200 characters!';
          }
          
          $("div.requestAQuoteErrors").html(sErrors);
          $("div.requestAQuoteErrors").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendReadyToOrder(){
      $("div.readyToOrderErrors").html("");
      var bEmptyErrors = false;
      
      $(".ready_no_empty").each(
            function(){
                if(validate_text($(this).val(),'')==false || $(this).val()=='Please enter your question or notes here, for example, how many vehicles you require?'){
                    bEmptyErrors = true;
                }
            }
       );
           
      $(".ready_no_empty_visible").each(function(){
          if($(this).parent().css('display')!='none'){
              if(validate_text($(this).val(),'')==false || $(this).val()=='Please describe your vehicles exact condition or note any factory or additional options'){
                    bEmptyErrors = true;
                }
          }
      });     
      
      if(validate_email($("input#ready_email_address").val())==true && validate_phone($("input#ready_preferred_contact_number").val())==true && bEmptyErrors == false){
          $("form#ReadyToOrder").hide();
          $("#readyToOrderContainer div.tabLoader").show();
          $.ajax({
            url: baseHref+"default/index/sendmail",
            type: "POST",
            data: $("form#ReadyToOrder").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
            dataType: "html",
            async:false,
            success: function(data){
                 $("div#readyToOrderContainer").html(data);
            }
        });
      }
      else{
          var sErrors = '';
          if(validate_phone($("input#ready_preferred_contact_number").val())==false){
              sErrors += 'Incorrect phone number! ';
          }
          if(validate_email($("input#ready_email_address").val())==false){
              sErrors += 'Incorrect e-mail address! ';
          }
          var sErrorsEmpty = '';
          $(".ready_no_empty").each(
                function(){
                    if(validate_text($(this).val(),'')==false || $(this).val()=='Please enter your question or notes here, for example, how many vehicles you require?'){
                      sErrorsEmpty = 'You have to fill all fields! ';
                   }
                }
          );
          
          $(".ready_no_empty_visible").each(function(){
          if($(this).parent().css('display')!='none'){
              if(validate_text($(this).val(),'')==false || $(this).val()=='Please describe your vehicles exact condition or note any factory or additional options'){
                    sErrorsEmpty = 'You have to fill all fields for Part Exchange! ';
                }
             }
        });    
      
          if(sErrorsEmpty!=''){
                sErrors += sErrorsEmpty;
          }
          $("div.readyToOrderErrors").html(sErrors);
          $("div.readyToOrderErrors").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function sendSepakToAHuman(){
      $("div#callToAHuman div.errorsHuman").html("");
      if(validate_phone($("input#phonenumber").val())==true && validate_text($("input#name").val(),'Enter your name')==true){
          $("form#CallToAHuman").hide();
          $("div#callToAHumanBox div.loading").show();
          $.ajax({
            url: baseHref+"default/index/sendmail",
            type: "POST",
            data: $("form#CallToAHuman").serialize(),
            dataType: "html",
            async:false,
            success: function(data){
                 $("div#callToAHumanBoxWrapper").html(data);
                 $("div#callToAHuman div.success").effect('shake', {
                        times: 3,
                        distance: 10
                    }, 100);
            }
        });
      }
      else{
          var sErrors = '';
          if(validate_phone($("input#phonenumber").val())==false){
              sErrors += 'Incorrect phone number<br />';
          }
          
          if(validate_text($("input#name").val(),'Enter your name')==false){
              sErrors += 'Incorrect name';
          }
          
          $("div#callToAHuman div.errorsHuman").html(sErrors);
          $("div#callToAHuman  div.errorsHuman").effect('shake', {
            times: 3,
            distance: 10
        }, 100);
      }
  }
  
  function validate_email(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(email) == false) {
        return false;
    }
    return true;
}
    
function validate_textarea(text,max) {
    if (text.length > max) {
        return false;
    } else {
        return true;
    }
}

function validate_text(text,defText) {
    if (text=='' || text == defText) {
        return false;
    } else {
        return true;
    }
}

function validate_phone(phone) {
    phone = phone.replace(/ /g,"");
    if (IsNumeric(phone) && phone.length > 7) {
        return true
    } else {
        return false;
    }
}

 function IsNumeric(input){
    return (input - 0) == input && input.length > 0;
}

  var iSay = 1;
  function nextSay(){
     if((iSay+1)>iCustomersSay){
        iSay = 1;
     }
     else{
        iSay++; 
     }
     
     $("div.customerSayItem").hide();
     $("div#say_"+iSay).show();
  }
  
  function fixPathImages(){
      //funkcja służy do patchaowania grafik dodanych do dokumentu. Zakąłdamy, ze adres panelu może się zmienić a z tamtąd pobierane są grafiki dla dokumentów
      // więc ścieżkę images/index/auto.jpg musimy zamienić na http://panel.citroenleasing.com/images/index/auto.jpg
      var src = '';
      var sNewSrc = '';
      $(".fixImages img").each( 
        function() { 
            src = $(this).attr('src');
            sNewSrc = imagesHref + '' + src;
            $(this).attr('src',sNewSrc);
        } 
    );
  }

var iImagesOffset = 1;
function scrollImages(direction){
    if(direction=='toLeftImages'){
        iImagesOffset--;
    }
    if(iImagesOffset<=0){
        iImagesOffset = 1;
    }
    if(direction=='toRightImages'){
        iImagesOffset ++;
    }
    if(iImagesOffset>Math.ceil(iImagesCount/3)){
        iImagesOffset = 1;
    }
    
    $(".smallImageContainer").hide();
    for(var iTemp = (iImagesOffset*3)-2; iTemp<=iImagesOffset*3;iTemp++){
        $("#imgContainer_"+iTemp).show();
    }
}


function getOfferTypes(){
    $("select#carOfferType").html("<option value=''>Loading...</option>");
    $.ajax({
        url: baseHref+"default/index/getoffertypes",
        type: "POST",
        dataType: "json",
        data:{carType: $('input.car_type:checked').val()},
        async:false,
        success: function(makes){
            var options = '';
            
             for (var i = 0; i < makes.length; i++) {
                var selected = '';
                if(sAction!='usedcars' && sAction!='usedoffer' && sAction!='newcars' && sAction!='newoffer' && sAction!='leasingcars' && sAction!='leasingoffer' && sAction!='commercials'){
                    if(sPage == 'CS' && makes[i].optionValue=='newcars'){
                        selected = 'selected = "selected"';
                    }

                    if(sPage == 'CL' && makes[i].optionValue=='leasingcars'){
                        selected = 'selected = "selected"';
                    } 
                }
                else{
                    if(makes[i].optionValue=='leasingcars' && sAction=='leasingcars' || makes[i].optionValue=='leasingcars' && sAction=='leasingoffer'){
                        selected = 'selected = "selected"';
                    } 
                    if(makes[i].optionValue=='newcars' && sAction=='newcars' || makes[i].optionValue=='newcars' && sAction=='newoffer'){
                        selected = 'selected = "selected"';
                    } 
                    if(makes[i].optionValue=='usedcars' && sAction=='usedcars' || makes[i].optionValue=='usedcars' && sAction=='usedoffer'){
                        selected = 'selected = "selected"';
                    }
                    if(makes[i].optionValue=='newcars' && sAction=='commercials'){
                        selected = 'selected = "selected"';
                    }
                }
                
                options += '<option '+selected+' value="' + makes[i].optionValue + '">' + makes[i].optionDisplay + '</option>';
            }
            $("select#carOfferType").html(options);

        }
    });
    var selectedOfferType = $("select#carOfferType").val();
    if(selectedOfferType=='leasingcars'){
        $("#budgetSlider").slider({step: 20});
    }
    else{
        $("#budgetSlider").slider({step: 100});
    }
}

function loadMakes(){
    $("select#make").html("<option value=''>Loading...</option>");
    $("select#model").html("<option value=''>Loading...</option>");
    $.ajax({
        url: baseHref+"default/index/getmakes",
        type: "POST",
        dataType: "json",
        data:{carType:$('input.car_type:checked').val(), carOfferType:$("select#carOfferType").val()},
        async:false,
        success: function(makes){
            var options = '';
             for (var i = 0; i < makes.length; i++) {
                options += '<option value="' + makes[i].optionValue + '">' + makes[i].optionDisplay + '</option>';
            }
            $("select#make").html(options);
            //loadModels();
        }
    });
}

function loadModels(){
    $("select#model").html("<option value=''>Loading...</option>");
    $.ajax({
        url: baseHref+"default/index/getmodels",
        type: "POST",
        dataType: "json",
        data:{carType:$('input.car_type:checked').val(), carOfferType:$("select#carOfferType").val(),make:$("select#make").val()},
        async:false,
        success: function(makes){
            var options = '';
             for (var i = 0; i < makes.length; i++) {
                options += '<option value="' + makes[i].optionValue + '">' + makes[i].optionDisplay + '</option>';
            }
            $("select#model").html(options);
        }
    });
}

function loadFuelTypes(){
    var sFuelType = '';
    $("select#fuelType").html("<option value=''>Loading...</option>");
    $.ajax({
        url: baseHref+"default/index/getfueltypes",
        type: "POST",
        dataType: "json",
        data:{carType:$('input.car_type:checked').val(),carOfferType:$("select#carOfferType").val(),make:$("select#make").val(),model:$("select#model").val(),min_price:$("input#minPrice").val(),max_price:$("input#maxPrice").val()},
        async:true,
        success: function(makes){
            var options = '';
             for (var i = 0; i < makes.length; i++) {
                sFuelType = makes[i].optionDisplay;
                if(sFuelType=='D'){
                    sFuelType = 'Diesel';
                }
                if(sFuelType=='P'){
                    sFuelType = 'Petrol';
                } 
                if(makes[i].optionValue=='Not found'){
                    makes[i].optionValue='';
                }
                options += '<option value="' + makes[i].optionValue + '">' + sFuelType + '</option>';
            }
            $("select#fuelType").html(options);
        }
    });
}

function loadTransmissions(){
    var sTransmission = '';
    $("select#transmission").html("<option value=''>Loading...</option>");
    $.ajax({
        url: baseHref+"default/index/gettransmissions",
        type: "POST",
        dataType: "json",
        data:{carType:$('input.car_type:checked').val(),carOfferType:$("select#carOfferType").val(),make:$("select#make").val(),model:$("select#model").val(),min_price:$("input#minPrice").val(),max_price:$("input#maxPrice").val(),fuel_type:$("select#fuelType").val()},
        async:true,
        success: function(makes){
            var options = '';
             for (var i = 0; i < makes.length; i++) {
                sTransmission = makes[i].optionDisplay;
                if(sTransmission=='M'){
                    sTransmission = 'Manual';
                }
                
                if(makes[i].optionValue=='Not found'){
                    makes[i].optionValue='';
                }
                
                if(sTransmission=='A'){
                    sTransmission = 'Automatic';
                }
                options += '<option value="' + makes[i].optionValue + '">' + sTransmission + '</option>';
            }
            $("select#transmission").html(options);
        }
    });
}

function getMinPrice(){
    $.ajax({
        url: baseHref+"default/index/getminprice",
        type: "POST",
        dataType: "json",
        data:{sCarOfferType:$("select#carOfferType").val()},
        async:false,
        success: function(minprice){
            $("input#minPrice").val(minprice);
            $("span#budget").html("£"+$("input#minPrice").val()+" - " + "£"+$("input#maxPrice").val());
            $("#budgetSlider").slider({values: [minprice, $("input#maxPrice").val()]});
            $("#budgetSlider").slider({min: minprice});
        }
    });
}

function getMaxPrice(){
    $.ajax({
        url: baseHref+"default/index/getmaxprice",
        type: "POST",
        dataType: "json",
        data:{sCarOfferType:$("select#carOfferType").val()},
        async:false,
        success: function(maxprice){
            $("input#maxPrice").val(maxprice);
            $("span#budget").html("£"+$("input#minPrice").val()+" - " + "£"+$("input#maxPrice").val());
            $("#budgetSlider").slider({max: maxprice});
            $("#budgetSlider").slider({values: [$("input#minPrice").val(), maxprice]});
            
        }
    });
}

function countCars(){
    $.ajax({
        url: baseHref+"default/index/countcars",
        type: "POST",
        dataType: "json",
        data:{carType:$('input.car_type:checked').val(),sCarOfferType:$("select#carOfferType").val(),sMake:$("select#make").val(),sModel:$("select#model").val(),sMinPrice:$("input#minPrice").val(),sMaxPrice:$("input#maxPrice").val(),sFuelType:$("select#fuelType").val(),sTransmission:$("select#transmission").val()},
        async:false,
        success: function(count){
            $("#counterContainer").html(count);
        }
    });
}

function getUrl(){
    return baseHref+'index/'+$("select#carOfferType").val()+'/car_type/'+$("input.car_type:checked").val()+'/'+'make/'+$("select#make").val()+'/'+'model'+'/'+$("select#model").val()+'/min_price/'+$("input#minPrice").val()+'/max_price/'+$("input#maxPrice").val()+'/fuel_type/'+$("select#fuelType").val()+'/transmission/'+$("select#transmission").val()+'/orderby/'+$("select#orderby").val()+'/items_per_page/'+$("select#itemsperpage").val(); 
}

function loadContractHireYears(){
    var sOptionSelected = $("select#contractHireYears").val();
    $("select#contractHireYears").html("<option value=''>Loading...</option>");
     $.ajax({
        url: baseHref+"default/index/getcontracthireyears",
        type: "POST",
        dataType: "json",
        data:{iId : iOfferId,iMileage: $("select#contractHireMileages").val()},
        async:false,
        success: function(result){
            var options = '';
             for (var i = 0; i < result.length; i++) {
                var sSelected = '';
                if(sOptionSelected==result[i].optionValue){
                    sSelected = 'selected="selected"';
                }
                options += '<option '+sSelected+' value="' + result[i].optionValue + '">' + result[i].optionDisplay + '</option>';
            }
            $("select#contractHireYears").html(options);
        }
    });
}


function loadContractHirePrice(){
    $.ajax({
        url: baseHref+"default/index/getcontracthireprice",
        type: "POST",
        dataType: "json",
        data:{iId : iOfferId ,iMileage: $("select#contractHireMileages").val(),iYear: $("select#contractHireYears").val()},
        async:false,
        success: function(result){
            //$("span#monthlyPrice").html(parseToFloat(result));
            $("input#hideMonthlyPrice").val(result);
        }
    });
}

function loadContractHireInitialPrice(){
    $.ajax({
        url: baseHref+"default/index/getcontracthireinitial",
        type: "POST",
        dataType: "json",
        data:{iId : iOfferId ,iMileage: $("select#contractHireMileages").val(),iYear: $("select#contractHireYears").val()},
        async:false,
        success: function(result){
            //$("span#initialPayments").html(parseToFloat(result));
            $("input#hideInitialPrice").val(result);
        }
    });
}

function parseToFloat(number)
{
   var output, str;
   
   // parsujemy na float
   output = parseFloat(number)
   str = String(output);
   
   // jesli zwrocony string jest bez kropki
   if(str.lastIndexOf('.') == -1)
      str += '.00';
      
   return(str);
}

function calculateNewPrices(){
    
    var fNewPrice = $("input#hideNewPrice").val();
    var fNewMonthlyPrice = $("input#hideMonthlyPrice").val();
    var fPriceAdditions = 0;
    $("input.otherOptionPrice:checked").each( 
        function() { 
            fPriceAdditions = parseFloat(fPriceAdditions) + parseFloat($(this).val());
        } 
    );
        
    $("input.paintOptionPrice:checked").each( 
        function() { 
            fPriceAdditions = parseFloat(fPriceAdditions) + parseFloat($(this).val());
        } 
    );
    
    $("span#newPriceContainer").html(formatNumber(parseFloat(fNewPrice)+parseFloat(fPriceAdditions)));
    $("span#newMonthlyContainer, span#newMonthlyFinanceTab").html(formatNumber(parseFloat(fNewMonthlyPrice)+parseFloat(fPriceAdditions/36)));
}

function calculateLeasingPrices(){
    var fMonthlyPrice = $("input#hideMonthlyPrice").val();
    var fPriceAdditions = 0;
    var iYears = $("select#contractHireYears").val();
    iYears = iYears * 12;

    $("input.otherOptionPriceLeasing:checked").each( 
        function() { 
            fPriceAdditions = parseFloat(fPriceAdditions) + parseFloat($(this).val());
        } 
    );
        
    $("input.paintOptionPriceLeasing:checked").each( 
        function() { 
            fPriceAdditions = parseFloat(fPriceAdditions) + parseFloat($(this).val());
        } 
    );
    
    fPriceAdditions = fPriceAdditions/iYears;
    
    $("span#monthlyPrice").html(formatNumber(parseFloat(fMonthlyPrice)+parseFloat(fPriceAdditions)));
    $("span#initialPayments").html(formatNumber(3*(parseFloat(fMonthlyPrice)+parseFloat(fPriceAdditions))));
}

function formatNumber (anynum) {
    decimal = 2;
    divider =100;
    workNum=Math.abs((Math.round(anynum*divider)/divider));
    workStr=""+workNum
    if (workStr.indexOf(".")==-1){workStr+="."}
    dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
    pStr=workStr.substr(workStr.indexOf("."))
    while (pStr.length-1< decimal){pStr+="0"}
    if(pStr =='.') pStr ='';
    //--- Adds a comma in the thousands place.
    if (dNum>=1000) {
    dLen=dStr.length
    dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
    }
    retval = dStr + pStr
    //-- Put numbers in parentheses if negative.
    if (anynum<0) {retval="("+retval+")";}
    return retval;
}


var iCurrentStep = 1;
function goNextStep(item){
    $("#landingForOffer .errors").html('');
    if($(item).attr('class')=='goNextStep'){
        $(item).children("input:radio").attr("checked","checked");
    }
    if(validate(iCurrentStep)==true){
        if((iCurrentStep+1)>max){
            setProgress(100);
            finish();
        }
        else{
            $("#landingForOffer div#question_"+iCurrentStep).hide();
            iCurrentStep++;
            var sCheckTooltip = checkTooltip();//ukrywanie tooltipów
            for(s=1;s<=max;s++){
                 sFindElemTool = ','+((s))+',';
                if(sCheckTooltip.indexOf(sFindElemTool) > 0){
                    $("#landingForOffer #question_"+s+" > .tip").hide();
                }
                else{
                    $("#landingForOffer #question_"+s+" > .tip").show();
                }
            }
            
            var sCheckDisabled = checkDisabled();//generuję string zawierajacy listę kroków które mają być wyłączone po wybraniu danej opcji
            var sFindElem = '';

            var iTemp = 0;
            for(z=iCurrentStep;z<=max;z++){//sprawdzam od aktualnego kroku ilość opcji do wykluczenia
                sFindElem = ','+((z))+',';
                if(sCheckDisabled.indexOf(sFindElem) > 0){
                    iTemp++;
                }
                else{
                    break;
                }
            }
            iCurrentStep = iCurrentStep + iTemp;
            
            //$("div#question_"+i).fadeIn("fast");
            
            $("#landingForOffer div#question_"+iCurrentStep).show("slide", {direction: "right"}, 150);

            hideNavigElements(iCurrentStep);
            
        }
    }
}

function goPrevStep(){
    if((iCurrentStep-1)>0){
        $("#landingForOffer div#question_"+iCurrentStep).hide();
        iCurrentStep--;
        var sCheckDisabled = checkDisabled();
        var sFindElem = '';

        var iTemp = 0;
        for(z=iCurrentStep;z>=1;z--){
            sFindElem = ','+((z))+',';
            if(sCheckDisabled.indexOf(sFindElem) > 0){
                iTemp++;
            }
            else{
                break;
            }
        }
        iCurrentStep = iCurrentStep - iTemp;

        $("#landingForOffer div#question_"+iCurrentStep).show("slide", {direction: "left"}, 150); 
    }
    hideNavigElements(iCurrentStep);
}

function hideNavigElements(iCurrentStep){
    if(iCurrentStep==1){
        $("#landingForOffer a#prevStep").hide();
    }
    else{
        $("#landingForOffer a#prevStep").show();
    }
    setProgress((iCurrentStep-1)/(max)*100);
}
  
function setProgress(new_value) {
    $( "#landingForOffer #progressbar" ).progressbar('value', new_value );
}

function checkDisabled(){
     var sDisabled = '';
     var sDisabledAll =',';    
     $("#landingForOffer .questionsContainers > ul > li > input:checked").each(function(){
         sDisabled =  $(this).attr("class").replace(/disable/gi, "").replace(/ /gi, "");
         sDisabledAll = sDisabledAll + ","+ sDisabled;
    });
    sDisabledAll = sDisabledAll + ',';
    return sDisabledAll;
}

function checkTooltip(){
     var sDisabled = '';
     var sDisabledAll =',';    
     $("#landingForOffer .questionsContainers > ul > li > input:checked").each(function(){
         sDisabled = $(this).attr("tooltips").replace(/hidetooltip/gi, "").replace(/ /gi, "");
         sDisabledAll = sDisabledAll + ","+ sDisabled;
    });
    sDisabledAll = sDisabledAll + ',';
    return sDisabledAll;
}

function validate(iStep){
    var sErrors = '';
    
    //spradzam czy są dostępne radio buttony dla aktualnego etapu, jezeli tak to sprawdzam czy któryś z nich jest zaznaczony
    
    var iCheckRadio = 0;
    $("#landingForOffer #question_"+iStep+" > ul > li > input:radio").each(function(){
        iCheckRadio++;
    });
    
    var iCheckChecked = 0;
    if(iCheckRadio>0){
        $("#landingForOffer #question_"+iStep+" > ul > li > input:radio:checked").each(function(){
            iCheckChecked++;
        });
        
        if(iCheckChecked<=0){
            sErrors=' You have to set the answer! ';
        }
    }
    
    //sprawdzam czy mam jakąś textarea do validacji -> nie moze być pusta!
    if ($("#landingForOffer #question_"+iStep+" > div > textarea.validText").length > 0){
        if($("#question_"+iStep+" > div > textarea.validText").val()==''){
            if(sErrors!=''){
                sErrors = sErrors + ', '
            }
             sErrors=' You have to fill all fields! ';
        }
    }

    
    var sErrorsInputs = '';
    $("#landingForOffer #question_"+iStep+" > div > div > .validText").each(function(){
         if($(this).val()==''){
             if(sErrors!=''){
                sErrorsInputs = sErrorsInputs + ', '
            }
             sErrorsInputs=' You have to fill all fields! ';
         }
    });
    sErrors = sErrors + sErrorsInputs;
    
    var sErrorsEmail = '';
    $("#landingForOffer #question_"+iStep+" > div > div > .validEmail").each(function(){
         if(validate_email_landing($(this).val())==false){
             if(sErrors!=''){
                sErrorsEmail = sErrorsEmail + ', '
            }
             sErrorsEmail=' Incorrect e-mail address! ';
         }
    });
    sErrors = sErrors + sErrorsEmail;
    
    var sErrorsPhone = '';
    $("#landingForOffer #question_"+iStep+" > div > div > .validPhone").each(function(){
         if(validate_phone_landing($(this).val())==false){
             if(sErrors!=''){
                sErrorsPhone = sErrorsPhone + ', '
            }
             sErrorsPhone=' Incorrect phone number! ';
         }
    });
    sErrors = sErrors + sErrorsPhone;
    
    if(sErrors==''){
        return true
    }
    else{
        $("#landingForOffer #error_"+iStep).html(sErrors);
        $("#landingForOffer #error_"+iStep).effect('shake', {
                            times: 3,
                            distance: 10
                        }, 100);
        return false;
    }
}

function validate_email_landing(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(email) == false) {
        return false;
    }
    return true;
}
            
function validate_phone_landing(phone) {
    phone = phone.replace(/ /g,"");
    if (IsNumeric(phone) && phone.length > 7) {
        return true
    } else {
        return false;
    }
}


function finish(){
    $("#landingForOffer #navigContainer").hide();
    $("#landingForOffer #loader").show();
    $("#landingForOffer #formContainer").addClass("formContainerFix");
    var sFindElem ='';
    var sDisabled = checkDisabled(); // wyszukuje zablokowane kwestie i wywala je po to by, serialize() nie przekazało ich do post
    for(s=1;s<=max;s++){
         sFindElem = ','+((s))+',';
        if(sDisabled.indexOf(sFindElem) > 0){
            $("#landingForOffer #question_"+s).html();
        }
    }
    $.ajax({
        url: baseHref+"default/index/sendmail",
        type: "POST",
        data: $("#landingForm").serialize()+"&car="+$("input#car").val()+"&url="+$("input#url").val()+"&idOffer="+idOffer+"&nameAction="+nameAction,
        dataType: "html",
        async:false,
        success: function(items){
           $("#contentContainerItems").html(items);
           $("#snip").show();
         }
    });
}

function loadApplyForCreditForm(){
    $.ajax({
        url: baseHref+"default/index/applyforcredit",
        type: "POST",
        dataType: "html",
        data:{apply_customer_type: $('#apply_customer_type').val()},
        async:false,
        success: function(applyforcredit){
            $("#applyForCreditForm").html(applyforcredit);
        }
    });
}

function addToGarage(sType,iId,item){
    sGarage = $.cookie('garage');
    if(sGarage==null){
        var sGarage = sType+'_'+iId;
    }
    else{
        if (sGarage.indexOf(sType+'_'+iId)==-1){
            if(sGarage!=''){
                sGarage = sGarage + ','+sType+'_'+iId;
            }
            else{
                sGarage = sGarage +sType+'_'+iId;
            }
        }
    }
    $.cookie('garage', sGarage, {expires: 7,path: '/'});
    $("#garageInfo").remove();
    $(item).parent().parent().parent().parent().parent().append('<div id="garageInfo" class="smallBox"><div class="smallBoxTop"><div class="smallBoxBottom"><a class="closePopup" href="#" onclick="$(\'#garageInfo\').remove();return false;">X</a><h3>Garage</h3>You added car to garage.<br /><a href="index/garage">Go to garage »</a><br class="clearBoth"></div></div></div>');
    updateGarageLeft();
}

function updateGarageLeft(){
    sGarage = $.cookie('garage');
    if(sGarage!="" && sGarage!=null){
        var tempGarage = sGarage.split(',');
        $("#garageLeftCount").text(tempGarage.length);
        $("#leftGarageContainer").show();
    }
    else{
        $("#garageLeftCount").text("0");
        $("#leftGarageContainer").hide();
    }
    
}

function removeFromGarage(sId){
    sGarage = $.cookie('garage');
        sGarage = sGarage.replace(","+sId, "");
        sGarage = sGarage.replace(sId+",", "");
        sGarage = sGarage.replace(sId, "");
        sGarage = sGarage.replace(" ", "");
        if(sGarage==''){
            $("#allContainer").html('<div class="box"><div class="boxInner"><div class="boxInnerFirst"><div class="boxInnerSecond"><div class="msgInfo">Your garage is empty.</div></div></div></div></div>');
        }
    
    $.cookie('garage', sGarage, {expires: 7,path: '/'});
    updateGarageLeft();
}


