/**
 * Ajax fix voor page reload
 */
if (document.location.href.search(/#/) != -1) {
    var url = document.location.href.split("#");
    document.location.href  =  url[1];
}

$(document).ready(function(){
    setBehaviour();
    initHistory();
});


function setBehaviour() {
    
    $('a.ajax').click(function () {
        ajax_load(this.href);
        return false;
    });

    $('form.ajax').submit(function () {
        $(this).children(":input").each(function(i, input){
            if($(input).attr('required')) if(!$(input).val()) {
                alert("Veld verplicht '" + $(input).attr('title') + "'");
                return false;
            }
        });
        if ($(this).children('#UPLOAD_IDENTIFIER')){
            var progressId = $(this).children('#UPLOAD_IDENTIFIER').val();
            var progressUrl = $(this).children('#UPLOAD_IDENTIFIER').attr('url');
            progressbar(progressUrl, progressId);
        }
        var hasFile = 0;
        $(this).children('input:file').each( function(i, input){
            if ($(input).val()) hasFile++;
        });
        if (hasFile >0) {
            //$(this).append("<input type='hidden' name='fileform' value='1' />");
            $(this).ajaxSubmit({
                beforeSubmit: function(){
                    $(this).fadeOut();
                    $(this).append('----SENDING----');
                },
                data: {fileform: true},
                success: function(data) {
                    // stukje code om de response te kunnen parsen
                    data = data.replace('<textarea>','');
                    data = data.replace('</textarea>','');
                    data = data.replace(/&lt;/g,'<');
                    data = data.replace(/&gt;/g,'>');
                    data = eval('('+data+')');
                    $.each(data, function(i,div){
                        if (div.id == 'notify') notify(div.message, div.type);
                        else $("#"+div.id).html(div.html);
                    });
                    setBehaviour();
                }
            });
        } else {
            $(this).ajaxSubmit({
                beforeSubmit: function(){
                    $(this).fadeOut();
                    $(this).append('----SENDING----');
                },
                success: function(data) {
                        data = eval('('+data+')');
                        $.each(data, function(i,div){
                            if (div.id == 'notify') notify(div.message, div.type);
                            else $("#"+div.id).html(div.html);
                        });
                        setBehaviour();
                    }
            });
        }
        return false;
    });

   // Initieer datepicker velden
   $('.datepicker').each(function(){
        if (jQuery.datepicker == undefined) {
            includeStyle("/styles/ui.datepicker.css");
            includeScript("/scripts/ui/ui.datepicker.js", function(){
                $('.datepicker').datepicker({dateFormat: 'dd-mm-yy'});
            });
            includeScript("/scripts/ui/i18n/ui.datepicker-nl.js");
        }
        else $('.datepicker').datepicker({dateFormat: 'dd-mm-yy'});
    });

    // Initieer draggable objecten
   $('.draggable').each(function(){
        if (jQuery.draggable == undefined) {
            includeScript("/scripts/ui/ui.draggable.js", function(){
                $('.draggable').draggable({containment: 'parent'});
            });
        }
        else $('.draggable').draggable({containment: 'parent'});
    });
    
    $('img.naar_overzicht').hover(
        function(){
            var pic = $(this);
            src = $(this).attr("src");
            pic.attr({src : src.replace("t_off","t_over")});
        },
        function(){
            var pic = $(this);
            src = $(this).attr("src");
            pic.attr({src : src.replace("t_over","t_off")});
        }
    );
    
    $('.rollover').hover(
        function(){
            var pic = $(this);
            src = $(this).attr("src");
            pic.attr({src : src.replace("_off","_over")});
        },
        function(){
            var pic = $(this);
            src = $(this).attr("src");
            pic.attr({src : src.replace("_over","_off")});
        }
    );

//   $('.slideritem').click(function(){
//        $('.slideritem').removeClass('slideritem_show');
//		$(this).addClass('slideritem_show');
//        var id = $(this).parents('li').attr('id');
//        if (id == undefined) id = 0;
//        else id = id.replace("slider_","");
//        //ajax_load(getUrlDir() + "showslider?nid="+id);
//        //showFlashItem(id,'magazine');
//    })
//
//     $('.more').click(function(){
//         if ($(this).parents('.slideritem').hasClass('slideritem_show')) {
//             $('.slideritem').removeClass('slideritem_show');
//         }
//         else {
//             $('.slideritem').removeClass('slideritem_show');
//             $(this).parents('.slideritem').addClass('slideritem_show');
//         }
//     })
//
//
//    
//     $("#slider_block .scroll_right").click(function(){
//         $('#slider_block #slideritems').scrollTo('+=640px', 1000,  {axis: 'x', easing: 'swing'});
//         //$('#slider').animate({marginLeft: '-=400px'});
//     });
//
//     $("#slider_block .scroll_left").click(function(){
//         $('#slider_block #slideritems').scrollTo('-=640px', 1000, {axis: 'x', easing: 'swing'});
//         //$('#slider').animate({marginLeft: '+=400px'});
//     });

     $("#questions_block .scroll_right").click(function(){
         $('#questions_block #questions').scrollTo('+=684px', 1000,  {axis: 'x', easing: 'swing'});
         //$('#slider').animate({marginLeft: '-=400px'});
     });

     $("#questions_block .scroll_left").click(function(){
         $('#questions_block #questions').scrollTo('-=684px', 1000, {axis: 'x', easing: 'swing'});
         //$('#slider').animate({marginLeft: '+=400px'});
     });

     $("input.checkall").click(function(){
    	 if ($(this).attr("checked")) {
		 	$("input[type=checkbox]").attr("checked","checked");
    	 } else {
 		 	$("input[type=checkbox]").removeAttr("checked");
    	 }
     });
     
}


// Laad een javascript
function includeScript(uri, callback) {
    var script = document.createElement("script");
    script.src = uri;
    script.type = "text/javascript";
    script.language = "javascript";
    if (callback != null) {
        script.onreadystatechange = function() {
            if (script.readyState == "complete") callback();
        };
        script.onload = callback;
    }
    document.getElementsByTagName("head")[0].appendChild(script);
    return false;
}

// Laad een stylesheet
function includeStyle(uri) {
    $("head").append("<link rel='stylesheet' type='text/css' href='" + uri + "' />");
}


// History - AJAX calls
function initHistory() {
    // Start ajax history
    $.history.addListener(historyChange);
}

var historyChange = function(newLocation, historyData) {
   if (newLocation == "")  newLocation = "/";
    else if (oldLocation != newLocation) {
        ajax_load(newLocation);
    }
    oldLocation = newLocation;
}
var oldLocation;


/**
* Laadt een url via ajax
*/
function ajax_load(alink) {
    // Voor back/forward knoppen
    $.history.add(alink, alink);
    $.get(alink, function(data) {
        if (data[0] == '<') document.location = "/"; 
        else {
            data = eval('('+data+')');
            $.each(data, function(i,div){
                if (div.id == 'notify') notify(div.message, div.type);
                if (div.id == 'debug') Debug.write(div.message, div.name);
                else $("#"+div.id).html(div.html);
            });
        }
        // Zet behaviour opnieuw
        setBehaviour();
    });
}


function progressbar(url, barid) {
    var timestamp = new Date().getTime();
    $.get(url, 
        {barid: barid, stamp: timestamp}, 
        function(data) {
            if (!data) return;
            var response;
            eval ("response = " + data);
            if (!response) return;
            var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
            $("#progressbar").progressBar(percentage);
        }
    );
    //setTimeout("progressbar('"+url+"', '"+barid+"')", 3000);

}


var notifier = 0;
function notify(message, type) {
   // $('#notification').remove();
    notifier++;
    $('#content').append("<div id='not" + notifier + "' class='notification'>" + message + "</div>");
    window.setTimeout("$('#not" + notifier + "').fadeOut()", 2000);
}

/* Debug functies */

// We gaan een debug object beginnen
window.Debug = {
    output : null, // Het debug vensters
    div : null,
    output2: null, 

    popup : function () {
        debugWindow = window.open('/index/debug', 'debugWindow', 'width=550px, height=450px, menubar=false');
        window.setTimeout(function() {
                Debug.output2 = debugWindow.$('#debugscreen');
                Debug.output2.html(Debug.output.html());
                },
                1000);
       // this.hide();
    },

    initialize : function () {
        if (!this.output) {
            $('body').append("<div id='debug'>Debug scherm <a onclick='Debug.popup()'>(window)</a><div id='debugscreen'></div></div>");
            this.div    = $('#debug');
            this.output = $('#debugscreen');
        }
    },
    
    write : function (message, label) {
        if (!this.output) this.initialize();
        var dat = new Date;
        dat = dat.toLocaleTimeString();
        this.output.prepend("<fieldset><legend>" + dat + " - " + label + "</legend><pre>" + message + "</pre></fieldset>");
        if (this.output2) this.output2.html(this.output.html());
    },

    hide : function () {
        this.div.fadeOut();
    },
    
    close : function () {
    }
    

}

function showlog(){
    ajax_load("/demo_debug/showlog");
}



