$(document).ready(function() {

// !HIDE BUTTON
    $(".hide").click(function(event){
        $(event.target).parent().hide();
    });

// !COUNTRY CHANGE POPUP

    $("#current-country").click(function(event){
        $("#country-home-list-container").show();
    });


// !PRODUCT SUPPORT JUMP

    $("#support-jump-to-product").change(function(event){
    
        if ($(event.target).val() !== '') {
            window.location = $(event.target).val();       
        }
    });
    

// !LATCH COMPATIBILITY    

    var translations = {

        "us": {
            "en": {
                "brand_none":   "LATCH not available",
                "brand_some":   "Select your brand",        
                "brand_all":    "Available on all vehicles",
                "result_none":  "Model year 2000 and earlier vehicls are NOT equiped with LATCH system.",
                "result_some":  "The following vehicles are equipped with LATCH system: ",     
                "result_all":   "All model year 2003 and later vehicles are equiped with LATCH system."     
            },
            
            "es": {
                "brand_none":   "LATCH no disponible",        
                "brand_some":   "Seleccione una marca",        
                "brand_all":    "Disponible en todos los vehículos",        
                "result_none":  "Los modelos del año 2000, anteriores no están equipados con el sistema LATCH.",
                "result_some":  "Los siguientes vehículos están equipados con el sistema LATCH: ",     
                "result_all":   "Los vehículos modelo 2003, posteriores están equipados con el sistema LATCH."     
            }
        },
    
        "ca": {
            "en": {
                "brand_none":   "UAS not available",        
                "brand_some":   "Select your brand",        
                "brand_all":    "Available on all vehicles",        
                "result_none":  "Model year 2000 and earlier vehicls are NOT equiped with LATCH system.",
                "result_some":  "The following vehicles are equipped with UAS system: ",     
                "result_all":   "All model year 2003 and later vehicles are equiped with LATCH system."     
            },
            "fr": {
                "brand_none":   "DUA non disponible",        
                "brand_some":   "Sélectionnez marque",        
                "brand_all":    "Disponible sur tous les véhicules",        
                "result_none":  "Les véhicules de l'année 2000 et les plus anciens ne sont pas équipés d'un DUA.",
                "result_some":  "Les véhicules suivants sont équipés d'un DUA: ",     
                "result_all":   "Les véhicules de l'année 2003 et les plus récents  sont équipés d'un DUA."     
            }        
        }        
    }
    
    var terms = translations[siteRegion][pageLanguage];
    
    var brands = {
    
        "2000": [""],
        "2001": ["","Jaguar", "Lexus", "Lincoln", "Mazda", "Mercedes-Benz", "Mercury", "Mitsubishi", "Nissan", "Oldsmobile", "Pontiac", "Saab", "Subaru", "Toyota", "Volkswagen", "Volvo"],
        "2002": ["","Acura", "Bentley", "BMW", "Buick", "Cadillac", "Chevrolet", "Chrysler", "Daewoo", "Dodge", "Ferrari", "Ford", "GMC", "Honda", "Hyundai", "Infiniti", "Isuzu", "Jaguar", "Jeep", "Kia", "Land Rover", "Lexus", "Lincoln", "Maserati", "Mazda", "Mercedes-Benz", "Mercury", "Mitsubishi", "Nissan", "Oldsmobile", "Pontiac", "Saab", "Saturn", "Subaru" ,"Suzuki", "Toyota", "Volkswagen", "Volvo"],
        "2003": [""]
    
    };

    var vehicles = {

        "2001": {

			"Jaguar": "S-Type",
			"Lexus": "GS 300/430, LS 430, LX 470, RX 300",
			"Lincoln": "LS",
			"Mazda": "Protégé, Tribute",
			"Mercedes-Benz": "C-Class",
			"Mercury": "Sable",
			"Mitsubishi": "Galant, Montero, Montero Sport",
			"Nissan": "Sentra, Maxima, Quest",
			"Oldsmobile": "Alero, Silhouette",
			"Pontiac": "Aztec, Montana",
			"Saab": "9-5",
			"Subaru": "Legacy",
			"Toyota": "Corolla, Echo, Prius, Highlander, Land Cruiser, RAV4, Sequoia, Sienna",
			"Volkswagen": "Cabrio, Golf, GTI, Jetta, New Beetle",
			"Volvo": "S60, V70, S80"       
        },

        "2002": {

			"Acura": "MDX, 3.2TL, RSX",
			"Bentley": "Arnage Black Label",
			"BMW": "3 Series Sport Wagon, 3 Series/M3, Coupe 3/Sedan 5 Series, Sport Wagon 5 Series, M57 Series, Mini Cooper, SX5",
			"Buick": "Century, LeSabre, Regal, Rendezvous",
			"Cadillac": "Deville",
			"Chevrolet": "Prizm, Impala, Malibu, Monte Carlo, Avalanche, Tahoe, Tracker, Trailblazer, Trailblazer Ext, Venture, Silverado",
			"Chrysler": "300M, Concorde, Concorde Ltd., Sebring 4 DR, PT Cruiser, Town &amp; Country, Voyager",
			"Daewoo": "Leganza, Lanos, Nubria",
			"Dodge": "Neon, Intrepid and Stratus 4 DR, Caravan, Grand Caravan",
			"Ferrari": "456M",
			"Ford": "Escape, Focus, Taurus and Thunderbird, Ranger, Windstar",
			"GMC": "Envoy, Envoy XL, Sierra, Yukon, Spectra",
			"Honda": "Civic, Accord, CRV, Passport, Odyssey",
			"Hyundai": "XG 350, Sonata, Elantra, Tiburon",
			"Infiniti": "Q45, G20 e I35",
			"Isuzu": "Axiom, Rodeo, Rodeo Sport",
			"Jaguar": "S-Type, X-Type",
			"Jeep": "Liberty",
			"Kia": "Sedona, Optima",
			"Land Rover": "Discover Series II, Freelander",
			"Lexus": "LX 470, RX 300, ES 300 and IS 300/Sportcross, GS 300/430, LS 430, SC 430 ",
			"Lincoln": "LS",
			"Maserati": "Coupe",
			"Mazda": "Protégé, MPV, Tribute",
			"Mercedes-Benz": "G 500, ML-Class, C 230, C-Class",
			"Mercury": "Sable, Villager",
			"Mitsubishi": "Galant, Lancer, Montero, Montero Sport",
			"Nissan": "Xterra, Altima, Maxima, Quest, Sentra",
			"Oldsmobile": "Alero, Aurora, Bravada, Silhouette",
			"Pontiac": "Bonneville, Grand Am, Aztec, Montana",
			"Saab": "9-3, 9-5",
			"Saturn": "L-Series, VUE",
			"Subaru": "Impreza, Legacy, Forester",
			"Suzuki": "Aerio, Grand Vitara and Grand Vitara XL-7, Vitara",
			"Toyota": "Camry, Prius, Corolla, Echo, Highlander, Land Cruiser, RAV4, Sequoia, Sienna",
			"Volkswagen": "Cabrio, Golf, GTI, Jetta, New Beetle",
			"Volvo": "S40, S60, V40, V70, V70XC, S80"
        }

    }


    $("#latch-model-year").change(function(event){
    
        var year = $(event.target).val()
        
        var brandSelect = $("#latch-brand");
        
        var resultContainer = $("#latch-result");
    
        if (year !== '') {
        
            if (year == '2000') {
                brandSelect.unbind('change');
                brandSelect.attr('disabled', 'disabled');
                brandSelect.html('<option>' + terms['brand_none'] + '</option>');
                resultContainer.html('<p>' + terms['result_none'] + '</p>');
            }
            
            else if (year == '2003') {
                brandSelect.unbind('change');
                brandSelect.attr('disabled', 'disabled');
                brandSelect.html('<option>' + terms['brand_all'] + '</option>');
                resultContainer.html('<p>' + terms['result_all'] + '</p>');
            }
            
            else {

                var brandOptions = '';
                
                var brandsOfYear = brands[year];
                
                for (brandIndex in brandsOfYear) {
                
                    var brand = (brandsOfYear[brandIndex] !== '') ? brandsOfYear[brandIndex]:terms['brand_some'];
                    brandOptions = brandOptions + '<option value="' + brandsOfYear[brandIndex] + '">' + brand + '</option>';
                }
                brandSelect.attr('disabled', '');
                brandSelect.html(brandOptions);
                brandSelect.bind('change', function(event){
                
                    var selectedBrand = $(event.target).val();
                    
                    if (selectedBrand !== '') {
                        resultContainer.html('<p>' + terms['result_some'] + vehicles[year][selectedBrand] + '.</p>');
                    }
                    
                    else {
                        resultContainer.html('<p>' + terms['brand_some'] + '.</p>');
                    }
                });
            }
        
        }
        
        else {        
            brandSelect.unbind('change');
            brandSelect.attr('disabled', 'disabled');
            brandSelect.html('');
            resultContainer.html('');
        }
    
    });



// !VIDEO SETUP

    $('.video-trigger').click(function(event) {
    
        event.preventDefault();
        
        var eventTarget = $(event.currentTarget);
            
        var videoPropertyId = eventTarget.attr("rel");
        var videoId = "video-" + videoPropertyId;
    
        var targetVideoSplit = $("#" + videos[videoPropertyId].targetVideoSplitId);
    
        var targetVideoSplitCloser = targetVideoSplit.children(".box-split-closer");
        var targetVideoContainer = targetVideoSplit.find(".video-container");
        
        // remove any existing video
        if (targetVideoContainer.has("video")) {    
            targetVideoContainer.html("");
        }
        
        // insert new video
        targetVideoContainer.html('<video width="640" height="360" type="video/mp4" controls="controls" src="' + videos[videoPropertyId].src + '" poster="' + videos[videoPropertyId].poster + '" id="' + videoId + '"></video>');
        var targetVideo = targetVideoSplit.find("video");
    
        // set new caption
        var targetVideoCaption = targetVideoSplit.children(".video-caption");
        targetVideoCaption.html(videos[videoPropertyId].caption + " (" + videos[videoPropertyId].duration + ")");
    
        var videoPlayer;
    
        targetVideoSplit.slideDown("fast", function() {
         	
         	$('html,body').animate({scrollTop: targetVideoSplit.offset().top - 10},'slow');
         	
            videoPlayer = new MediaElementPlayer("#" + videoId, {
                defaultVideoWidth: 640,
                defaultVideoHeight: 360,
                enableAutosize: true,
                startVolume: 0.5,
                features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
                translationSelector: false,
                loop: false,
                success: function (me) {
                    me.play();
                }
            });
            
        });
        
        targetVideoSplitCloser.click(function(event) {
            targetVideoSplit.slideUp("fast");
            targetVideoContainer.html("");
        });
    });



// !LIGHTBOX

    $(".lightbox-intercept").click(function(event){event.preventDefault();});    

    // select one or more elements to be overlay triggers
    $(".lightbox-trigger[rel]").overlay({
        mask: '#000', 
    	color: '#ccc',
    	top: 25,
    	close: '.lightbox-close'
    });    

    $(".lightbox-gallery-image").click(function(event) {
        var image = $(event.target)
        var imageId = parseInt(image.attr("rel"));
        var galleryId = image.parent().attr("rel");
        var gallery = $(galleryId).CLEKLightboxGallery({'startImageId':imageId});
    });
    
});


// lightbox image gallery plugin
    (function($) {
    
    $.fn.CLEKLightboxGallery = function(settings) {
        
        var config = {
            'contentBox' : '.lightbox-gallery-content-box',
            'navigationClass' : '.lightbox-gallery-nav',
            'startImageId': 0
        };
        if (settings) $.extend(config, settings);
    
        var content = undefined;
        var navigation = undefined;
        var selectedNavImage = undefined;
        
        this.each(function() {
    
            content = $(this).find(config.contentBox);
            navigation = $(this).children(config.navigationClass);
            navigationItemImages = navigation.find("img");
    
            // remove any previous content        
            content.empty();
            navigationItemImages.removeClass("selected");
            
            var firstNavImage = navigationItemImages.eq(config.startImageId);
            firstNavImage.addClass("selected");
            selectedNavImage = firstNavImage;
            content.append('<img src="' + firstNavImage.attr("src") + '" /><p>' + firstNavImage.attr("alt") + '</p>');
            contentImage = content.children("img");
            contentCaption = content.children("p");
    
            // setup navigation
            navigationItemImages.click(function(event) {
    
                selectedNavImage.removeClass("selected");
                var newSelectedNavImage = $(event.target);
                newSelectedNavImage.addClass("selected");
                selectedNavImage = newSelectedNavImage;
                
                // animate content out/in (use animate to preserve container height)
                content.animate({opacity: 0}, 250, function() {
    
                    contentCaption.html(newSelectedNavImage.attr("alt"));
                    contentImage.attr("src", newSelectedNavImage.attr("src"));
                    content.animate({opacity: 100}, 250)
    
                });
            });        
    
        });
        
        return this;
    };


// HOME SLIDESHOW
    var homeSlides = $('.home-slide'),
        currentSlide = undefined,
        nextSlide = undefined,
        homeSlidesControls = undefined,
        slideshowTimeOutID = 0;
        
    if ((homeSlides != undefined) && (homeSlides.length > 1)) {
  
      var homeSlidesContainer = $('.home-slideshow');
      
      // create controls container
      homeSlidesContainer.after('<div class="slides-control-container"><ul></ul></div>');  
      var homeSlidesControlList = $('.slides-control-container>ul');
      homeSlides.each(function(index) {
        var slide = $(this);
        slide.attr('rel', index);
        if (slide.css('display') != 'none') {
          currentSlide = slide;
          homeSlidesControlList.append('<li class="slides-control selected" rel="' + index + '">&nbsp;</li>');
        }
        else {
          homeSlidesControlList.append('<li class="slides-control" rel="' + index + '">&nbsp;</li>');
        }
      });
      homeSlidesControls = homeSlidesControlList.children();
      homeSlidesControls.click(function() {
        gotoSlide($(this).attr('rel'));
      });
  
      var getNextSlide = function() 
      {
        var foundSlide = undefined;
        if (currentSlide.is(homeSlides.last())) {
          foundSlide = homeSlides.first();
        } 
        else {
          foundSlide = currentSlide.next();
        }
        return foundSlide;
      };
    
      var gotoNextSlide = function() 
      {
        window.clearTimeout(slideshowTimeOutID);
        currentSlide.fadeOut(1000, function() {
          homeSlidesControls.filter('[rel="' + currentSlide.attr('rel') + '"]').removeClass('selected');
          homeSlidesControls.filter('[rel="' + nextSlide.attr('rel') + '"]').addClass('selected');
          nextSlide.fadeIn(1000, function() {
            currentSlide = nextSlide;
            nextSlide = getNextSlide();
            startSlideShow();
          });
        });
      };
      
      var gotoSlide = function(newSlideIndex)
      {
        window.clearTimeout(slideshowTimeOutID);
        var oldSlideIndex = currentSlide.attr('rel');
        if (newSlideIndex != oldSlideIndex) {
          homeSlidesControls.filter('[rel="' + oldSlideIndex + '"]').removeClass('selected');
          homeSlidesControls.filter('[rel="' + newSlideIndex + '"]').addClass('selected');
          currentSlide.fadeOut(1000, function() {
            currentSlide = homeSlides.filter('[rel="' + newSlideIndex + '"]');
            currentSlide.fadeIn(1000);
          });
        }
      };
  
      var startSlideShow = function() 
      {
        slideshowTimeOutID = window.setTimeout(gotoNextSlide, 8000);
      };
    
      nextSlide = getNextSlide();
      startSlideShow(); 
    }


})(jQuery);
