﻿
//------------------------------------------ 
// Initialize SevenUp
//------------------------------------------
$(document).ready(function() {
    sevenUp.plugin.black.test({
        enableClosing: true,
        enableQuitBuggingMe: true
    });
});

//------------------------------------------- 
// Begin functions:  Topscroller on home page
//-------------------------------------------
function InitTopScroller() {
    var animationSpeed = 320;

    $(window).load(function() {
        $('#top-scroller').nivoSlider({
            effect: 'fade', //Specify sets like: 'fold,fade,sliceDown'
            slices: 15,
            animSpeed: 500,
            pauseTime: 6000,
            startSlide: 0, //Set starting Slide (0 index)
            directionNav: false, //Next & Prev
            directionNavHide: true, //Only show on hover
            controlNav: true, //1,2,3...
            controlNavThumbs: false, //Use thumbnails for Control Nav
            controlNavThumbsFromRel: true, //Use image rel for thumbs
            controlNavThumbsSearch: '.jpg', //Replace this with...
            controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
            keyboardNav: true, //Use left & right arrows
            pauseOnHover: true, //Stop animation while hovering
            manualAdvance: false, //Force manual transitions
            captionOpacity: 0.8, //Universal caption opacity
            beforeChange: function() { },
            afterChange: function() { },
            slideshowEnd: function() { } //Triggers after all slides have been shown
        });
    });

    //calculate intial left position of the model blocks in the scroller
    InitBrandBlockPositions(0, 20, 87);

    //initialize the hover events
    InitTopScrollerHoverEvent(animationSpeed);
}
function InitTopScrollerHoverEvent(animationSpeed) {
    //describes the animations of the model blocks in the top-scroller on hover
    $("div.brand-block").hover(
      function() {
          var thisObj = $(this);
          var sRel = $(thisObj).find(".hidden-field:first").val();
          if ($(thisObj).width() == 87) {
              //check if the hide animation is completed
              if (!$(thisObj).hasClass('animated')) {
                  //stop the scroller
                  $('#top-scroller').data('nivo:vars').stop = true;
                  //set the left property of each next right model
                  SetLeftBrandBlockPositions($(this).index(), 20, 87, 253, 400);

                  $(thisObj).animate({ width: "340px" }, animationSpeed);
                  //change the height property
                  $(thisObj).find(".brand-block-body").filter(':not(:animated)').css("max-height", "122px");
                  $(thisObj).find(".brand-block-body").filter(':not(:animated)').animate({ height: "122px" }, { duration: animationSpeed });
                  //change the logo image size properties
                  $(thisObj).find(".content img.brand-model-logo").filter(':not(:animated)').animate({
                      width: 108,
                      height: 34
                  }, animationSpeed, function() {
                      //when completed: 
                      //animate the seperator by changing the height property,
                      $(thisObj).find(".seperator").filter(':not(:animated)').animate({ height: "118px" }, { duration: animationSpeed });
                      //show the models information by a fade animation,
                      $(thisObj).find(".content div.left").stop(true, true).fadeIn('fast');
                      //show the relate model image in the scroller
                      $('.nivo-control[rel="' + sRel + '"]').click();
                  });
              }
          }
      },
      function() {
          var thisObj = $(this);
          $(thisObj).addClass('animated');
          //hide the models information by a fade animation
          $(this).find(".content div.left").stop(true, true).fadeOut('fast');

          //animate the seperator by changing the height property
          $(thisObj).find(".seperator").animate({ height: "0px" }, animationSpeed, function() {
              //when completed:
              //change the logo image size properties
              $(thisObj).find(".content img.brand-model-logo").animate({
                  width: 70,
                  height: 23
              }, { queue: false, duration: animationSpeed });
              //change the width property
              $(thisObj).animate({ width: "87px" }, { queue: false, duration: animationSpeed });
              //change the height property
              $(thisObj).find(".brand-block-body").animate({ height: "32px" }, animationSpeed, function() {
                  $(this).css("max-height", "32px");
                  $(thisObj).removeClass('animated').dequeue();

              });

          });
          //set the left property of each next right model
          SetLeftBrandBlockPositions($(thisObj).index(), 20, 87, 0, 400);
          //start the scroller
          $('#top-scroller').data('nivo:vars').stop = false;
      });
}

//sets the intial left position of the model blocks in the scroller
function InitBrandBlockPositions(currentItemIndex, left, width) {
    var itemCounter = 0;
    $("div.brand-block").each(function(i) {
        if (itemCounter > currentItemIndex) {
            var thisLeft = (left + width) * itemCounter;
            $(this).css("left", thisLeft + "px");
        }
        itemCounter++;
    });
}

//sets the left position of each next model block in the scroller
function SetLeftBrandBlockPositions(currentItemIndex, left, widthDefault, widthTo, speed) {
    var itemCounter = 0;
    $("div.brand-block").each(function(i) {
        if (itemCounter > currentItemIndex) {
            var thisLeft = ((left + widthDefault) * itemCounter) + widthTo;
            $(this).animate({ left: thisLeft + "px" }, { queue: false, duration: speed });
        }
        itemCounter++;
    });
}
//------------------------------------------ 
// End functions:  Topscroller on home page
//------------------------------------------


//------------------------------------------------- 
// Begin functions:  Preowned carousel on home page
//-------------------------------------------------
function InitPreOwnedCarousel() {
    //buttons are not visible onload
    $("#carouselButtonPrevious").css("visibility", "visible");
    $("#carouselButtonNext").css("visibility", "visible");
    //position of the listitem is absolute onload en relative when page is loaded
    $("#contentHomePreOwned #preOwnedCarousel ul li").css("position", "relative");

    $("#preOwnedCarousel").hover(function() {
        var description = $(this).find(".description"); //$("#contentHomePreOwned .description");
        $(description).animate({ "top": "0px" }, { queue: false, duration: 500 });
    }, function() {
        var description = $(this).find(".description"); //$("#contentHomePreOwned .description");
        $(description).animate({ "top": "60px" }, { queue: false, duration: 500 });
    });

    jQuery('#preOwnedCarousel').jcarousel({
        scroll: 1,
        initCallback: preOwnedcarousel_initCallback
    });


}
function preOwnedcarousel_initCallback(carousel) {
    jQuery('#carouselButtonNext').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#carouselButtonPrevious').bind('click', function() {
        carousel.prev();
        return false;
    });
};

var Map = {
    map: null,
    lat: 52.17,
    lon: 5.2,
    zoom: 16,
    finalZoomLevel: 16,
    contactLayer: null,
    init: function(target, newZoomLevel) {
        try {
            map = new VEMap(target);
        } catch (e) { }
        if (map == undefined) return;

        if (newZoomLevel !== undefined) Map.zoom = newZoomLevel;

        map.AttachEvent("oninitmode", function() {
            $(".center-location").each(function() {
                if (this.value != "") {
                    Map.search(this.value);
                }
            });
        });

        map.SetDashboardSize(VEDashboardSize.Small);
        map.LoadMap();
        map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
        map.SetCenterAndZoom(new VELatLong(Map.lat, Map.lon), Map.zoom - 1);
        map.SetMapStyle(VEMapStyle.Aerial);
        map.ShowMessageBox = false;
        this.contactLayer = this.createLayer();
    },
    get_contactLayer: function() { return this.contactLayer; },
    createLayer: function() {
        var layer = new VEShapeLayer();
        map.AddShapeLayer(layer);
        return layer;
    },
    setLayerVisibility: function(layer, visible) {
        if (visible)
            layer.Show();
        else
            layer.Hide();
    },
    search: function(input) {
        map.Find(null, input);
    },
    clearPins: function() {
        map.DeleteAllShapes();
    },
    zoomIn: function() {
        map.ZoomIn();
    },
    setCenter: function(center) {
        map.Find(null, center, VEFindType.Businesses, null, null, null, false, false, false, false,
			    function(layer, resultsArray, places, hasMore, veErrorMessage) {
			        if (null != places) {
			            map.SetCenter(places[0].LatLong);
			            map.SetZoomLevel(Map.zoom);
			        }
			    }
		    );
    },
    addPin: function(lat, lon, icon, header, infobox, layer, isCustomStyle) {
        if (lat == "" || lon == "")
            return;
        var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));

        if (isCustomStyle) {
            map.ClearInfoBoxStyles();
        } else {
            map.SetInfoBoxStyles();
        }

        //Set the icon
        shape.SetCustomIcon(icon);
        shape.SetTitle("");
        shape.SetDescription(infobox);
        //Set the info box

        var target = layer;
        target.AddShape(shape);
        return shape.GetID();
    },
    addContact: function(name, description, url, location) {
        var icon = "<div><img src='/images/maps-icon.png' alt='Jaguar' /></div>";
        var htmlDescription = description.replace(/--br--/gi, "<br />");
        var infobox = "";
        infobox += "<div class='wide_pin'>";
        infobox += "<div class='wide_pin_top'></div>";
        infobox += "<div class='wide_pin_middle'>";
        infobox += "<div class='wide_pin_content'>";
        infobox += "<div>";
        infobox += "<p class='wide_pin_description_wide_text'><b>" + name + "</b></p>";
        infobox += "<p class='wide_pin_description_wide_text'>" + htmlDescription + "</p>";
        if (url != "" && url != null) {
            infobox += "<a href='" + url + "' title='Route' target='_blank'>Plan route</a>";
        }        
        infobox += "</div>";
        infobox += "</div>";
        infobox += "</div>";
        infobox += "<div class='wide_pin_bottom'></div>";
        infobox += "</div>";
        var center = true;
        var type = this.get_contactLayer();
        map.Find(null, location, VEFindType.Businesses, null, null, null, false, false, false, false,
			function(layer, resultsArray, places, hasMore, veErrorMessage) {
			    if (null != places) {
			        if (center) {
			            map.SetCenter(places[0].LatLong);
			            map.SetZoomLevel(Map.zoom);
			        }

			        id = Map.addPin(places[0].LatLong.Latitude, places[0].LatLong.Longitude, icon, '', infobox, type, true);
			    } else {
			        //alert("no results! " + veErrorMessage);
			    }
			}
		);
    }
};
//------------------------------------------------ 
// End functions:  Preowned carousel on home page
//------------------------------------------------

//------------------------------------------------ 
// Begin functions:  Model page
//------------------------------------------------
function InitModelCarouselAndSlider() {
    jQuery('ul.thumb-model-carousel').jcarousel({
        scroll: 1,
        animation: "fast",
        wrap: 'first',
        size: mycarousel_itemList.length,
        itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback_small },
        initCallback: mycarousel_initCallback_small

    });

    jQuery('ul.model-carousel').jcarousel({
        start: 1,
        scroll: 1,
        animation: "fast",
        wrap: 'circular',
        size: mycarousel_itemList.length,
        itemVisibleInCallback: { onBeforeAnimation: mycarousel_itemVisibleInCallback },
        itemFirstInCallback: { onAfterAnimation: mycarousel_itemFirstOutCallbackAfterAnimation },
        itemVisibleOutCallback: { onAfterAnimation: mycarousel_itemVisibleOutCallback }
    });
}

function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1], '640', false));

    //scroll big slider when click on an image from this carousel
    $('.model-carousel .jcarousel-item').bind('click', function() {
        var index = $(this).attr('jcarouselindex');
        if (index != null)
            carousel.scroll(jQuery.jcarousel.intval(index));
        return false;
    });

    //scroll big slider when click on a thumb
    $('.thumb-model-carousel .jcarousel-item').bind('click', function() {
        $('.thumb-model-carousel .jcarousel-item').removeClass("active");
        $(this).addClass("active");

        var index = $('.thumb-model-carousel .jcarousel-item').index($(this));

        carousel.scroll(jQuery.jcarousel.intval(index) + 1);

        return false;
    });
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
};

function mycarousel_itemFirstOutCallbackAfterAnimation(carousel, item, i, state, evt) {
    //set a trigger to notify the 'big-image-loaded' event, wich scrolls the small-carousel to the selected image
    $('#model-carousel-container').trigger('big-image-loaded', [i]);
    $(".model-carousel .jcarousel-item.active").animate({ opacity: 0.5 }, 500);
    //remove all active classes
    $(".model-carousel .jcarousel-item.active").removeClass("active");
    //set current li active
    item.className = item.className + " active";
    //animate opacity of the li
    $(".model-carousel .jcarousel-item.active").animate({ opacity: 1 }, 500);
}


function mycarousel_itemLoadCallback_small(carousel, state) {
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }
        if (i > mycarousel_itemList.length || i < 0) {
            break;
        }
        carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i - 1], '110', true));
    }
}
function mycarousel_initCallback_small(carousel) {
    //set the first item active
    $('.thumb-model-carousel .jcarousel-item:first').addClass("active");

    $('#model-carousel-container').bind('big-image-loaded', function (event, i) {
        var index = parseInt(i);
        if (index > mycarousel_itemList.length) {
            index = index % mycarousel_itemList.length;
            if(index == 0)
                index = mycarousel_itemList.length;
        }
        carousel.scroll(jQuery.jcarousel.intval(index));

        //remove all active classes
        $(".thumb-model-carousel .jcarousel-item.active").removeClass("active");
        index--;
        if (index >= mycarousel_itemList.length) {
            index = index % parseInt(mycarousel_itemList.length);
        }
        $('.thumb-model-carousel .jcarousel-item:eq(' + index + ')').addClass("active");

        return false;
    });

    $('#carouselButtonNext').bind('click', function() {
        carousel.next();
        return false;
    });

    $('#carouselButtonPrevious').bind('click', function() {
        carousel.prev();
        return false;
    });
}
/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item, width, inDiv) {
    if (item != null) {
        var url = item.url.replace("width=", "width=" + width)
        if (inDiv == true) {
            return '<div><img src="' + url + '" alt="' + item.title + '" /></div>';
        } else {
            return '<img src="' + url + '" alt="' + item.title + '" />';
        }
    }
    return null;
};
//------------------------------------------------ 
// End functions:  Model page
//------------------------------------------------

//------------------------------------------------ 
// Begin functions:  Pre-owned detail page
//------------------------------------------------
var timeoutPreOwnedCarouselSlider;
var firstPreOwnedCarouselSlider = true;
var preOwnedImages = "";

function ShowImageInShadowBox(imageUrl) {
    preOwnedImages.each(function (index, element) {
        var thisHref = $(element).attr("href");
        if (thisHref.indexOf(imageUrl) > -1) {
            $(element).click();
            return;
        }
    });
    stopPreOwnedCarouselSlider();
}

function InitPreOwnedCarouselSlider(images) {
    preOwnedImages = images;
    jQuery('ul.galleria').jcarousel({
        start: 1,
        scroll: 1,
        animation: "fast",
        initCallback: initCallbackFunctionPreOwnedCarouselSlider
    });

    $('ul.galleria').galleria({
        history: false,
        insert: "#galleria_container",
        onImage: function (image, caption, thumb) { // let's add some image effects for demonstration purposes
            var newLink = $("<a ></a>");
            newLink.attr("href", "#");
            newLink.unbind();
            newLink.click(function () {
                ShowImageInShadowBox(image.attr("src"));
            });
            newLink.append(image.clone());
            image.replaceWith(newLink);


            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // fade out inactive thumbnail
            _li.siblings().children('img.selected').fadeTo(500, 0.3);

            // fade in active thumbnail
            thumb.fadeTo('fast', 1).addClass('selected');

            // add a title for the clickable image
            image.removeAttr('width');
            image.removeAttr('height');

            // add event
            $('#galleria_container').trigger('image-loaded');

            // to each list item
            $('ul.galleria li').each(function (idx) {

                // add data 'index' with value idx+1
                $(this).data('index', (++idx));
            });
        },
        onThumb: function (thumb) { // thumbnail effects goes here

            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // if thumbnail is active, fade all the way.
            var _fadeTo = _li.is('.active') ? '1' : '0.3';

            // fade in the thumbnail when finnished loading
            thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn(1500);

            // hover effects
            thumb.hover(
						function () { thumb.fadeTo('fast', 1); },
						function () { _li.not('.active').children('img').fadeTo('fast', 0.3); } // don't fade out if the parent is active
					);

            thumb.click(stopPreOwnedCarouselSlider);
        }

    }).find('li:first').addClass('active');
    // For some reason, if the page is visited again without refresh, the galleria didn't work. This is a fix
    if ($('ul.galleria').find('li:first').find('img').attr('rel') !== undefined)
        $.galleria.activate($('ul.galleria').find('li:first').find('img').attr('rel'));
    if ($('ul.galleria').find('li:eq(1)').length > 0)
        nextImagePreOwnedCarouselSlider();
}

function nextImagePreOwnedCarouselSlider() {
	if (!firstPreOwnedCarouselSlider)
		$.galleria.next();
	firstPreOwnedCarouselSlider = false;
	timeoutPreOwnedCarouselSlider = setTimeout("nextImagePreOwnedCarouselSlider()", 4000);
}

function stopPreOwnedCarouselSlider() {
	clearTimeout(timeoutPreOwnedCarouselSlider);
}

function initCallbackFunctionPreOwnedCarouselSlider(carousel) {
	$('#galleria_container').bind('image-loaded', function() {
		var idx = $('.galleria li.active').data('index') - 2;

		carousel.scroll(idx);
		return false;
	});
};

//------------------------------------------------ 
// End functions:  Pre-owned detail page
//------------------------------------------------

function GoToUrl(url) {
    if (url != null) {
        if (url != "") {
            //navigate to the url value
            window.location.href = url;
        }
    }
}  
