/**
 * 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();
});

var thema = '';

function loadTheme(changetheme){
    if (changetheme != thema) ajax_load('/thema/'+changetheme);
    //alert(changetheme +' | ' +thema);
}

function setBehaviour() {

    $('.newscontainer').width(($('#news li').size()*154)+2);
    $('.questioncontainer').width($('#questionlist li').size()*172);

    $('div').unbind('click');
    $('span').unbind('click');

    thema = document.location.href;
    if (thema.search('#') > -1) {
        thema = thema.split('#');
        thema  =  thema[1];
    }
    thema = thema.replace('http://', '');
    thema = thema.split('/');
    thema = thema[2];
    $('body').attr('class', thema);
    
    $('.newsitem').click(function(){
        $('.newsitem').removeClass('newsitem_show');
        $(this).addClass('newsitem_show');
        var id = $(this).parents('li').attr('id');
        if (id == undefined) id = 0;
        else id = id.replace("news_","");
        //ajax_load(getUrlDir() + "shownews?nid="+id);
        showFlashItem(id,'magazine');
    }) 

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

    $('a.popup').click(function () {
        var popup = window.open(this.href, "popup", "width=450px, height=550px, scrollbars=1");
        return false;
    });


    $('a.colofon').click(function () {
        var popup = window.open(this.href, "popup", "width=500px, height=600px, scrollbars=1");
        return false;
    });
    
    $('.login_button').click(function () {
        $('#login').remove();
        $('#content').append('<div id="login"></div>');
        ajax_load("/inzending/"+thema+"/login");
        scroll(0,0);
        return false;
    });

    $('.login_link').click(function () {
        $('#logindiv').remove();
        $('#content').append('<div id="logindiv" class="popup"></div>');
        ajax_load("/thema/"+thema+"/login");
        scroll(0,0);
        return false;
    });
    $('a.ajax_confirm').click(function () {
        var text = $(this).attr('confirm');
        if (text == undefined) text = "Wilt u deze actie echt uitvoeren?";
        if (confirm(text)) ajax_load(this.href);
        return false;
    });
    
    $('form.ajax').unbind('submit');
    $('form.ajax').submit(function(){
		var formError = false;
    	$(this).find(":input").each(function(i, input){
    		 $(this).removeClass("input_error");
             if($(this).attr('required')) {
            	if(!$(this).val()) {
            		var title = $(this).attr('title') ? $(this).attr('title') : $(this).attr('name'); 
	                notify("Veld verplicht '" + title + "'");
	                $(this).addClass("input_error");
	                formError = true;
            	}
            	// Checkboxes
                if($(this).attr('type') == "checkbox" &! $(this).attr('checked')) {
         			var title = $(this).attr('title') ? $(this).attr('title') : $(this).attr('name'); 
         			notify("Veld verplicht '" + title + "'");
	                $(this).addClass("input_error");
                    formError = true;
                }
            }
            // Uploads: zet extenties met punt in accept attibute, comma separated
            if($(this).attr('accept')){
                var accept = $(this).attr('accept').toLowerCase();
                var filename = $(this).val().toLowerCase();
                var ext = filename.substr(filename.length-4, 4);
                if (accept.indexOf(ext) == -1){
                    formError = true;
         			notify("Alleen bestandstype '" + accept + "'");
	                $(this).addClass("input_error");
                }
            }
    	});
    	
    	if (formError) {
    		scroll(0,0);
    		return false;
    	}
        var hasFile = false;
        var files = $('input:file', this).fieldValue();
        for (var j=0; j < files.length; j++) if (files[j]) hasFile = true;
        if (hasFile) {
            $(this).ajaxSubmit({
                data: {fileform: true},
                success: function(data) {
                    // stukje lelijke code om de response te kunenn parsen
                    data = data.replace('<textarea>','');
                    data = data.replace('</textarea>','');
                    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({
                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;
    });

    $('form.ajax2').submit(function () {
        ajax_form(this);
        return false;
    });

    if (typeof adminBehaviour=="function") adminBehaviour();

    $('.more').hover(
        function(){$(this).addClass('more_on')},
        function(){$(this).removeClass('more_on')}
    );

    $('.more').click(function(){
        if ($(this).parents('.newsitem').hasClass('newsitem_show')) {
            $('.newsitem').removeClass('newsitem_show');
        }
        else {
            $('.newsitem').removeClass('newsitem_show');
            $(this).parents('.newsitem').addClass('newsitem_show');
        }
    })
    
    $('div.doemee img.actief').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")});
        }
    );
    
    $('div.doemee img.nietactief').hover(
        function(){
            var pic = $(this);
            src = $(this).attr("src");
            pic.attr({src : src.replace("inactief","over")});
        },
        function(){
            var pic = $(this);
            src = $(this).attr("src");
            pic.attr({src : src.replace("over","inactief")});
        }
    );

    $(".scroll_right").unbind('click');
    $(".scroll_left").unbind('click');
    
    $("#news_block .scroll_right").click(function(){
        $('#news_block #newsitems').scrollTo('+=614px', 1000,  {axis: 'x', easing: 'swing'});
        //$('#news').animate({marginLeft: '-=400px'});
    });

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

    $("#questions_block .scroll_left").click(function(){
        $('#questions_block #questions').scrollTo('-=684px', 1000, {axis: 'x', easing: 'swing'});
        //$('#news').animate({marginLeft: '+=400px'});
    });
    
    $("input[type=file]").each(function(){
        if ($(this).width() != 217) {
            $(this).filestyle({
                image: "/images/formulier/bladeren.png",
                imageheight : 23,
                imagewidth : 82,
                width : 217
            });
        }
    });
    
    $("a.textedit").toggle(
    function () {
        $("div.textedit").css({"display":"none", "color":"red"});
        $("div.textview").css({"display":"block", "color":"blue"});
    },
    function () {
        $("div.textedit").css({"display":"block", "color":"blue"});
        $("div.textview").css({"display":"none", "color":"red"});
    });
    
   // 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'});
    });
}


// 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 = "/";
            $('html').html(data);
        }
        else {
            data = eval('('+data+')');
            $.each(data, function(i,div){
                if (div.id == 'notify') notify(div.message, div.type);
                else $("#"+div.id).html(div.html);
            });
        }
        // Zet behaviour opnieuw
        setBehaviour();
    });
}


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);
}


function getUrlDir() {
    var url = document.location.href.split("#");
    if (url[1]) url = url[1].substr(0, url[1].lastIndexOf("/"))  + "/";
    else url = url[0].substr(0, url[0].lastIndexOf("/"))  + "/";
    return url;
}



