/**********
*   Initialisation
**********/
$(document).ready(function () {

    //replace fonts
    Cufon.replace('h1');
    Cufon.replace('h2');
    Cufon.replace('h3');
    Cufon.replace('.menu a');
    Cufon.replace('.buttonLeft a', {hover: true});
    Cufon.replace('.buttonRight a', {hover: true});
    Cufon.replace('.buttonLeftNav a');
    Cufon.replace('.buttonRightNav a');
    Cufon.replace('button.zoek');
    Cufon.replace('.winkel_tekst');
    Cufon.replace('.servicepunten li a');

    //layout
    stretchContent();
    /*@cc_on
        startList();
    @*/

    //fix transparency png pictures
    $(".hoofdcats").pngFix();
    $(".subcatContainer .foto").pngFix();
    $(".vraagContainer").pngFix();
    $(".winkelContainer .foto").pngFix();
    $("#submenu li li.last a").pngFix();
    $(".zoek_postcode").pngFix();
    $(".servicepunten li img").pngFix();

    //add event handlers
    $(".hoofdcats li.hoofdcat h1 a, .hoofdcats li.hoofdcat .overlay_hoofdcat a").bind("click", function (event) {
        event.preventDefault();                 //don't load next page
        event.stopPropagation();                //idem
        showSubCats($(this).attr('href'));      //show subcategories
    });

    //ie6 homepage event
    $("li.hoofdcat img, li.hoofdcat .overlay_hoofdcat").bind('click', function() {
        linkElement = $(this).next().find('a');
        linkElement.trigger('click');
    });

    //inzoomen fotos op homepage
    $("li.hoofdcat").hover(
      function () {
          $(this).find('img').stop().animate({width: (186*1.1)+'px', height: (144*1.1)+'px'}, 500);
      },
      function () {
          $(this).find('img').stop().animate({width: '186px', height: '144px'}, 500);
      }
    );

    $(".winkelSummary").bind("click", displayWinkelInfo);

    // Links met rel="external" moeten in een nieuw venster worden geopend
    $('A[rel="external"]').click( function() {
        window.open(jQuery(this).attr('href') );
        return false;
    } );

    //start slideshow van winkels
    $('.winkel_slideshow').cycle({
        delay:  3000,
        speed:  500,
        before: onBefore,
        after:  onAfter
    });

    $(".servicepuntenContainer ul li a").bind("click", switchServicepunt);
    $(".slideshow_clickwindow").bind("click", function() {
        $('.winkel_slideshow img.current').trigger('click');
    });

});

// function for preloading images
jQuery.preloadImages = function(){
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}

/*****
*   Winkels
*****/

function displayWinkelInfo(event) {

    //voorkom doorklik tegen
    event.preventDefault();

    //hide alle infoContainers
    $('.winkelContainer').hide();

    //maak alle links unbold
    $('.winkelSummary a').css('font-weight', 'normal');
    $('.winkelSummary a.titel').css('text-decoration', 'underline');

    //maak deze links bold
    id = $(this).attr('id');
    links = $('#' + id + ' a').css('font-weight', 'bold').css('text-decoration', 'none');

    //laat deze infoContainer zien
    el = $('#' + id + 'Info > .winkelContainer');
    el.fadeIn('slow');

}

/*****
*   Homepage animatie
*****/

function showSubCats(sKey) {

    //haal met AJAX data van subcats op
    $.getJSON("../ajax/getSubCats.php", { titel_key: sKey },
        function(json) {

            //zet data om
            aData = eval(json);

            //return true als er geen subcats zijn, dan moet de link gewoon werken
            //zodat we doorgaan naar de subcat-index
            if (aData.length == 0) {
                location.href = sKey;
                return true;
            }

            //grey out hoofdcats
            $('<li class="overlay_inactive" style="display: none;"><a href="/"></a></li>').appendTo('.hoofdcats').fadeIn("slow");
            $('.hoofdcats').pngFix();
            //show active hoofdcat
            $('.'+sKey).css('z-index', 1000).addClass('hoofdcat_active').removeClass('hoofdcat');

            var aElements = new Array();
            var aPositions = new Array();

            //plaats de subcats
            for(i=0; i<aData.length; i++) {

                //maak divjes aan
                aElements[i] = $('<li class="subcat" style="display:none;"><img src="crop/186/144/'+aData[i]['foto']+'" alt="'+aData[i]['titel']+'"><div class="overlay_subcat"><a href="'+sKey+'/'+aData[i]['titel_key']+'/"></a></div><h1><a href="'+sKey+'/'+aData[i]['titel_key']+'/">'+aData[i]['titel']+'</a></h1></li>').appendTo('.hoofdcats');

                //bepaal plaats van divjes
                aPositions[i] = $('#plaats'+aData[i]['positie']).position();

                //plaats de divjes
                aElements[i].css('position', 'absolute');
                aElements[i].css('z-index', '1000');
                aElements[i].css('top', aPositions[i].top);
                aElements[i].css('left', aPositions[i].left);

                //replace fonts again
                Cufon.replace('.hoofdcats h1');

            }

            //verwijder alle eventuele binds
            $(".hoofdcats li.hoofdcat h1 a, .hoofdcats li.hoofdcat .overlay_hoofdcat a, .hoofdcats li.hoofdcat_active h1 a, .hoofdcats li.hoofdcat_active .overlay_hoofdcat a, li.hoofdcat img").unbind();

            //add event handlers
            $(".hoofdcats li.hoofdcat_active h1 a, .hoofdcats li.hoofdcat_active .overlay_hoofdcat a, .overlay_inactive, #backgroundLeft").bind("click", function(event) {
                event.preventDefault();         //don't load next page
                event.stopPropagation();        //idem
                hideSubCats();                  //hide subcats
            });
            //add event handlers for subcats
            $(".hoofdcats li.subcat h1 a, .hoofdcats li.subcat .overlay_subcat a").bind("click", function (event) {
                event.stopPropagation();
                location.href = event.target;
            });
            //inzoomen fotos op homepage
            $("li.subcat").hover(
              function () {
                  $(this).find('img').stop().animate({width: (186*1.1)+'px', height: (144*1.1)+'px'}, 500);
              },
              function () {
                  $(this).find('img').stop().animate({width: '186px', height: '144px'}, 500);
              }
            );

            //ie6 homepage event
            $("li.hoofdcat_active img, li.hoofdcat_active .overlay_hoofdcat, li.subcat img, li.subcat .overlay_subcat").bind('click', function() {
                linkElement = $(this).next().find('a');
                linkElement.trigger('click');
            });

            $(document).delay(500, function() {
                $('li.subcat').fadeIn('slow');
                $('.hoofdcats').pngFix();
            });

            return false;

        });

    return false;

}

function hideSubCats() {

    //verwijder alle eventuele binds
    $(".hoofdcats li.hoofdcat_active h1 a, .hoofdcats li.hoofdcat_active .overlay_hoofdcat a, .overlay_inactive, #backgroundLeft").unbind();
    $(".hoofdcats li.subcat, .hoofdcats li.subcat h1 a, .hoofdcats li.subcat .overlay_subcat a, li.hoofdcat_active img, li.hoofdcat_active .overlay_hoofdcat, li.subcat img").unbind();

    //verwijder subcats en overlays
    $('li.overlay_inactive').remove();
    $('li.subcat').remove();

    //verwijder class hoofdcat_active
    $('.hoofdcat_active').addClass('hoofdcat').removeClass('hoofdcat_active');

    //zet alle hoofdcats op z-index 500
    $('.hoofdcats li').css('z-index', 500);

    //add event handlers
    $(".hoofdcats li.hoofdcat h1 a, .hoofdcats li.hoofdcat .overlay_hoofdcat a").bind("click", function (event) {
        event.preventDefault();                 //don't load next page
        event.stopPropagation();                //idem
        showSubCats($(this).attr('href'));      //show subcategories
    });

    //ie5 homepage event
    $("li.hoofdcat img, li.hoofdcat .overlay_hoofdcat").bind('click', function() {
        linkElement = $(this).next().find('a');
        linkElement.trigger('click');
    });

}



/*****
*   Winkels slideshow
*****/

function onBefore(currSlideElement, nextSlideElement, options, forwardFlag) {
    $('span.winkel_tekst').html('');
    $(currSlideElement).unbind("click", winkelClickThrough);
    $(currSlideElement).removeClass('current');
    $(nextSlideElement).bind("click", winkelClickThrough);
    $(nextSlideElement).addClass('current');
};

function onAfter(currSlideElement, nextSlideElement, options, forwardFlag) {
    $('span.winkel_tekst').html('ServicePartner<br>' + this.alt);
    Cufon.replace('.winkel_tekst');
};

function winkelClickThrough(event) {

    sKey = $(event.target).attr('class').split(' ');
    location.href = $('base').attr('href') + "de_winkels/"+sKey[0];

}

/*****
*   Layout
*****/

function stretchContent() {

    //bepaal de hoogte van de browser
    if( typeof( window.innerHeight ) == 'number' ) {
        browserHeight = window.innerHeight;
    } else {
        browserHeight = document.documentElement.clientHeight;
    }

    //bepaal de hoogte van de header
    headerHeight = $('#header').css('height');
    headerHeight = headerHeight.substr(0, headerHeight.length-2);

    //bepaal de hoogte van de footer
    footerHeight = $('#footer').css('height');
    footerHeight = footerHeight.substr(0, footerHeight.length-2);

    //bepaal de nieuwe hoogte van de content div
    //browserHeight - headerHeight - footerHeight - 80px padding
    newHeight = browserHeight-headerHeight-footerHeight-80;
    newHeight = newHeight + 'px';

    ie6 = false;
    //test of we te maken hebben met ie6
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion<=6) {
            ie6 = true;
        }
    }

    //als we een normale browser hebben zetten de min-height
    if (!ie6) {
        $('#content').css('min-height', newHeight);
    //dat werkt niet in ie6, dus gebruiken we gewoon height
    } else {
        $('#content').css('height', newHeight);
    }

}

/*****
*   Forms
*****/


/*
    check if the value of the postcode-field is correct
*/
function checkPostcode(formId) {

    if (validatePostalCode($("#"+formId+" input[name='postcode']").val())) {
        //alles is goed, return true
        return true;
    } else {
        //postcode klopt niet, genereer foutmelding en return false
        $("#zoek_winkel_postcode_error").html('U heeft een verkeerde postcode ingevuld.');
        return false;
    }

}

function validatePostalCode(string) {

    if (string.match(/[1-9][0-9]{3} ?[a-zA-Z]{2}/)==string) {
        return true;
    } else {
        return false;
    }

}

function formatPostcode(formId) {

    //postcode trimmen
    sPostcode = $("input[name='postcode']").val();
    sPostcode = sPostcode.replace(/\s+/g,'');

    //letters toevoegen
    if (sPostcode.match(/[1-9][0-9]{3}/)==sPostcode) {

        $.getJSON('ajax/getPostcodeLetters.php', {postcode: sPostcode}, function(json) {

            //letters plakken
            if (json != null) {
                sPostcode = sPostcode+json;
            }

            //geformat terugzetten
            $("input[name='postcode']").val(sPostcode);
            //formulier opnieuw versturen
            $(formId).submit();

        });

        //formulier niet laten verzenden tot de postcode is aangepast
        return false;

    } else {

        //geformat terugzetten
        $("input[name='postcode']").val(sPostcode);
        return true;

    }

}

function clearSearchField() {

    var searchField = $('.menu .searchField input');
    var data = searchField.val();

    if (data == 'waar wilt u meer over weten?') {
        searchField.val('');
    }

}

function fillSearchField() {

    var searchField = $('.menu .searchField input');
    var data = searchField.val();

    if (data == '') {
        searchField.val('waar wilt u meer over weten?');
    }

}

/*****
*   Menu
*****/

function startList() {

    if (document.getElementById("submenu") != null) {
        var sfEls = document.getElementById("submenu").getElementsByTagName("LI");
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover=function() {
                this.style.width = this.offsetWidth + 'px';
                parentEl = this.parentNode;
                if (parentEl.className != 'subsubmenu') {
                    this.className+=" hover";
                }
            }
            sfEls[i].onmouseout=function() {
                this.className=this.className.replace(new RegExp(" hover\\b"), "");
            }
        }
    }
}

/*****
*   Service punten animatie
*****/

function switchServicepunt(event) {

    //stop doorklik
    event.preventDefault();
    //bepaal key van item dat we laten zien
    if (event.target.nodeName == "A") {
        sKey = $(event.target).attr('id');
    } else {
        sKey = $(event.target).parents('a').attr('id');
    }
    if ((sKey == '') || (sKey == 'undefined')) {
        return false;
    }

    if (window.sOndernemerUrl === undefined) {
        sUrl = '../ajax/getServicepunt.php';
    } else {
        sUrl = sOndernemerUrl + 'ajax/getServicepunt.php';
    }

    //haal data op
    $.getJSON(sUrl, { titel_key: sKey },
        function(json) {

            //decode json
            aData = eval(json);

            //verberg active bg
            $('.servicepunten li.active').removeClass('active');
            $('#'+aData['titel_key']).parent('li').addClass('active');

            //verberg huidige tekst en foto
            $('.servicepunten .tekst, .servicepuntenContainer .foto').fadeOut('fast', function() {
                //vul nieuwe data
                $('.servicepunten .tekst img').attr('src', aData['icoon']);
                $('.servicepunten .tekst img').attr('alt', aData['titel']);
                $('.servicepunten .tekst h3').html(aData['titel']);
                $('.servicepunten .tekst .clearer').nextAll().remove();
                $('.servicepunten .tekst').append(aData['tekst']);
                $('.servicepuntenContainer .foto img').addClass('hidden');
                $('.servicepuntenContainer .foto img.'+sKey).removeClass('hidden');
                //toon nieuwe tekst en foto
                $('.servicepunten .tekst, .servicepuntenContainer .foto').fadeIn('fast');
            });

        }
    );

}

/*****
*   Hulpjes
*****/

/*
function ucwords(str) {

    return str.replace(/\b\w/gi, function(c,i,s) {
        return c.toUpperCase();
    });

}
*/

function ucwords (str) {
    // Uppercase the first character of every word in a string
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}


/*****
*   Routeplanner formulier aanpassen
*****/

function setRouteForm() {

    //er is een vertrekadres opgehaald
    if ($('#route_van').val() != '') {

        $('#route_van').unbind('focus');
        $('#route_van').addClass('route_van_vol');
        $('form button.route_submit').removeClass('route_submit').addClass('route_reset');
        $('form button.route_reset').click(function() { clearRouteForm(); return false; });
        return true;

    //er moet nog een vertrekadres ingevuld worden
    } else {

        $('#route_van').removeClass('route_van_vol').val('Vul een vertrekadres in...');
        $('#route_van').focus(function() { $('#route_van').val(''); });
        $('form button.route_reset').unbind('click');
        $('form button.route_reset').removeClass('route_reset').addClass('route_submit');
        return false;

    }

}

function clearRouteForm() {

    $('#route_van').removeClass('route_van_vol').val('Vul een vertrekadres in...');
    $('#route_van').focus(function() { $('#route_van').val(''); });
    $('form button.route_reset').unbind('click');
    $('form button.route_reset').removeClass('route_reset').addClass('route_submit');

}

