if(typeof EUNIT == "undefined"){
    var EUNIT = {};
}

if(typeof EUNIT.ui == "undefined"){
    EUNIT.ui = {};
}

//Create a modal dialog with callbacks for OK and cancel
EUNIT.ui.modaldialog = function(divid, oktext, canceltext,
        okcallback, cancelcallback){
    
    buttons = {};
    buttons[oktext]=function() {
			$(this).dialog('close');
			if(okcallback){
			    okcallback();
			}
		};
	buttons[canceltext] = function() {
			$(this).dialog('close');
			if(cancelcallback){
			    cancelcallback();
			}
		};
            
    $("#"+divid).dialog({
		bgiframe: true,
		resizable: false,
		draggable: false,
		height:180,
		modal: true,
		autoOpen:false,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: buttons
	});    
};

EUNIT.ui.twitterWidget = function(account, numtweets, id){
    var cont = $('#'+id+' .tweets');
    cont.empty();
    cont.append($.DIV({Class:'loading'}));
    
    $.jTwitter(account, numtweets, function(userdata){
        cont.empty();
        for(var i in userdata){
            var data = userdata[i];
            var date = new Date();
            date.setTime(Date.parse(data['created_at']));
        
            var t = $.DIV({Class: 'tweet'},
                $.DIV({Class: 'date'}, date.toLocaleString()),
                $.SPAN({Class:'msg'}));
        
            //take any @name's and turn them into a twitter url!
            var mre = /@\w+/;
            var txt=data['text'];
            var txt = txt.replace(mre, function(match){
                return '<a href="http://twitter.com/'+
                    match.slice(1)+
                    '">'+
                    match+
                    '</a>';
            });
            $(t).children(".msg").html($.link(txt));
        
            cont.append(t);
        }
    });                    
};


EUNIT.ui.buttons = {
    hoverOver: function(){
        $(this).addClass("ui-state-hover"); 
    },
    
    hoverOut: function(){
        $(this).removeClass("ui-state-hover"); 
    },
    
    mouseDown: function(){
		$(this).parents('.eubuttonset-single:first').find(".eubutton.ui-state-active").removeClass("ui-state-active");
		if( $(this).is('.ui-state-active.eubutton-toggleable, .eubuttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
		else { $(this).addClass("ui-state-active"); }	        
    },
    
    mouseUp: function(){
        if(! $(this).is('.eubutton-toggleable, .eubuttonset-single .eubutton,  .eubuttonset-multi .eubutton') ){
			$(this).removeClass("ui-state-active");
		}
    },
    
    applyCallbacks: function(){
        $(this).hover(EUNIT.ui.buttons.hoverOver, EUNIT.ui.buttons.hoverOut)
            .mousedown(EUNIT.ui.buttons.mouseDown)
            .mouseup(EUNIT.ui.buttons.mouseUp);
        
    }
};

$(function(){
	//all hover and click logic for buttons on load
	$(".eubutton").each(EUNIT.ui.buttons.applyCallbacks);
});

//AJAX Dialog class, wraps a dom in a jquery UI dialog with OK/Cancel buttons
//that submit the form to an AJAX url for checking/submission
EUNIT.ui.AJAXFormDialog = {
    
    init: function($dialogdiv, isettings){
        var that = this;
        if (isettings == undefined) isettings = {};
        var settings = {
            oktext              : "OK",
            okurl               : null,
            canceltext          : "Cancel",
            width               : 600,
            height              : 600,
            title               : "title",
            postsubmitcallback  : null,
            cancelcallback      : null,
            opencallback        : null
        };
        jQuery.extend(settings, isettings);


        function display_errors(msg, errors){
            $dialogdiv.find("span.actionmessage").append(
                "<span class='ajaxform_error'>" + msg + "</span>");

            if(errors === undefined) return;
            jQuery.each(errors, function(key, msg){
                $dialogdiv.find("[name="+key+"]").after(
                        '<span class="ajaxform_error">'+msg+"</span>");
            });
        }

        //function called just before data is submitted to the server
        function presubmit(formData, jqForm, options){
            // $submit_button.attr("disabled", "true");
            // $submit_button.after("<div class='ajaxform_spinny' />");
            $(".ajaxform_msg").remove();
            $(".ajaxform_error").remove();
            return true;
        }

        //called when the data is returned from the server.
        function postsubmit(response, statusText){
            // $submit_button.removeAttr("disabled");
            // $(".ajaxform_spinny").remove();

            if(response['error_msg'] === undefined){
                $dialogdiv.dialog('close');
                
                if (settings.postsubmitcallback){
                    settings.postsubmitcallback();
                }
                
            }else{
                display_errors(response['error_msg'], response['error_val']);
            }
        }

        function okcallback(){
            
            $dialogdiv.find("form").ajaxSubmit({
                beforeSubmit   : presubmit,
                success        : postsubmit,
                url            : settings.okurl,
                dataType       : "json",
                iframe         : true
            });
        }

        function cancelcallback(){
            var closed = true;
            if(settings.cancelcallback){
                closed = settings.cancelcallback();
            }
            if(closed){
                $(this).dialog('close');
            }
        }

        buttons = {};
        if(settings.oktext){
            buttons[settings.oktext] = okcallback;
        }
        if(settings.canceltext){
            buttons[settings.canceltext] = cancelcallback;
        }

        var dialogsettings = {
            bgiframe: true,
    		autoOpen: false,
    		width: settings.width,
    		height: settings.height,
    		modal: true,
    		title: settings.title,
    		buttons: buttons,
    		open: settings.opencallback
    	};



        $dialogdiv.dialog(dialogsettings);     

    },
    
    //fil a dialog with data from dataset. fieldsmap maps from the form
    // input id's to the datasets keys with an options mapping function
    //
    // var fieldsmap = {
    //    form_itemid: ['itemid', transformFunc]
    //}
    //
    // transformFunc is passed the data and the JQuery wrapped input DOM
    // element. If it returns null then the inputs value will not be set.
    
    fill: function($dialog, fieldsmap, dataset){
                
        $.each(fieldsmap, function(inputname, d){
            var data = dataset[d[0]];
            var func = d[1];
            var $input = $dialog.find("#"+inputname);
            
            if(func){
                data = func(data, $input);
            }
            if(data == null){
                return;
            }
            
            if($input.attr("type") == "checkbox"){
                if(data){
                    $input.attr("checked", "checked");
                }else{
                    $input.removeAttr("checked");
                }
            }else{
                $input.val(data);
            }
        });
    },
    
    clean: function($dialog){
        //clear any errors that might have been
        $dialog.find(":input").val("");
        $dialog.find(".ajaxform_msg").remove();
        $dialog.find(".ajaxform_error").remove();
    }
};