$(function() {
    externalLinks.init();
    dealerLocator.init();
    featurePicker.init();
    modalTabSwap.init();
    gallerySwap.init();
    videoActive.init();
    searchObject.init();
    modalTabSwap.init();
    modelHash.init();
    jsToggle();

    if($('.carousel-slider').length > 0){
        $(window).load(function() {
            $('.carousel-slider ul:first-child').cycle({
                fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
            });
        })
    }
    
    $('.menu-main .menu-models > li').mouseover(function() {
        $('.menu-models .modal-dropdown').hide();
        $(this).find('.modal-dropdown').show();
    });
    
    $('.menu-main .menu-innovation > li').mouseover(function() {
        $('.active').removeClass('active');
        $('.menu-innovation .modal-dropdown').hide();
        $(this).addClass('active');
        $(this).find('.modal-dropdown').show();
    });
    
    if(typeof initialiseLinks == 'function') {
        initialiseLinks();
    }
    
    if($("#features").length > 0){
        $('.detail-photo-links a').click(function(){
            
            var classname = $(this).attr('class');
            $(this).parent('li').parent('ol').parent('.detail-photo-links').parent('.detail-photo').children('ol').children('li').children('img').addClass('hidden');
            $(this).parent('li').parent('ol').parent('.detail-photo-links').siblings('ol').children('li').children('img.'+classname).removeClass('hidden');
            return false;
            
        });
    }
    
    if($("#feature-area").length > 0) {
        // alert($('.carousel-slider ul li').attr('class'));
    }
    
    $(".menu-main > li > a").click( function (event){
        event.preventDefault();
    });
    
    $("#featureLinkList li a").click( function (event){
        $("#features-tab").click();
    });
});


externalLinks = {
    init:function() {
        $('a[rel=external]').attr('target', '_blank');
    }
};

featurePicker = { // Functionality for the Home Page carousel
    init: function() {
        if ($('.feature-picker').length !==0) {
            $(".content-features li").each(function(index) {
                $(this).attr("rel", index);
            });
            
            $(".menu-features li").each(function(index) {
                $(this).attr("rel", index);
            });
            
            $(".menu-features li").hover(function(){
                if($(this).attr('class') != 'active'){
                    $(this).children('.small').hide();
                    $(this).children('.large').show();
                }
            }, function(){
                if($(this).attr('class') != 'active'){
                    $(this).children('.large').hide();
                    $(this).children('.small').show();
                }
            });
            
            $(".menu-features li").click(function() {
                var slide = $(this).attr("rel");
                
                // cache backgroun image
                backgroundImageUrl = $(".content-features li").eq(slide).attr('data');
                backgroundImage = $('<img />').attr('src', backgroundImageUrl).load(function() {
                    $(".content-features li").eq(slide).css('background', 'url(' + backgroundImageUrl + ')');
                });
                
                // console.log(slide);
                if (".carousel:visible"){
                    $(".carousel-slider ul:first-child").hide();
                    $(".content-features").show();
                }
                
                $(".menu-features li.active").removeClass('active');
                $(this).addClass('active');
                $(".menu-features li .small").show();
                $(".menu-features li .large").hide();
                $(this).children('.small').hide();
                $(".menu-features li").eq(slide).find('.large').show();
                
                $(".content-features li").hide();
                $(".content-features li").eq(slide).show();
            });
            
        }
    }
}

/** search code below **/

searchObject = {
    init        : function() {
        delay = (function(){
          var timer = 0;
          return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
          };
        })();

        var runningRequest = false;
        var request;

       //Identify the typing action
        var lastRequest = '';

        $('input#keywords').keyup(function(e) {
           var result;
           if(lastRequest == $.trim($('input#keywords').val())) {
               return;
           }
           lastRequest = $.trim($('input#keywords').val());
           var $q = $(this);

           if($q.val() == ''){
               $('.mod-searchresults').html('');
               return false;
           }

           data = {
               keywords    : $('#keywords').val(),
               XID         : $('input[name=XID]').val(),
               ACT         : $('input[name=ACT]').val(),
               RP          : '/search/ajax',
               collection  : $('input[name=collection]').val(),
               search_mode : $('input[name=search_mode]').val(),
               loose_ends  : $('input[name=loose_ends]').val(),
               site_id     : $('input[name=site_id]').val(),
               ajax        : true
           };

           url = '/search/ajax';
           delay(function() {
               searchObject.request(url, data, $('.mod-searchresults'));
            }, 400);
        }); 
    },
    result      : '',
    processing  : false,
    request     : function (url, data, target) {

        var self = this;
        this.result = false;
        //Abort opened requests to speed it up
        if(this.processing) {
            async.abort();
        }
        
        var self = this;
        this.processing = true;
        $('#keywords').css('background-color', 'rgb(150, 170, 190)');

        async = $.ajax({
             type    : 'POST',
             url     : url,
             data    : data,
             success : function(data) {
                 self.processing = false;                    
                 self.result = data
                 self.display(data, target)
                 $('#keywords').css('background-color', '');

             }
         })
         return this;

    },
    display     : function(data, target) {
         target.html(data);
     }
};

dealerLocator = {
    init : function() {
        $('.map-region').click(function(e) {
            e.preventDefault();
            regionId = $(this).attr('id').substring(7);

            var src = baseURL + 'dealer-locator/region/';

            $.modal('<iframe src="' + src + regionId + '" height="450" width="830" style="border:0">', {
                closeHTML:"",
               containerCss:{
                    backgroundColor:"#ddd",
                    borderColor:"#000",
                    height:450,
                    padding:0,
                    width:830,
                },
                overlayClose:true
            });
        })
        
        $('#selCountry').change(function() {
            $.modal('<iframe src="' + baseURL + 'dealer-locator/international/' + $('#selCountry').val() + '" height="450" width="450" style="border:0">', {
                closeHTML:"",
                containerCss:{
                    backgroundColor:"#fff",
                    borderColor:"#000",
                    padding:0
                },
                overlayClose:true
            });
        });
    }
}
 
modalTabSwap = {
    $modalTabs: undefined,
    
    init:function() {
        var $modalTabs = $('#modal-tabs');

        if ($modalTabs.length) {
            var self = this;
            
            var $features = $('#features').addClass('active');
            var $specifications = $('#specifications');
            var $design = $('#design-options');
            var $reviews = $('#reviews');
            
            self.$modalTabs = $modalTabs;
            $specifications.hide();
            $design.hide();
            $reviews.hide();
            
            self.bind();
        }
    },

    bind:function() {
        var self = this;
        
        var $featureArea = $('#feature-area');
        
        var $features = $('#features');
        var $specifications = $('#specifications');
        var $design = $('#design-options');
        var $reviews = $('#reviews');
        
        var $featuresTab = $('#features-tab');
        var $specificationsTab = $('#specifications-tab');
        var $designTab = $('#design-options-tab');
        var $reviewsTab = $('#reviews-tab');
        
        $featuresTab.click(
            function(event) {
                event.preventDefault();
                $('.active').removeClass('active');              
                $features.show().addClass('active');

                $featureArea.children().addClass('hidden')
                $('#explorationWrap').removeClass('hidden');

            }          
        );   
        
        $specificationsTab.click(
            function(event) {
                event.preventDefault();
                
                $('.active').hide().removeClass('active');
                $specifications.show().addClass('active');
                $featureArea.children().addClass('hidden');
                $('#explorationWrap').removeClass('hidden');
            }      
        );
        
        $designTab.click(
            function(event) {
                event.preventDefault();
                
                $('.active').hide().removeClass('active');
                $design.show().addClass('active');
                $featureArea.children().addClass('hidden');
                $('#explorationWrap').removeClass('hidden');
            }           
        );   
        
        $reviewsTab.click(
            function(event) {
                event.preventDefault();
                
                $('.active').hide().removeClass('active');
                $reviews.show().addClass('active');
                $featureArea.children().addClass('hidden');
                $('#explorationWrap').removeClass('hidden');
            }          
        );
        
        $('#gallery-tab').click(
            function(event) {
                event.preventDefault();
                $featureArea.children().addClass('hidden')
                $('#gallery-wrap').removeClass('hidden');
                
            }
        );
        
        $('#videos-tab').click(
            function(event) {
                event.preventDefault();
                
                $featureArea.children().addClass('hidden')
                $('#video-wrap').removeClass('hidden');
            }
        );
        
        
    }
};


gallerySwap = {
    $galleryThumbs: undefined,
    
    init:function() {
        var $galleryThumbs = $('.gallery-thumbs');

        if ($galleryThumbs.length) {
            var self = this;
            self.$galleryThumbs = $galleryThumbs;

            self.bind();
        }
    },

    bind:function() {
        var self = this;
        
        $('.gallery-thumbs li').click(
            function() {
                var self = $(this);
                
                self.siblings().removeClass('active');
                self.addClass('active');
                var $imageSelected = self.children('img').attr('class');
                $('.gallery-large').addClass('hidden');
                var $imageSelected = $imageSelected.replace('thumb-','');
                $('.'+$imageSelected).removeClass('hidden');
            }
        );
    }
};

videoActive = {
    $videoThumbs: undefined,
    
    init:function() {
        var $videoThumbs = $('.video-thumbs');

        if ($videoThumbs.length) {
            var self = this;
            self.$videoThumbs = $videoThumbs;

            self.bind();
        }
    },

    bind:function() {
        var self = this;
        
        $('.video-thumbs li').click(
            function() {
                var self = $(this);
                
                self.siblings().removeClass('active');
                self.addClass('active');
            }
        );
    }
};

// checks for hash tag on model page and processes if necessary
modelHash = {
    init : function() {
        if( !$('body').hasClass('model') ) {
            return false;
        }
        
        hash = window.location.hash;
        if (hash != '') {
            switch(hash) {
                case '#reviews' :
                    $('#reviews-tab').click();
                    break;                
                case '#specifications' :
                $('#specifications-tab').click();
                    break;
            }
        }
    }    
}


function jsToggle(){    
        if(!supports_input_placeholder()){
                
                
                $(".jsToggle").focus(function(){
                   if($(this).val() == $(this).attr("placeholder")){
                           $(this).attr("value","");
                           $(this).css('color','');
                   }
                }).blur(function(){
                   if($(this).val() == ""){
                           $(this).attr("value",$(this).attr("placeholder"));
                                $(this).css('color','#c3c3c3');
                   }
                });
                
                $(".jsToggle").each(function(){
                        if($(this).val() == ""){
                                $(this).val($(this).attr("placeholder"));
                                $(this).css('color','#c3c3c3');
                        }
                });
        }
}

function supports_input_placeholder() {
  var i = document.createElement('input');
  return 'placeholder' in i;
}

