
/**
 * Log relay. I know this is ugly, but is there another possibility to forward
 * a variable number of arguments to another function? Just passing 'arguments'
 * makes the receiving function just get 1 argument (the array of arguments).
 * Just defining a number of args and passing all of them makes the receiving
 * function get 'undefined' for each arg not passed to log(). So... yeah.
 */
function log() {
    try {
        var a = arguments;
        if (a.length == 0)
            return console.log();
        else if (a.length == 1)
            return console.log(a[0]);
        else if (a.length == 2)
            return console.log(a[0], a[1]);
        else if (a.length == 3)
            return console.log(a[0], a[1], a[2]);
        else if (a.length == 4)
            return console.log(a[0], a[1], a[2], a[3]);
        else if (a.length == 5)
            return console.log(a[0], a[1], a[2], a[3], a[4]);
        else if (a.length == 6)
            return console.log(a[0], a[1], a[2], a[3], a[4], a[5]);
        else if (a.length == 7)
            return console.log(a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
        else if (a.length == 8)
            return console.log(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
        else if (a.length == 9)
            return console.log(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
        else
            return console.log(a);
    }
    catch (e) {
        // nop
    }
}


function fadingModalCallbackDialog(args) {
	id = args.id || "mydialog";
	title = args.title || "";
	msg = args.msg || "";
    btn1 = args.btn1 || { title: "Ok", func: function(){}, test: undefined };
    btn2 = args.btn2 || undefined;
    btn3 = args.btn3 || undefined;
    height = args.height || "auto";
    width = args.width || 300;
	
    var d = $("#"+id)
    if (d.length == 0) {
    	/* if the dialog html is not yet there, create it! */
        d_code = '<script src="/static/js/jquery/jquery.form.js" />' +
                 '<div id="' + id + '" title="' + title + '" class="ui-helper-hidden">' +
                 '<form id="' + id + '_form">' + msg + '</form></div>';
        $("body").append(d_code);
        d = $("#"+id);
    }
    
    diagopts = {
         modal: true,
         resizable: false,
         height: height,
         width: width,
         buttons: {
             btn1: function() {
            	 if (btn1.test === undefined || btn1.test()) {
            		 $('.ui-widget-overlay').fadeOut('slow');
            		 $('#'+id).closest(".ui-dialog").fadeOut('slow', function() {
            			 $('#'+id).dialog("close");
            			 btn1.func();
            		 });
            	 }
             }
         },
         autoOpen: false,
         open: function() {
             $('.ui-widget-overlay').hide().fadeIn();
         },
         beforeClose: function() {
             $('.ui-widget-overlay').fadeOut('slow');
             $('#'+id).closest(".ui-dialog").fadeOut('slow');
             return true;
         },
         show: "fade",
     };
    
    if (btn2 != undefined) {
    	$.extend(diagopts.buttons, {
            btn2: function() {
            	if (btn2.test === undefined || btn2.test()) {
            		$('.ui-widget-overlay').fadeOut('slow');
            		$('#'+id).closest(".ui-dialog").fadeOut('slow', function() {
            			$('#'+id).dialog("close");
            			btn2.func();
            		});
            	}
            }
    	});
    }
    
    if (btn3 != undefined) {
    	$.extend(diagopts.buttons, {
            btn3: function() {
            	if (btn3.test === undefined || btn3.test()) {
            		$('.ui-widget-overlay').fadeOut('slow');
            		$('#'+id).closest(".ui-dialog").fadeOut('slow', function() {
            			$('#'+id).dialog("close");
            			btn3.func();
            		});
            	}
            }
    	});
    }
    
    /* fire the dialogue */
    d.dialog(diagopts);
    
    /* hack the wished titles onto the buttons :) */
    btnPane = d.closest(".ui-dialog").find(".ui-dialog-buttonpane");
    
    b = btnPane.find(".ui-button-text").filter(function() {
        return $(this).text() == "btn1";
    });
    b.html(btn1.title);
    
    if (btn2 != undefined) {
    	b = btnPane.find(".ui-button-text").filter(function() {
    		return $(this).text() == "btn2";
    	});
    	b.html(btn2.title);
    }
    
    if (btn3 != undefined) {
    	b = btnPane.find(".ui-button-text").filter(function() {
    		return $(this).text() == "btn3";
    	});
    	b.html(btn3.title);
    }
    
    /* no close X in title bar - force user to use the dialog buttons */
    d.closest(".ui-dialog").find(".ui-dialog-titlebar-close").hide();
    d.dialog("open");
    return d;
}


function makeLogoutDialog(linkId, title, msg, url) {
	lid = linkId || "logoutLink"
    $("#"+lid).click(function() {
	    fadingModalCallbackDialog({
		    id: "logoutdialog",
		    title: title,
		    msg: msg,
            btn1: {
        	    title: "Logout",
        	    func: function() {
                    $('#' + id + '_form').ajaxSubmit({
                        success: function(result) {
                            if (result.success) {
                                window.location.replace("/");
                            }
                            else {
                                alert("Logging out failed");
                            }
                        },
                        dataType: "json",
                        type: "post",
                        url: url
                    });
        	    }
            },
            btn2: {
        	    title: "Cancel",
        	    func: function() {
        	    }
            }              
	    });
    });
}


function alertFancy(msg, title, id, height, width) {
	var title = title || "";
	var id = id || "fancyAlertDiv";
	
    fadingModalCallbackDialog({
	    id: id,
	    title: title,
	    msg: msg,
	    height: height,
	    width: width,
        btn1: {
        	title: "Ok",
    	    func: function() {}
        }
    });
}


/* csrf protection for ajax-sendable forms */
$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});


