this.tooltip = function () {
    /* CONFIG */
    xOffset = -25;
    yOffset = -10;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result		
    /* END CONFIG */
    $(".tooltip").hover(function (e) {
        this.t = this.alt;
        this.title = "";
        $("body").append("<p id='tooltip'>" + this.t + "<span></span></p>");
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function () {
	    this.title = this.t;
	    $("#tooltip").remove();
	});
    $(".tooltip").mousemove(function (e) {
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
    });
};

function cufonize() {

}
function mainMenu() {
    if ($('#mainMenu li.hasSub').length > 0) {

        $("#mainMenu ul li.hasSub").mouseenter(function () {

            var aWidth = $(this).width();
            //aWidth = aWidth + 30;
            aWidth = aWidth + "px";
            //alert(aWidth);
            $(this).has('ul').css({ "width": aWidth });
            $(this).css({ "width": aWidth });
            $(this).addClass("hover");

        });
        $("#mainMenu ul li").mouseleave(function () {
            $(this).removeClass("hover");
            Cufon.refresh();

        });
        $("#mainMenu ul li ul").mouseleave(function () {
            $(this).parents(".hasSub").removeClass("hover");
            Cufon.refresh();
        });

    }
}
function inspiratieCar() {
    if ($('#inspiratieCar').length > 0) {
        $('#inspiratieCar').append('<div class="controls"><a href="#" class="prev"><span>Vorige</span></a><a href="#" class="next"><span>Volgende</span></a></div>');

        $('#inspiratieCar .next').show(); //.delay(1300).animate({ "opacity": 1, "right": "0" });
        $('#inspiratieCar .prev').show(); //.delay(1300).animate({ "opacity": 1, "left": "0" });
        $('#inspiratieCar .car').delay(600).fadeIn();


        $('#inspiratieCar .car').cycle({
            fx: 'fade',
            speed: 'slow',
            timeout: 0,
            cleartype: true, cleartypeNoBg: true,
            next: '#inspiratieCar .next',
            prev: '#inspiratieCar .prev',
            before: function () {
                var thisCurrent = $(this).prevAll().length;
                $('#carimages .cari img').hide();
                $('#carimages .cari img:eq(' + thisCurrent + ')').fadeIn();

            }
        });
    }
}
function hpCar() {
	var thisCurrent = $(this).prevAll().length;
    $('#carimages .cari img').hide();
    $('#carimages .cari:eq(' + thisCurrent + ') img:first').show();

/*    if($.browser.msie && ($.browser.version == '7.0' || $.browser.version == '8.0')){
	$(".titleLeft").css("top", "10px");
    }*/
    if ($('#hpCar').length > 0) {
        $('#hpCar').cycle({
            fx: $.browser.msie && ($.browser.version == '7.0' || $.browser.version == '8.0') ? 'none' : 'fade',
            speed: 'slow',
            timeout: 7000,
            cleartype: true, cleartypeNoBg: true,
            before: function () {
		$(this).css('filter','none');
                var thisCurrent = $(this).prevAll().length;
                $('#carimages .cari img').hide();
                $('#carimages .cari:eq(' + thisCurrent + ') img:first').fadeIn();
            }
        });

        $('#carimages img:not(:first)').hide();
        
    }
}
function tagCloud() {
    //create list for tag links
    $("<ul>").attr("id", "tagList").appendTo("#tagCloud");
    //create tags

    var totalCountTags = 0;
    $.each(tags.Tags, function (i, item) {
        if (item != null) {
            totalCountTags += item.Count;
        }
    });

    $.each(tags.Tags, function (i, item) {
        //create item
        var li = $("<li>");
        //create link
	if(item != undefined){
            $("<a>").text(item.Name).attr({ title: "See all items tagged with " + item.Name, href: "?tag=" + item.Id }).appendTo(li);
            //add to list

            var percentage = Math.round(item.Count / totalCountTags * 10);
            var tagClass = "";

            tagClass = "taggroup" + percentage;

            //        var size;
            //        var padding;

            //        if (item.Count == 0) {
            //            size = "12px";
            //            padding = "3px";
            //        }
            //        else if (item.Count == 1) {
            //            size = "18px"
            //            padding = "3px";
            //        }
            //        else if (item.Count >= 2) {
            //            size = "26px";
            //        }
            //        li.children().css("fontSize", size);
            //        li.css("padding-top", padding);
            li.addClass(tagClass);
            li.appendTo("#tagList");
        }
    });
}
function inspirationFilterChanged() {
    $('#inspiratieCar .car').cycle("stop");
    $('#inspiratieCar .next').animate({ "opacity": 0, "right": "20px" });
    $('#inspiratieCar .prev').animate({ "opacity": 0, "left": "20px" });
    $('#inspiratieCar').delay(300).fadeOut();
    $('#inspiratieResults').delay(300).fadeIn();
    Cufon.refresh();

    $("#inspiratieResults ul li").mouseover(function () {
        $("#inspiratieResults ul li").removeClass("hover");
        $(this).addClass("hover");
    });
    $("#inspiratieResults ul li").mouseleave(function () {
        $("#inspiratieResults ul li").removeClass("hover");
    });
}

Shadowbox.init({
    overlayColor: "#ffffff",
    overlayOpacity: 0.5,
    skipSetup: true,
    troubleElements: ["select", "object", "embed", "iframe"],
    handleOversize: 'drag'
});

function homeGrayFilter() {
	$('#homepage .imaged p.img img').each(function(){
		$(this).attr('src',$(this).data('img-gray'));
	});
	$('#homepage .imaged p.img img').hover(function(){
		$(this).attr('src',$(this).data('img-org'));
	}, function(){
		$(this).attr('src',$(this).data('img-gray'));
	});
}
function homeClickImg() {
	$('#homepage .imaged p.img').each(function(){
		var parent = $(this).parents('.block');
			
		var url = "";
        var target = "";
            
        if ($('a',parent).length > 0) {
            $('h3',parent).css({cursor: 'pointer'});
            $('p.img',parent).css({cursor: 'pointer'});
            $('p.img',parent).bind('click', function() {
				url = $('a',parent).attr('href');
				target = $('a',parent).attr('target');

                if(target == "_blank") {
                    window.open(url);
                } else {
                    window.location = url;
                }                    
                    
            });
			$('h3',parent).bind('click', function() {
				url = $('a',parent).attr('href');
				target = $('a',parent).attr('target');

                if(target == "_blank") {
                    window.open(url);
                } else {
                    window.location = url;
                }                    
                    
            });
        }
	});
}

function showPrintButton() {
    $('.printButton').removeClass('hide');
}

function loadSlideShow() {
    $('.slideshow').cycle({
        fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
    });
}

function initShadowBox() {
    $('a[rel=shadowbox]').click(function (e) {
        e.preventDefault();
        Shadowbox.open({
            content: $(this).attr('href'),
            title: $(this).attr('title'),
            player: 'img'
        });
    });
}

function processStep2() {
    $('#content2').empty();
    $('#contentTitle2').empty();
    $('#content3').empty();
    $('#contentTitle3').empty();
    DisableLinks($('.next-step-disabled'));
}

function processStep3() {
    $('#content3').empty();
    $('#contentTitle3').empty();
    DisableLinks($('.next-step-disabled'));
}

function processStep4() {
    EnableLinks($('.next-step-disabled'));
    $('.next-step').removeClass('next-step-disabled');
}

$(document).ready(function () {
    tooltip();
    mainMenu();
    cufonize();
    inspiratieCar();
    hpCar();
    showPrintButton();
    loadSlideShow();
    DisableLinks($('.next-step-disabled'));

    if ($('#tagCloud').length > 0) {
        tagCloud();
    }
    if ($('#homepage').length > 0) {
        homeGrayFilter();
        homeClickImg();
    }

    if ($('#googlemap').length > 0) {
        var mapCenter = new google.maps.LatLng(51.693203, 5.076628);
        var map = new google.maps.Map(document.getElementById('googlemap'), {
            'zoom': 15,
            'center': mapCenter,
            'mapTypeId': google.maps.MapTypeId.ROADMAP
        });
        var marker = new google.maps.Marker({
            map: map,
            position: new google.maps.LatLng(51.693203, 5.076628),
            draggable: false
        });
    }

    // Shadowbox manual setup
    initShadowBox();

    if ($('#custom-carpet').length > 0) {
        accordion.setTolerateOpenItems(true);
        accordion.init();
        customCarpet.init();

    }

    if ($("#mainMap").length > 0) {
        var projectsMap;
        var projectMap;
        var infoWindow;
        var mapClicked;

        var elm = document.getElementById("mainMap");
        if (elm != null) {
            loadProjectsMap(elm);
            // default show all addresses in the list on page load
            $(".vestigingdetail").show();
        }

    }

    $(".tooltipEnabled img").mouseenter(function () {
        var thisAlt = $(this).attr("alt");
        $(this).parent().append("<div class='tt'>" + thisAlt + "<span></span></div>");
    });
    $(".tooltipEnabled img").mouseleave(function () {
        $(".tooltipEnabled li").find(".tt").remove();
    });

    if ($('#custom-carpet').length < 0) {
        var selectboxes = $("select");
        if (selectboxes.length > 0) {
            for (var i = 0; i < selectboxes.length; i++) {
                if (!$(selectboxes[i]).hasClass('noselectbox')) {
                    $(selectboxes[i]).selectBox();
                }
            }
            // $("select")
            // .selectBox()
            // .change(function () {
            // //alert("changed");
            // });
        }
    }

    $('.print').click(function () {
        print();
        return false;
    });

    /*$('a[href^="http"]').click(function () {
    window.open(this.href);
    return false;
    }).attr("title", "Opent in een nieuw scherm");
    */
});




var markers = new Array();
var visiblemarkers = new Array();
var geocoder;
var firstload;
var infoWindow;

function loadProjectsMap(elm) {
    var coordinates = $('meta[name=projectslatlng]').attr("content");
    var zooming = $('meta[name=projectszoom]').attr("content");
    if (zooming == null || zooming == '') { zooming = '10'; }
    var lat = coordinates.split(',')[0];
    var lng = coordinates.split(',')[1];
    var latlng = new google.maps.LatLng(lat, lng);
    var myOptions = {
        zoom: parseInt(zooming),
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };
    projectsMap = new google.maps.Map(elm, myOptions);
    createMarkers();
    geocoder = new google.maps.Geocoder();

    var marker = new google.maps.Marker({
        position: latlng,
        map: projectsMap,
        icon: "/images/icons/map_home.gif",
        title: "Home"
    });


    google.maps.event.addListener(projectsMap, 'click', function () { activateScrollwheel(); });
    google.maps.event.addListener(projectsMap, 'dragstart', function () { activateScrollwheel(); });

    google.maps.event.addListener(projectsMap, 'idle', function () {
        var bounds = projectsMap.getBounds();
        for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var latlng = markers[i].position;

            if (bounds.contains(latlng) == true) {
                visiblemarkers[visiblemarkers.length] = markers[i].zIndex;
            }
        }
        $(".vestigingdetail").hide();
        for (var j = 0; j < visiblemarkers.length; j++) {
            $(".vestigingResults").show();
            $('.vest' + visiblemarkers[j]).show();
        }
        visiblemarkers = [];
    });
}

function loadGeocodeMap() {
    /*loadProjectsMap($("#mainMap"));*/
    geocode();
}

function geocode() {
    var address = $(".mapsaddress:eq(0)").val();
    geocoder.geocode({
        'address': address,
        'partialmatch': true
    }, geocodeResult);
}

function geocodeResult(results, status) {
    if (status == 'OK' && results.length > 0) {
        projectsMap.fitBounds(results[0].geometry.viewport);
    } else {
        //alert("Geocode was not successful for the following reason: " + status);
        $(".search .row").addClass(".error");
        //$(".search .row .inputs").append('<p class="errorMessage">Locatie is ongeldig. Vul een <em>geldige</em> locatie in</p>');
    }
}


function activateScrollwheel() {
    var myOptions = {
        scrollwheel: true
    };
    projectsMap.setOptions(myOptions);
    google.maps.event.removeListener(projectsMap, 'click');
    google.maps.event.removeListener(projectsMap, 'dragstart');
    map = true;
}


function createMarkers() {
    $.ajaxSetup({ error: ajaxError });

    var url = locationJsonLocation;
    $.getJSON(url, function (data) { renderMarkers(data); });
}

function renderMarkers(data) {
    $.each(data.Coordinates, function (i, item) { setMarker(i, item); });
}

function setMarker(i, item) {
    var image = '/images/icons/map_red.png';
    var markerImage = new google.maps.MarkerImage({
        url: image,
        scaledSize: 16
    });
    //alert(item.Url);
    var mapInfo = item.Coordinates.split('|');
    var lat = mapInfo[0].split(',')[0];
    var lng = mapInfo[0].split(',')[1];
    var latlng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        position: latlng,
        map: projectsMap,
        icon: image,
        title: item.Name,
        zIndex: item.Id
    });
    markers[markers.length] = marker;
    google.maps.event.addListener(marker, 'click', function () {
        createInfoWindow(this);
    });
}

function markerClick(projectId) {
    document.location = '/handlers/' + projectId + '.aspx';
}

function createInfoWindow(marker) {
    if (infoWindow != null) { infoWindow.close(); }
    infoWindow = new google.maps.InfoWindow({
        disableAutoPan: false,
        position: marker.position
    });
    $.ajaxSetup({ error: ajaxError });

    var url = '/scripts/locations.ashx?id=' + marker.zIndex.toString();
    $.getJSON(url, function (data) { renderInfoWindow(data); });


}
function renderInfoWindow(data) {
    var content = '<div class="infobox"><h3>' + data.Name + '</h3>' + data.Street + '<br />' + data.Postcode + ' ' + data.City + '<br /></div>';
    if (data.TelephoneNumber != null) {
        content += data.TelephoneNumber + '<br />';
    }
    //    if (data.EmailAddress != null) {
    //        content += '<a href="mailto:' + data.EmailAddress + '">' + data.EmailAddress + '</a><br />';
    //    }
    if (data.WebsiteUrl != null) {
        content += '<a href="http://' + data.WebsiteUrl + '" target="_blank">' + data.WebsiteUrl + '</a><br />';
    }
    infoWindow.setContent(content);
    infoWindow.open(projectsMap);
}

function hideInfoWindow() {
    infoWindow.close();
}

function ajaxError() {
    //alert('error');
}


function loadProjectMap(elm) {
    var mapInfo = $('meta[name=projectMapInfo]').attr("content").split('|');
    var zooming = '10';
    if (mapInfo.length > 1) {
        zooming = mapInfo[1];
    }
    var coordinates = mapInfo[0];
    if (coordinates != null && coordinates != '') {
        var lat = coordinates.split(',')[0];
        var lng = coordinates.split(',')[1];
        var latlng = new google.maps.LatLng(lat, lng);
        var myOptions = {
            zoom: parseInt(zooming),
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(elm, myOptions);
        var image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png';
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: image
        });
    }
}

function triggerMarker(id) {
    var zoom = 14;

    //var url = '/scripts/locations.ashx?id=' + id;
    //$.getJSON(url, function (data) { performTriggerMarker(data); });

    for (var i = 0; i < markers.length; i++) {
        var marker = markers[i];
        if (marker.zIndex == id) {
            projectsMap.setZoom(zoom);
            projectsMap.panTo(marker.position);
            google.maps.event.trigger(marker, 'click');
            break;
        }
    }
}

function performTriggerMarker(data) {
    var zoom = 14;
    projectsMap.setZoom(zoom);
    projectsMap.panTo(new google.maps.LatLng(data.Latitude, data.Longitude));

    //google.maps.vent.trigger(projectsMap, 'click');
    return false;
}


customCarpet = {
    init: function() {
        accordion.open($('.accordion li:first'), 0);
        customCarpet.initClicks();
    },
    initClicks: function() {
        $('.carpet-select li a.selectable').unbind('click');
        $('.carpet-select li a.selectable').bind('click', function(e) {
            e.preventDefault();
            customCarpet.clickActions($(this));
        });
        $('.carpet-select-finishing li a.selectable').bind('click', function(e) {
            e.preventDefault();
            customCarpet.clickActions($(this));
        });
        initShadowBox();
    },
    clickActions:function($el) {
        var identifier = $el.data('identifier');
        var title = $el.data('title');

        var $parent = $el.parent();
        var $parentUl = $parent.parent();
        var $accordionItem = $parent.parents('li');
        var $nextaccordionItem = $accordionItem.next();


        // get the colors for this quality
        if($el.data('ajax') != undefined && $el.data('ajax') != '') {
            var ajaxUrl = $el.data('ajax');

            $.get(ajaxUrl, function(data){
                    $('.accordion-content',$nextaccordionItem).html(data);
                    customCarpet.initClicks();
                }
            )

        }

        // put identifier in hidden field and display selected in title
        $('input',$accordionItem).val(identifier);
        $('.selected-title',$accordionItem).html('<span class="title-divider">:</span>'+title);

        // select clicked item and deselect others
        $('li', $parentUl).removeClass('selected');
        $parent.addClass('selected');

        // open next accordion item, close current if open items are not tolerated
        if(!accordion.tolerateOpenItems){
            accordion.close($accordionItem, 'normal');
        }
        accordion.open($nextaccordionItem, 'normal');
    }
}

accordion = {
    tolerateOpenItems: false,
    
    init: function() {
        $('.accordion li').each(function() {
            accordion.close($(this), 0);
        });
        $('.accordion h3').unbind('click');
        $('.accordion h3').bind('click', function() {
            var liItem = $(this).parent();
            if($(liItem).hasClass('open')){
                accordion.close($(liItem), 'normal');
            } else {
                accordion.open($(liItem), 'normal');
            }
        });
    },
    open:function($el, speed){
        if(!accordion.tolerateOpenItems){
            $accordion = $el.parents('.accordion');

            $('li.open .accordion-content', $accordion).slideUp(function() {
                $($el).removeClass('open');
            });
        }

        $('.accordion-content', $el).slideDown(speed, function() {
            $($el).addClass('open');
        });
    },
    close:function($el, speed){

        $('.accordion-content', $el).slideUp(speed, function() {
            $($el).removeClass('open');
        });

    },
    setTolerateOpenItems:function(value){
        accordion.tolerateOpenItems = value;
    }
}

function DisableLinks(links) {
    links.each(
        function (index, linkDomElement) {
            var link = $(linkDomElement);
            if (link.attr('tmphref') == undefined)
            {
                // get the 'href' and 'onclick' attribute values
                var linkHRef = link.attr('href');
                var linkOnClick = link.attr('onclick');

                // set the dummy attribute values
                if (link.attr('id') != undefined) {
                    link.attr('href', '#' + link.attr('id')).attr('onclick', 'return false;');
                }
                else {
                    link.attr('href', '#').attr('onclick', 'return false;');
                }

                // add a temporary attribute to keep the original 'href' value
                if (linkHRef != undefined)
                    link.attr('tmphref', linkHRef);

                // add a temporary attribute to keep the original 'onclick' value
                if (linkOnClick != undefined)
                    link.attr('tmponclick', linkOnClick);

                // add the class decorating disabled links
                link.addClass('disabledLink');
            }
        }
    );
}

function EnableLinks(links) {
    links.each(
        function (index, linkDomElement) {
            var link = $(linkDomElement);

            // get the original values of 'href' and 'onclick' attributes from temporary attributes
            var originalLinkHRef = link.attr('tmphref');
            var originalLinkOnClick = link.attr('tmponclick');

            // restore the original 'href' value
            if (originalLinkHRef != undefined)
                link.attr('href', originalLinkHRef);

            // restore the original 'onclick' value
            if (originalLinkOnClick != undefined)
                link.attr('onclick', originalLinkOnClick);

            // remove temporary attributes
            link.removeAttr('tmphref').removeAttr('tmponclick');

            // remove the class decorating disabled links
            link.removeClass('disabledLink');
        }
    );
}
