//autorun:
$(function() {
    //hover states on the static widgets
    $('a.toggle-filelist, a.filelink, a.largelink, a.iconlink, a.ui-state-default, input.ui-state-default').hover(
        function() {
            $(this).addClass('ui-state-hover');
        },
        function() {
            $(this).removeClass('ui-state-hover');
        }
    );

    $('div.docrow').live('mouseover',
        function() {
            $(this).addClass('docrow-hover');
        });
    $('div.docrow').live('mouseout',
        function() {
            $(this).removeClass('docrow-hover');
        }
    );

    $(".groups_accordion").accordion({
        autoHeight: false
        ,header: 'h2'
        ,collapsible: true
        ,active: true
    });

    $("a.newwindow").each(function() {
        $(this).bind("click",
        function() {
            window.open(this.href);
            return false;
        });
    });
    
    if($('#sendpassword'))
    {
        $('#sendpassword').disable();
        $('#flduser_password').bind("keyup",function(){$('#sendpassword').enable();});
    }
    

    if (document.getElementById("nav"))
    {
        var lis = document.getElementById("nav").getElementsByTagName("LI");
        for (var i = 0; i < lis.length; i++)
        {
            lis[i].onmouseover = function()
            {
                this.className += " iehover";
            }
            lis[i].onmouseout = function()
            {
                this.className = this.className.replace(new RegExp(" iehover\\b"), "");
            }
        }
    }
    
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
    $("#nav li a").click(function(){
        //we just need to attach a click event listener to provoke iPhone/iPod/iPad's hover event
        //strange
    });
}
    
    $('li.finderitem').hover(
        function() {
            $(this).addClass('finderitem-hover');
        },
        function() {
            $(this).removeClass('finderitem-hover');
        }
    );
    
    $('#questions h3').each(function(key, toggle)
    {
        toggle = $(toggle);
        var target = toggle.next();
        
        toggle.hover(function(){
            toggle.addClass('iehover');
          },
          function(){
            toggle.removeClass('iehover');
          }
        );
            
        toggle.click(function(){
            target.toggle('blind');
        });

    });
    
    load_tooltips('.tooltip');
    
});


//get basepath
if (a = document.getElementsByTagName("link")[0])
{
    site_base = a.href.substr(0, a.href.indexOf('/resources'));
}

function popup(url, w, h, scroll)
{
    var l = (screen.width - w) / 2;
    var t = (screen.height - h) / 2;
    window.open(url, '_blank', 'resizable=yes,location=no,menubar=no,scrollbars=' + scroll + ',status=no,toolbar=no,fullscreen=no,dependent=no,width=' + w + ',height=' + h + ',left=' + l + ',top=' + t);
}

function load_tooltips(id, body)
{
    if(!body)
    {
        body = '<br/>';
    }
    $(id).tooltip({track: true
                       ,delay: 0
                       ,showURL: false
                       ,showBody: body
                       ,fade: 250});
}


function get_size_px(el)
{
// only initial unmodified body font-size in FF is in pixels, when set via javascript it's EMs again....
    var size = el.getStyle('font-size');

    if (Browser.Engine.trident == true)
    {
        return convert_em_px(size);
    }
    else
    {
        // check for px
        if (size.test("px"))
        {
            // only on unmodified body value..
            return size.toInt();
        }
        else
        {
            return convert_em_px(size);
        }
    }
}

function convert_em_px(size)
{
    // convert em to px, 16px == default browser font size (1em)
    size = size.toFloat();
    return (size * 16).round();
}



function captchaMp3()
{
    var d = new Date();
    var msie = (navigator.userAgent.toLowerCase().indexOf("msie") > -1) ? true: false;
    if (document.all && msie)
    {
        if (Number(parseFloat(navigator.appVersion.split('MSIE ')[1])) < 7)
        {
            embed = document.createElement("bgsound");
            embed.setAttribute("src", $('playsound') + "&cfsnd=" + d.getTime());
            document.getElementsByTagName("body")[0].appendChild(embed);
            return;
        }
    }
    if (document.getElementById)
    {
        var mp3player = '<embed src="' + $('playsound') + "&cfsnd=" + d.getTime() + '" hidden="true" type="audio/x-mpeg" autostart="true" />';
        $('soundcontainer').set('html', mp3player);
        return;
    }
    return;
}


function reloadValidationImage()
{
    if ($('validationimage'))
    {
        var now = new Date();
        newSrc = $('validationimage').src
        newSrc = (newSrc.indexOf("&") > 0) ? newSrc.substr(0, newSrc.indexOf("&")) : newSrc;
        newSrc += "&" + now.getTime();
        $('validationimage').src = newSrc;
    }
}


//JQUERY OBJECTS
//keep everything compatible, even when other libraries with the $-function are used
jQuery.fn.extend({
    check: function() {
        return this.each(function() {
            this.checked = true;
        });
    },
    uncheck: function() {
        return this.each(function() {
            this.checked = false;
        });
    },
    disable: function() {
        return this.each(function() {
            this.disabled = true;
        });
    },
    enable: function() {
        return this.each(function() {
            this.disabled = false;
        });
    },
    
    when_enabled: function(fn) {
        return this.each(function() {
            if(!$(this).hasClass("ui-state-disabled") && !$(this).hasClass("ui-state-inactive"))
            {
                fn.call(this);
            }
        });
    }
});

 (function($) {

    $.documentList =
    {
        loadDocument: function(map_id, meta_id)
        {
            var info = $('#docinfo_'+meta_id+'_'+map_id);

            if(info.length > 0)
            {
                info.remove();
            }
            else
            {
                $.getJSON(base_url + "/docs/?action=ajax&function=showversions&id="+map_id, function(json, status)
                {
                    $.documentList.onLoadDocument(json,status,meta_id,map_id);
                });
            }
        }
        ,loadDocumentRights: function(map_id,loc)
        {
            var info = $('#docinfo_'+map_id);

            if(info.length > 0)
            {
                info.remove();
            }
            else
            {
                $.getJSON(base_url + "/beheer/rechten/?action=ajax&function=showmeta&id="+map_id+"&loc="+loc, function(json, status)
                {
                    $.documentList.onLoadDocument(json,status,false,map_id);
                });
            }
        }
        ,loadDocuments: function(meta_id,loc)
        {
            var info = $('#docinfo_'+meta_id);

            if(info.length > 0)
            {
                info.remove();
            }
            else
            {
                $.getJSON(base_url + "/beheer/rechten/?action=ajax&function=showmaps&id="+meta_id+"&loc="+loc, function(json, status)
                {
                    $.documentList.onLoadMaps(json,status,false,meta_id);
                });
            }
        }
        ,onLoadDocument: function(json,status, meta, map)
        {
            if(json.html)
            {
                meta = meta === false ? '' : '_' + meta;
                var row = $('#doc'+meta+'_'+map);
                row.after('<div id="docinfo'+meta+'_'+map+'">'+json.html+'</div>');
            }
            load_tooltips('#docinfo'+meta+'_'+map+' .tooltip','<br/>');
        }
        ,onLoadMaps: function(json,status, meta, map)
        {
            if(json.html)
            {
                meta = meta === false ? '' : '_' + meta;
                var row = $('#mdata'+meta+'_'+map);
                row.after('<div id="docinfo'+meta+'_'+map+'">'+json.html+'</div>');
            }
            load_tooltips('#docinfo'+meta+'_'+map+' .tooltip','<br/>');
        }
        ,toggleFiles: function(version_id)
        {
            var files = $('#versionfiles_'+version_id);
            if(files.is(':visible'))
            {
                files.addClass('ui-helper-hidden');
                $('#versionicon_'+version_id).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
            }
            else
            {
                files.removeClass('ui-helper-hidden');
                $('#versionicon_'+version_id).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
            }
        }
        ,onDocumentCheck: function(element)
        {
            var map_id = element.id.substr(element.id.lastIndexOf('_')+1);
            var info = $('#doc_meta_'+map_id);
            if(element.checked)
            {
                info.removeClass('ui-helper-hidden');
            }
            else
            {
                info.addClass('ui-helper-hidden');
            }
        }

    }

 })(jQuery);
 
(function($) {
    $.checkAll = {
        check : function(element)
        {
            var name = element.name;
            var checked = element.checked;

            if(!checked)
            {
                $('input[name='+name+']').uncheck();
            }
            else
            {
                $('input[name='+name+']').check();
            }
        }
        ,checkByClass: function(element,className)
        {
            var i = $('input.'+className+':enabled');
            if(!element.checked)
            {
                i.uncheck();
            }
            else
            {
                i.check();
            }
            
            i.each(function(key,val){
               $(val).triggerHandler('click'); 
            });
        }
    }

})(jQuery);
//Status message system
 (function($) {

    //message tool
    $.messageBox =
    {
        showSuccessMessage: function(message)
        {
            var box = $("#message");
            box.empty();
            var div = $("<div class='msg_success'>" + message + "</div>").hide();
            box.append(div);
            div.fadeIn("slow");
        },

        showErrorMessage: function(message)
        {
            var box = $("#message");
            box.empty();
            var div = $("<div class='msg_warning'>" + message + "</div>").hide();
            box.append(div);
            div.fadeIn("slow");
        }

    }
})(jQuery);

//jQuery Metadata plugin
 (function($) {

    $.extend({
        metadata: {
            defaults: {
                type: 'class',
                name: 'metadata',
                cre: /({.*})/,
                single: 'metadata'
            },
            setType: function(type, name) {
                this.defaults.type = type;
                this.defaults.name = name;
            },
            get: function(elem, opts) {
                var settings = $.extend({},
                this.defaults, opts);
                // check for empty string in single property
                if (!settings.single.length) settings.single = 'metadata';

                var data = $.data(elem, settings.single);
                // returned cached data if it already exists
                if (data) return data;

                data = "{}";

                if (settings.type == "class") {
                    var m = settings.cre.exec(elem.className);
                    if (m)
                    data = m[1];
                } else if (settings.type == "elem") {
                    if (!elem.getElementsByTagName)
                    return undefined;
                    var e = elem.getElementsByTagName(settings.name);
                    if (e.length)
                    data = $.trim(e[0].innerHTML);
                } else if (elem.getAttribute != undefined) {
                    var attr = elem.getAttribute(settings.name);
                    if (attr)
                    data = attr;
                }
                if (data.indexOf('{') < 0)
                data = "{" + data + "}";

                data = eval("(" + data + ")");

                $.data(elem, settings.single, data);
                return data;
            }
        }
    });

    $.fn.metadata = function(opts) {
        return $.metadata.get(this[0], opts);
    };

})(jQuery);

//ConfirmDialog
 (function($) {
    $.uiConfirm = function(o) {
        o = $.verifyOptions(o, {
            message: 'string',
            confirmed: 'function',
            cancelled: 'function',
            complete: 'function',
            modal: 'boolean',
            overlay: 'object',
            bgiframe: 'boolean',
            ok_text: 'string',
            cancel_text: 'string',
            title: 'string'
        },
        {
            message: 'Weet u het zeker?',
            title: "Bevestiging",
            confirmed: function() {},
            cancelled: function() {},
            complete: function() {},
            modal: true,
            overlay: {
                opacity: 0.5,
                background: 'black'
            },
            bgiframe: true,
            ok_text: 'Ja',
            cancel_text: 'Annuleren'
        });

        var div = $('<div />').text(o.message).attr('title', o.title);
        var scope = this;

        var buttons = {};
        buttons[o.ok_text] = function() {
            div.dialog('close').remove();
            o.confirmed.call(scope);
            o.complete.call(scope);
        };
        buttons[o.cancel_text] = function() {
            div.dialog('close').remove();
            o.cancelled.call(scope);
            o.complete.call(scope);
        };

        var dialogOpts = $.extend({},
        o, {
            autoOpen: true,
            draggable: false,
            resizable: false,
            buttons: buttons
        });

        div.dialog(dialogOpts).closest('.ui-dialog');
    };
})(jQuery);

 (function($) {
    $.verifyOptions = function(options, required, defaults) {
        options = $.extend(defaults || {},
        options || {});
        $.each(required || {},
        function(name, type) {
            if (options[name] == null) throw "Missing required option '" + name + "'";
            if (typeof options[name] != type) throw "Type of option '" + name + "' is not " + type;
        });
        return options;
    };
})(jQuery);

//Alert
 (function($) {
    $.alert = function(message, element)
    {
        
        $.uiConfirm({
            message:    message
           ,title:      'Let op!'
           ,confirmed:  function() 
           {
                var href = $(element).attr('href');
                if(href)
                    window.location = href;
                else
                {
                    //false
                }
           } 
        });
        return false;
    }
})(jQuery);

//Input Field Controls
 (function($) {
    $.increaseInput = function(id,value,min,max,callback)
    {
        var el = $("#"+id);
        var num = isNaN(el.val()) ? 10 : parseInt(el.val());
        var oldnum = num;
        num = num + value;
        var newnum = 0;
        if(num <= max && num >= min)
        {
            el.val(num);
            newnum = num;
        }
        else
        {
            if(num > max)
            {
                el.val(max);
                newnum = max;
            }
            else
            {
                el.val(min);
                newnum = min;
            }     
        }
        if(callback && oldnum != newnum)
        {
            callback(id, newnum);
        }
    };
    
    $.toggleInputs = function(selector, element)
    {
        var list  = $(selector);
        var count = list.size();
        if($(selector+":checked").size() == count)
        {
            list.uncheck();
            $(element).text("Selecteer alle items");
        }
        else
        {
            list.check();
            $(element).text("Deselecteer alle items");
        }
    };
    
    $.updateLink = function(id, selector)
    {
        var el = $("#"+id);
        var list  = $(selector);
        var count = list.size();
        if($(selector+":checked").size() == count)
        {
            el.text("Deselecteer alle items");
        }
        else
        {
            el.text("Selecteer alle items");
        }
        
    };
})(jQuery);

//Formfiller
 (function($) {
    //message tool
    $.formFiller =
    {
        fill: function(element, prefix)
        {
            var option = $(element.options[element.selectedIndex]);
            var arr = $.parseJSON(option.val());
            $.each(arr,function(key,val){
               $("#"+prefix+key).val(val);
            });
        }
    }
})(jQuery);

//Formfiller
 (function($) {
    //message tool
    $.cartManager =
    {
        drukkerijDialog: false
        ,addToCart: function(type, id, cartname)
        {
            $.cartManager.onAddDialogComplete(cartname, {'type':type, 'item_id':id, 'dcount':0});            
        }
        ,onAddDialogComplete: function(cartname, params)
        {
            var action = "function=addtocart&cartname="+cartname+"&"+$.param(params);
            
            $.getJSON(base_url + "/orders/ajax/?" + action,
            function(json, status) {
                $.cartManager.onAddComplete(json, status);
            });
        }
        ,onAddComplete: function(json, status)
        {
            if (json.status == "success")
            {
                $.messageBox.showSuccessMessage(json.message);
                $.each(json.html,function(key,val){
                    $("#"+key+"cart_content").html(val);
                });
                $("#cart_download_button").removeClass("ui-state-inactive").addClass("ui-state-default");
                $("#cart_empty_button").removeClass("ui-state-inactive").addClass("ui-state-error");
            }
            else
            {
                $.messageBox.showErrorMessage(json.message);
            }
            if(json.debug)
            {
                $.log(json.debug);
            }
        }
        ,emptySidebarCart : function()
        {
            $.uiConfirm({
                message: "Weet u zeker dat u uw winkelwagen leeg wilt maken?"
                ,title: "Let op!"
                ,confirmed: function()
                {
                    var action = "function=emptycart"
                    $.getJSON(base_url + "/orders/ajax/?" + action,
                        function(json, status) 
                        {
                            $.cartManager.onDeleteComplete(json, status, $("div.cartcontent div.cartitem"));
                        }
                    );
                }
            });
            
        }
        ,deleteFromSidebarCart : function(type, id, cartname)
        {
            var action = "function=deletefromcart&type="+type+"&item_id=" + id + "&cartname=" + cartname;
            $.getJSON(base_url + "/orders/ajax/?" + action,
                function(json, status) 
                {
                    $.cartManager.onDeleteComplete(json, status, $("#ir_"+cartname+"_"+type+"_"+id));
                }
            );
        }
        ,openDrukkerijDialog : function(map_id, download_type, download_id, target)
        {
            $.cartManager.drukkerijDialog = $('#drukkerijDialog').dialog({
                bgiframe: true,
                autoOpen: false,
                height: 450,
                width: 450,
                buttons: {
                    'Voeg Toe': function() {
                        var dcount = 0;
                        var scount = 0;
                        var cartname = "download";
                        var type = download_type;
                        var id = download_id;
                        if($("#drukkerij_selector_true").attr('checked'))
                        {
                            cartname = "drukker";
                            id = map_id;
                            type = "map";
                            var n = $("#drukkerij_aantal_deelnemer").val();
                            if($("#student_form").is(':visible') && !isNaN(n) && parseInt(n) >= 1 && parseInt(n) <= 100)
                            {
                                dcount = n;
                            }
                            var s = $("#drukkerij_aantal_begeleider").val();
                            if($("#coach_form").is(':visible') && !isNaN(s) && parseInt(s) >= 1 && parseInt(s) <= 100)
                            {
                                scount = s;
                            }
                        }
                        $.cartManager.onAddDialogComplete(cartname,{'type': type, 'item_id': id, 'dcount': dcount, 'scount': scount});
                        $.cartManager.drukkerijDialog.dialog('close');
                    }
                    ,'Annuleren': function() {
                        $.cartManager.drukkerijDialog.dialog('close');
                    }
                },
                close: function()
                {
                    $.cartManager.drukkerijDialog.dialog('destroy');
                },
                modal: true
            });
            //Reset radio-knoppen
            $("#drukkerij_selector_false").attr('checked',true);
            $("#drukkerij_false").show();
            $("#drukkerij_true").hide();
            //Activeer radio-knoppen
            $("#drukkerijDialog input.selector").click(function() {
                var selected = this.value;
                $("#drukkerijDialog div.selector_container").each(function() {
                    var el = $(this);
                    if(this.id == selected)
                    {
                        if(el.is(":hidden"))
                            el.show();
                    }
                    else
                    {
                        if(el.is(":visible"))
                            el.hide();
                    }
                });
            });
            //hide or display form items
            if(target == 'all')
            {
                $("#coach_form, #student_form").show();
            }
            else if(target == 'student')
            {
                $("#coach_form").hide();
                $("#student_form").show();
            }
            else if(target == 'coach')
            {
                $("#coach_form").show();
                $("#student_form").hide();
            }
            $.cartManager.drukkerijDialog.dialog('open');
        }
        ,deleteItem: function(type, id, cartname, element)
        {
            var action = "function=deletefromcart&type="+type+"&item_id=" + id + "&cartname=" + cartname;
            $.getJSON(base_url + "/orders/ajax/?" + action,
                function(json, status) 
                {
                    $.cartManager.onDeleteComplete(json, status, element);
                }
            );
        }
        ,deleteSelected: function(selected)
        {
            var json = [];
            selected.each(function(i){
                var split = this.value.split("_");
                json[i] = {'cartname' : split[1]
                         ,'type' : split[2]
                         ,'id' : split[3]};
            });
            var action = "function=deleteselectedfromcart";
            $.getJSON(base_url + "/orders/ajax/?" + action, {'json' : $.toJSON(json)},
                function(json, status) 
                {
                    $.cartManager.onDeleteComplete(json, status, selected.parents("div.cartitem"));
                }
            );
            
        }
        ,updateCounter: function(newValue, cartname, type, id)
        {
            newValue = parseInt(newValue);
            if(newValue != NaN)
            {
                var action = "function=updateitemcount&type="+type+"&item_id=" + id + "&cartname=" + cartname + "&dcount="+newValue;
                $.getJSON(base_url + "/orders/ajax/?" + action,
                    function(json, status) 
                    {
                        $.cartManager.onUpdateComplete(json, status);
                    }
                );
            }
        }
        ,updateSupervisorCounter: function(newValue, cartname, type, id)
        {
            newValue = parseInt(newValue);
            if(newValue != NaN)
            {
                var action = "function=updateitemsupervisorcount&type="+type+"&item_id=" + id + "&cartname=" + cartname + "&scount="+newValue;
                $.getJSON(base_url + "/orders/ajax/?" + action,
                    function(json, status) 
                    {
                        $.cartManager.onUpdateComplete(json, status);
                    }
                );
            }
        }
        ,onDeleteComplete: function(json, status, element)
        {
            if (json.status == "success")
            {
                $.messageBox.showSuccessMessage(json.message);
                var total = 0;
                element.fadeOut("slow",function()
                {
                    $(this).remove();    
                    $("div.cartcontent").each(function()
                    {
                        var cnt = $(this).find("div.cartitem, div.empty").size();
                        var addr_cnt = $(this).find("div.address_box").size();
                        total += (cnt - addr_cnt);
                        if(cnt - addr_cnt == 0)
                        {
                           $(this).hide().append("<div class='empty'>Er zitten momenteel geen "+_words.maps+" in deze lijst.</div>");
                           $(this).find("div.address_box").remove();
                           $(this).fadeIn();
                        }
                    });
                });
                
                if(total == 0)
                {
                    $("#cart_order_button, #cart_download_button, #cart_empty_button").removeClass("ui-state-default").removeClass("ui-state-error").addClass("ui-state-inactive");
                }
            }
            else
            {
                $.messageBox.showErrorMessage(json.message);
            }
        }
        ,onUpdateComplete: function(json, status)
        {
            if (json.status == "success")
            {
                $.messageBox.showSuccessMessage(json.message);
            }
            else
                $.messageBox.showErrorMessage(json.message);
        }
        ,onIncrease: function(id, newValue)
        {
            var vals = id.split('_');
            $.cartManager.updateCounter(newValue,vals[2],vals[3],vals[4]);
        }
    }
})(jQuery);
