var pathExpressInstallFile = escape("/lib/flash/expressInstall.swf");

function initContentFlash() {
    $('.contentflash').each(
        function() {
            var strId = $(this).attr('id');
            var strParams = $(this).find('a').attr('rel').split('|');

            $('#' + strId).flashembed(
            {
                src: strParams[0],
                version: [strParams[1]],
                width: strParams[2],
                height: strParams[3],
                expressInstall: pathExpressInstallFile,
                wmode: 'transparent',
                scale: 'noscale'
            })
        }
    );
       }

function initHyperlinks() {
    
	$("a[rel=realpages]").fancybox({
		'width': 900,
		'height': 660,
		'type': 'iframe'
	})

    $('.various').fancybox({
        'type': 'ajax',
        'ajax': {
            dataFilter: function(data) {
                return $(data).find('#nyro')[0];
            }
        }
    });

    $('.case_afbeelding').fancybox({ 'type': 'image' });
    $('.fancybox').fancybox({ 'type': 'iframe' });

    $('.fancybox').click(function() { 
        console.log($(this).attr('href'));
    })

	$(".paragraph a[rel=external]").each(function() {
		$(this).after('<a href="' + $(this).attr('href') + '" title="Open deze link in een nieuw venster" class="newwindowlink">&nbsp;<img src="/lib/images/external_link.png" alt="(Openen in nieuw venster?)"></a>');
		$(this).next('.newwindowlink').click(function() { window.open($(this).attr("href")); return false; });

	});

	//get all hyperlinks with http in href
/*
	$("a[href*=http]").each(function() {
		var x = $(this).attr("href");

		try {
			//_gaq.push(['_trackEvent(\'Externe hyperlinks\', ' + x + ')']);
			_gaq.push(['_trackEvent', 'Externe hyperlinks', 'click', x]);
		} catch (err) { }

		//check if rel=external
		if ($(this).attr('rel') == 'external') {
			$(this).click(function() {
				setTimeout(function() { window.open(x); }, 100)
				return false;
			});
			if ($(this).attr("title") == "") $(this).attr("title", "Deze link wordt in een nieuw venster geopend.")
			else $(this).attr("title", "'" + $(this).attr("title") + "' wordt in een nieuw venster geopend.");
		}
		//check if rel=realpages
		else if ($(this).attr('rel') == 'realpages') {
			//do nothing
		}
		else {
			$(this).click(function() {
				setTimeout(function() { document.location = x; }, 100)
				return false;
			});
		}
	});
	*/
}

function initSubMenu(){
    $("#accordion").accordion({
        header: '.block', 
        event: 'click',
        animated: 'easeOutCubic',
        active: intSubMenuActiveIndex,
        autoHeight: false
    });	
}

function initNoFlashContainer(){
    $.ajax({
        type: "GET",
        url: '/lib/xml/Cases_mobile.ashx',
        dataType: "xml",
        success: function(data) {
            $(data).find("project").each(function() {
                var thumb = $(this).find('thumb').text();
                var titel = $(this).find('titel').text();
                var desc = $(this).find('omschrijving').text();
                var link = $(this).find('link').parent().text();
                var url = link.substring(link.search(/\/\d/), link.length);

                $('.slideshow').prepend('<div class="moving_box"><img src="' + thumb + '" /><h2>' + titel + '</h2><p>' + desc + '<a href="' + url + '" class="read-more-link"  title="' + titel + '">lees meer</a></p></div>');
            });
            $('#flashcases').prepend('<div id="arrowLeft" class="arrows"></div>');
            $('#flashcases').prepend('<div id="arrowRight" class="arrows"></div>');
            
            $(".slideshow").cycle({ fx: 'scrollHorz', random: 1, timeout: 10000, next: '#arrowRight', prev: '#arrowLeft'});
        }
    });

    $(".slideshow").touchwipe({
		wipeLeft: function() {
		    $(".slideshow").cycle("prev");
		},
		wipeRight: function() {
		    $(".slideshow").cycle("next");
		}
	});
	
	
	$('#arrowLeft').click(function(){
		$(".slideshow").cycle("prev");
	});
	
	$('#arrowRight').click(function(){
		$(".slideshow").cycle("next");
    });    
}


function initNieuwsItems() {
	$('.boxgrid.nieuwsbericht').hover(function() {
        $(".cover", this).stop().animate({top:'123px'},{queue:false,duration:260});
    }, function() {
        $(".cover", this).stop().animate({top:'177px'},{queue:false,duration:260});
});
    

    
/*$('.nieuwsbericht a').click(function(){
        var strNieuwsDetailUrl = $(this).attr('href') + ' #nieuwsdetail';
        $('#nieuwsitems .nieuwsdetail').load(strNieuwsDetailUrl, function(){
            $('#sluitnieuwsdetail').click(function(){
                $('#nieuwsitems .nieuwsdetail').animate( 
                    {top: '-546px'},
                    {
                    easing: 'easeInCubic',
                    duration: 500
                    }
                ); 
                return false;               
            });
            $('#nieuwsitems .nieuwsdetail').animate( 
                {top: '0'},
                {
                easing: 'easeOutBounce',
                duration: 1000
                }
            );
        });
        return false;
    });
*/    
}

function FlashSetSize(width, height) {   
    $('#upperLeftCorner').css('height', height);
    $('#upperLeftCorner').css('width', width);
}
function initSearchForm(){
    // zoekformulier
    $('#searchform').submit(function(){
        MoveToTopOfPage();
        loadSearchResults();
        return false;
    });
    //tagcloud
    $('#tagcloud a').click(function() {
    	$('#txtSearch').val($(this).attr('rel'));
    	MoveToTopOfPage();
    	loadSearchResults();
    	return false;
    });
}

function loadSearchResults(){
    startLoading();
    var strSearchUrl = '/zoek/' + $('#txtSearch').val().replace(/ /g, '%20') + ' #zoekresultaten';
    initAjaxContent();
    $('#ajaxcontent').load(strSearchUrl, function(){
        initSearchResultLinks();
        centerPager();        
        finishLoading();
        expandjaxContent();
    });
}

function initSearchResultLinks(){
    $('.searchresultlink').click(function() {
        startLoading();
        strSearchUrl = $(this).attr('href') + ' #zoekresultaten';
        $('#ajaxcontent').load(strSearchUrl, function() {
            initSearchResultLinks();
            centerPager();    
            finishLoading();
        });
        return false;
    });
    $('#zoekresultaten a.close').click(function() {
        disposeAjaxContent();
    });    
}

function centerPager() {
    var intContainerWidth = 560;
    var intPagerWidth = $('#paging').width();
    var intLeftPostion = Math.round((intContainerWidth - intPagerWidth) / 2);
    $('#paging').css('left', intLeftPostion + 'px');
}

function initAjaxContent(){
    if($('#ajaxcontent').length == 0) $('#contentvlak').prepend('<div id="ajaxcontent"></div>');
}

function expandjaxContent(){
    $('#ajaxcontent').animate( 
        {top: '0px'},
        {
        easing: 'easeOutBounce',
        duration: 1000
        }
    );
}

function disposeAjaxContent(){
    $('#ajaxcontent').animate(
        { top: '-552px' },
        {
            easing: 'easeInCubic',
            duration: 500,
            complete: function() { $('#ajaxcontent').remove(); }
        }
    );
}

function startLoading(){
    $('#contentvlak').prepend('<div id="ajaxloader">loading</div>');
}

function finishLoading(){
    $('#ajaxloader').remove();
}

function MoveToTopOfPage(){
    $('html, body').animate({scrollTop:0}, { easing: 'easeInCubic', duration: 500 });
}

var intInitialHeight;
function initPortfolio() {
    intInitialHeight = $('#portfolio').height();

    $('#toonmeer').click(function() {

        var intCurrentHeight = $('#portfolio').height();
        var intListHeight = $('#portfolio ul').height();
        var intNewHeight;
        var strTekst;

        if (intCurrentHeight < intListHeight) {
            intNewHeight = intListHeight
            strTekst = 'Toon minder';
        } else {
            intNewHeight = intInitialHeight
            strTekst = 'Toon meer';
        }
        $('#portfolio').animate(
            {height: intNewHeight + 'px'},
            500,
            'easeInCubic',
            function() { $('#toonmeer').html(strTekst); }
        );
        return false;
    });
}

function initContact() {
    // init qaptcha slider
    $('.QapTcha').QapTcha();
    
    var intSwitchSpeed = 500;

    $('#tabroutebeschijving').click(function() {
        $('#tabcontact').removeClass('active');
        $('#tabadressen').removeClass('active');
    	$('#tabroutebeschijving').addClass('active');
    	$('#adressen, #contact').fadeOut(intSwitchSpeed, function() {
    		$('#contact_formulier').show();
    		$('#googlemaps').fadeIn(intSwitchSpeed, function() {
    			initGoogleMaps();
    		});
    	});
    	return false;
    });

    $('#tabadressen').click(function() {
        $('#tabcontact').removeClass('active');
        $('#tabroutebeschijving').removeClass('active');
        $('#tabadressen').addClass('active');
        if ($('#directionswindow').height() > 0)
            $('#directionswindow').animate(
                {
                    height: '0px'
                },
                250,
                'easeInCubic',
                function() { }
            );
        $('#googlemaps, #contact').hide();
        $('#adressen').fadeIn(intSwitchSpeed);
        return false;
    });

    $('#tabcontact').click(function() {
       $('#tabroutebeschijving').removeClass('active');
       $('#tabadressen').removeClass('active');
       $('#tabcontact').addClass('active');

       $('#adressen, #googlemaps').hide();
       $('#contact').fadeIn(intSwitchSpeed);
       return false;
    });
    
    $('#toonbeschrijving').click(function(){
       var intHeight = 0
       var strButtonImageUrl;
       
       if($('#directionswindow').height() == 0) {
        intHeight = $('#directions').height() + 10;
        strButtonImageUrl = 'url(/lib/images/bg_button_terug.jpg)'; 
       }else{
        strButtonImageUrl = 'url(/lib/images/bg_button.jpg)';        
       }
      
       $('#directionswindow').animate( 
            {
                height: intHeight + 'px'
            },
            500,
            'easeInCubic',
            function(){
                $('#toonbeschrijving').css('background-image', strButtonImageUrl);  
            }
        );
        return false;
    });

    $('#contact_formulier').submit(function(){
        if($('#contact_formulier').valid())
           overlayDirections(); 
        return false;
    });

    if ($('.googlemaps').length > 0) initGoogleMaps();
}

function initJQueryValidate(){
    jQuery.extend(jQuery.validator.messages, {
        required: "Dit veld is verplicht",
        maxlength: jQuery.format("U kunt niet meer dan {0} karakters invoeren."),
        minlength: jQuery.format("U dient minimaal {0} karakters in te voeren."),
        rangelength: jQuery.format("U dient minimaal {0} en maximaal {1} karakters in te voeren."),
        email: "Een geldig emailadres is verplicht.",
        url: "Een geldig URL is verplicht.",
        date: "Een geldige datum is verplicht.",
        number: "Een geldig getal is verplicht.",
        digits: "Gebruik alleen cijfers.",
        equalTo: "Herhaal de invoer nogmaals.",
        range: jQuery.format("U dient een waarde tussen {0} en {1} in te voeren."),
        max: jQuery.format("U dient een waarde kleiner dan of gelijk aan {0} in te voeren."),
        min: jQuery.format("U dient een waarde groter dan of gelijk aan {0} in te voeren."),
        creditcard: "Een geldig creditcardnummer is verplicht."
    });   
    
    $('form.validate').validate();
}


$(document).ready(function() {
    //Initialiseer hier je scripts
    initJQueryValidate();
    initContentFlash();
    initHyperlinks();
    initNoFlashContainer();
    initSubMenu();
    initNieuwsItems();
    initSearchForm();
    initPortfolio();
    initContact();

    /*
    $.fn.nyroModal.settings.endShowContent = function(elt, settings) {
    initHyperlinks();
    };*/

    $('#upperLeftCorner').find('object').click(function() {
        secondTracker._trackPageview('/virtual/openUpNext');
    });
});
