$(document).ready(function () {
 	//****************************
    //***Mega menu **
    //****************************
    if(	$("#mega-menu").length){
	   	$("#mega-menu").megamenu({ container: '#header-bottom',item_width:190 });
		$("#mega-menu").find(".groupitem").each(function(){
			if( $(this).find(".mm-subitem-link a") ){
				$(this).find(".groupitemlink").attr('href',$(this).find(".mm-subitem-link a").attr('href'));
				$(this).find(".groupitemlink").attr('title',$(this).find(".mm-subitem-link a").attr('title'));
				$(this).find(".mm-subitem-link").remove();
			}
		});
		$("#mega-menu").activeMenu();
	}

    //****************************
    //***flags **
    //****************************	
	$('#flagicon').addClass($(this).getUrlParam('lang'));
	if($("#quick-link-menu").length)
		$("#quick-link-menu").megamenu({ container: '#quick-link'});
		
    //****************************
    //***SlideShow **
    //****************************
    var changeEvery = 10;//secs
    var totWidth = 0;
    var positions = new Array();
    var imagesLayer = $('#filmstrip-images');
    var slideTextLayer = $('.filmstrip-text-inner');
    var thumbNail = $('#filmstrip-thumb');
    var slideControlLayer = $('#filmstrip-controlbox');
    var arrow = $('#filmstrip-arrow');
	//image loader
    var imgLength = $('#filmstrip-images').find('img').length;
    var imgLoaded = 0;

    slideTextLayer.find('.filmstrip-text ul').each(function () {
        var width = ($(this).width() - $(this).find('.separator').length *$(this).find('.separator').width())/$(this).children('li').size();
        var charLength = 40 / $(this).children('li').size() - 3 * $(this).children('li').size();
        $(this).children('li').each(function () {
            $(this).css('maxWidth', width);
            $(this).children('a').jTruncate({
                length: charLength,
                minTrail: 0,
                ellipsisText: " ...",
                moreText: ""
            });
        });
    });
    
    //****************************
    //***Thumbnail **
    //****************************

    // move the thumb help text layer
	$(".filmstrip-description-text").appendTo($("#filmstrip-thumb"));
	
	$.fn.thumbnailSlideShow = function(index)
	{
		// 1. if there's any animation running, avoiding any the events to be queued
        if ($(this).is('.active')) { return false; }

        // 2. find the index of the control to bind the event to. 
        // Note: the array index starts from 0, whereas the dom element n-th child selection starts from 1
        var childIndex = index + 1;

		// 3. find the current active thumbnail control

        var activeIndex = thumbNail.find('li.active').index() + 1;
        
        // 4. set the active control be inactive
        thumbNail.find('ul li').removeClass('active').addClass('inactive');

		// 5. set the current element which triggers the event to be active
        $(this).addClass('active');

        // 6. hide the text information for the active thumbnail
        thumbNail.find('ul li:nth-child(' + activeIndex + ') span').hide();
        
        // 7. show the active thubmnail image
        thumbNail.find('ul li:nth-child(' + activeIndex + ') img').show({effect:'drop',direction:'up',speed:700});
        
        // 8. hide the triggering thumbnail image and show it's text info
        thumbNail.find('ul li:nth-child(' + childIndex + ') img').hide({effect:'drop',direction:'up',speed:700}, function(){$(this).next().show();});

		// 9. fade in and fade out the corresponding background image
        imageSwitch(childIndex, 200);
	}
    // Change the cotnainer div's width to the exact width of all the slides combined
    thumbNail.find('ul li').each(function (index) {
    	$(this).bind('mouseover',function(e){
    		e.preventDefault();
    		$(this).children('span').show();
    		$(this).children('img').hide();
    	});
  	    $(this).bind('mouseleave',function(e){
    		e.preventDefault();
    		if(!$(this).is('.active')){
	    		$(this).children('span').hide();
	    		$(this).children('img').show();
    		}
    	});

        $(this).click(function (e, keepScroll) {
          
          	$(this).thumbnailSlideShow(index);
            // Prevent the default action of the link 
            e.preventDefault();

            // Stopping the auto-advance if an icon has been clicked:
            if (!keepScroll) clearInterval(itvl);
        });
        
    	$(this).bind('autoPlay',function(){
	 		$(this).thumbnailSlideShow(index);
	 	});
    });


    //****************************
    //*** Txt **
    //****************************

    // Change the cotnainer div's width to the exact width of all the slides combined
    
    $.fn.textInfoSlideShow = function(index)
    {
        if ($(this).is('.active') || slideTextLayer.is('.paused')) return false;
		
		slideTextLayer.bind('mouseover',function(){slideTextLayer.addClass('paused');})
		slideTextLayer.bind('mouseleave',function(){slideTextLayer.removeClass('paused');});

        // Start the sliding animation 
        var activeIndex = slideControlLayer.find('li.slider-control.active').index() + 1;
        var prevIndex = (activeIndex == 0) ? slideControlLayer.find('li.slider-control').length : activeIndex;
        var childIndex = index + 1;

        $('li.slider-control').removeClass('active').addClass('inactive');
        $(this).addClass('active');

        imageSwitch(childIndex);
        
        slideTextLayer.children(':nth-child(' + prevIndex + ')').animate({ left: '310px' }, { easing: 'easeInOutQuint', duration: 300, complete:
            function () {
                slideTextLayer.children(':nth-child(' + childIndex + ')').stop().animate({ left: '0px' }, { easing: 'easeInOutQuint', duration: 300 });
            }
        });
        arrow.stop().animate({marginLeft:index*13});
    }
    
    slideControlLayer.find('ul li').each(function (index) {
        $(this).click(function (e, keepScroll) {
           
           $(this).textInfoSlideShow(index);
            // Prevent the default action of the link 
            e.preventDefault();
            // Stopping the auto-advance if an icon has been clicked:
            if (!keepScroll){
            	clearInterval(itvl);
            	itvl = setInterval(function () { autoAdvance(); }, changeEvery * 1000);
            }
        });
        
		$(this).bind('autoPlay',function(){
	 		$(this).textInfoSlideShow(index);
	 	});
    });
    
    function imageSwitch(index, delay) {
        //fast forward if client has multi click between the controls
        if (imagesLayer.find(':animated').length > 0) {
            imagesLayer.find(':animated').stop(true, true);
        }
        
        var $active = imagesLayer.children('.active');
        
        if($active.is('.youtube'))
        {
        	if(ytplayer){
        		ytplayer.pauseVideo();
        	}
        }

        if ($active.length == 0) $active = imagesLayer.children(':last');

        var $next = imagesLayer.children('.element:nth-child(' + index + ')');

		$active.addClass('last-active');
		
		if( $active.is('.map')){
			$active.trigger('onhidden');
		}

		//problem with gmap handling opacity issue
		if( $next.is('.map')){
			$next.css({ visibility:'visible'}).
			addClass('active').delay(delay)
	        .show(1000, function () {
	            $active.removeClass('active last-active');
	        });
			return;
		}
        
        $next.css({ display:'block',opacity: '0'})
        .addClass('active').delay(delay)
        .animate({ opacity: '1'}, 1000, function () {
            $active.removeClass('active last-active');
	    	if($(this).css('filter')!='none')
	            this.style.removeAttribute('filter');
            
        });
        
    }

    //Enabling auto-advance.
    var current = 1;
    function autoAdvance() {
        if (current == -1) return false;

        slideControlLayer.find('ul li').eq(current % slideControlLayer.find('ul li').length).trigger('autoPlay', [true]); // [true] will be passed as the keepScroll parameter of the click function on line 28
        
        //thumbNail.find('ul li').eq(current % thumbNail.find('ul li').length).trigger('autoPlay', [true]);
        
        current++;
    }
    
    // The number of seconds that the slider will auto-advance in:
    var itvl = setInterval(function () { autoAdvance(); }, changeEvery * 1000);

	//it seems that the loading Bar needs to be removed twice
	//as the interval is creating another instance of it.
	

	//$('#loadingBar').css('opacity',1).animate({'opacity':0},function(){$(this).remove();});
	$('#loadingBar').remove();
	
    /* On page load, mark the first thumbnail as active */
    if(slideControlLayer.length > 0)
	    slideControlLayer.find('ul li:first').trigger('autoPlay');
	    
	if(thumbNail.length > 0)
    	thumbNail.find('ul li:first').trigger('autoPlay');
    else{
    	$('#filmstrip-images img').animate({opacity:1},1000);
	}
	if(window.loadInterval != undefined)
		clearInterval(loadInterval);
		
    
    //**************************** 
    //***Booking form ************
    //http://www.stilbuero.de/jquery/tabs/
    //****************************
   //$('#booking-front').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });

    //$('#vd-container').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
    //****************************
    //***Quick info **
    //****************************
    $('#quickInfo .col').height(function () {
		//editing mode
		if($(this).find('.ms-formfieldcontainer').length >0 )
			return 'auto';

        var max = 0;
        $('#quickInfo .col').each(function () {
			var h1 = $(this).find('h2').outerHeight();
			var h2 = $(this).find('.img img').outerHeight();			
			var l = $(this).find('.col-main').outerHeight();
			var t = $(this).find('.text').outerHeight();
			var i = $(this).find('.img').outerHeight();

			//find the highest between text and image and they overlay on top of each other
			h2 = (t > $(this).find('.img img').outerHeight())?t:$(this).find('.img img').outerHeight();
			//find the total height of header and content				
            if (h1+h2 > max)
                max = h1+h2;
        });
        return max;
    });
    $('#quickInfo .col').each(function(index){
    	$('#quickInfo .col').eq(index).css('zIndex',4-index);
    });
    $('#quickInfo .col:last').css('border', 'none');

	if($(".cr-list").length && $(".cr-list").is(':visible')){
		//$(".cr-list").simplyScroll({autoMode: 'loop'});
		$('.cr-list').newsFlash();
	}
	
    //http://blog.jeremymartin.name/2008/02/jtruncate-in-action.html
    $("#custom-reviews li").jTruncate({
        length: 106,
        minTrail: 0,
        ellipsisText: " ...",
        moreText: ""
    });
    
    //home promotion text truncate
    $("#filmstrip #promotions ul li a").jTruncate({
        length: 40,
        minTrail: 0,
        ellipsisText: " ...",
        moreText: ""
    });
    
   
    //campervan detail promotion text truncate    
    $(".left-col-content #promotions ul li a").jTruncate({
        length: 35,
        minTrail: 0,
        ellipsisText: " ...",
        moreText: ""
    });

    if(('#crmTabs').length)
		$('#crmTabs').tabs();
    //****************************
    //***vehicle detail tabs **
    //****************************
    $('#vd-container').tablify({ tabcontainer: '#vd-tab', targetcontainer: '#vd-form',activetabid: $(this).getUrlParam('tabid'), autoHeight:  $(this).getUrlParam('autoheight')});
    
    //$('#vd-container').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'slow' });
    $('#searchField').find(':text').clearText();
    
    $('#showOverFlow').bind('click',function(){
    	$(document).find('div').css('overflow','visible');
    });
    $('#filmstrip-thumb ul li span').each(function(){
    	$(this).css('marginTop',($(this).parent().height() -  $(this).height())/2)
    });

    /*if($('#filmstrip-thumb-container').css('visibility')=='hidden'){
		$('#vehiclePage').addClass('Flat');
	}*/

    //****************************
    //** popup
    //****************************

    if(('#page.popup').length){
	    var closeButton = '<div id="closeButton"><a class="button" href="javascript:window.close()">CLOSE</a></div>';
	    $('#page.popup').prepend(closeButton);
    }
    //***************************
    //** Sitemap
    //***************************
    if($('.SiteMapContainer').length){
	    $('.SiteMapContainer').each(function(){$(this).children('.SiteMapUL1').RowsToColumns(2,630)});
	    $('.SiteMapContainer').find('#coldiv1 .SiteName1:last').addClass('last');
	    $('.SiteMapContainer').find('#coldiv2 .SiteName1:last').addClass('last');	    
    }
    $('#cms.vd-table').ALTRow();    
    $('.vd-table.cms').ALTRow();       
});


$(window).load(function(){
	//****************************
    //***related content **
    //****************************
    if($('.relatedContents .rc img').length >1){
		var h = $('.relatedContents .rc .imgContainer').getHighest('img');
	    $('.relatedContents .rc .imgContainer').each(function(){
	  		  $(this).height(h);
	    });	
    }
});


