if (typeof(SFX) == "undefined") {
    var SFX = {}; //load the SFX var if we don't already have one.
}

SFX.tracker_mod = function () {
	var ARTIFACT_STATUS_OPEN = 1;
	var ARTIFACT_STATUS_CLOSED = 2;
	var ARTIFACT_STATUS_DELETED = 3;
	var ARTIFACT_STATUS_PENDING = 4;

    var modal_stack = [];
    var top_level_dirty = false;
    var saved_data;
    var comment_interval;
    var checking_for_new_comments = false;
    var atid;
    var artifact_id;
    var group_id;

    return {
        'modal_box': function (a_href) {
	    jQuery.facebox.loading();
            jQuery.ajax({url: a_href.href + "&modal=1", success:SFX.tracker_mod.modal_ajax_load_success, failure: SFX.tracker_mod.modal_ajax_load_failure, cache: false});
	    modal_stack.push(a_href);
	    return false;
        },
        'set_settings': function(incoming_atid, incoming_artifact_id, incoming_group_id){
            atid = incoming_atid;
            artifact_id = incoming_artifact_id;
            group_id = incoming_group_id;
        },
        'status_display': function (options) {
            if (options) {
                for (var item in options) {
                    if (item == "html") {
                        jQuery('#tracker_mod_status_div').html(options[item]);
                    }
                    else if (item == "fadeOut") {
                        jQuery('#tracker_mod_status_div').fadeOut(options[item]);
                    }
                    else {
                        jQuery('#tracker_mod_status_div').css(item, options[item]);
                    }
                }
            }
        },
        'close_comments_display': function () {
            var statusVal = jQuery('#main-form form select[name="status_id"]').attr('value');
            if (statusVal ==  ARTIFACT_STATUS_CLOSED ||  statusVal ==  ARTIFACT_STATUS_DELETED) {
	            jQuery('#close_comments').show();
				jQuery('#close_comments input[type="checkbox"]').attr('checked', true);
						;
            } else {
	            jQuery('#close_comments').hide();
            }
        },

        'modal_ajax_load_success': function(data, textStatus) {
            jQuery("#top_feedback").hide();
            if (jQuery.browser.msie && jQuery.browser.version == '6.0') {
                jQuery("#main-form select").each(function(i) {
                    jQuery(this).hide();
                });
            }

            jQuery.facebox(data);
            jQuery("#facebox .content .yui-g").removeClass("yui-g").css('height', '1%');

            // only load the content in the facebox if it is a tracker/admin link
            jQuery("#facebox .content a").each(function() {
                if (this.href.match(/tracker\/admin/)) {
                    jQuery(this).click(function() {
                        return SFX.tracker_mod.modal_box(this);
				  });
                }
            });

            jQuery("#facebox .content p").css('margin-left', '0');
            jQuery("#facebox .content form").submit(function() {
                return SFX.tracker_mod.modal_submit(this);
            });
            if (modal_stack.length > 1) {
                jQuery("#facebox .footer").prepend("<a class='facebox_back_button leftarw' href='#' onclick='return SFX.tracker_mod.modal_back();'>Back</a> &nbsp; ");
            }
            else {
                jQuery("#facebox .footer .facebox_back_button").remove();
            }
            return true;
        },

	'modal_submit': function(form) {
                    var form_data = jQuery(form).serializeArray();
                    jQuery.facebox.loading();
                    form_data.push({name: 'post_changes', value: 'Submit'});
                    jQuery.ajax({url: form.action, type: 'POST', data: form_data, success: SFX.tracker_mod.modal_submit_success, failure: SFX.tracker_mod.modal_submit_failure, cache: false});
                    return false;
                },

	'modal_submit_success': function(data, textStatus) {
                    if (modal_stack.length > 1) {
                        modal_stack.pop()
                    }
                    if (modal_stack.length != 0) {
                        SFX.tracker_mod.modal_box(modal_stack.pop());
                    }
                    top_level_dirty = true;

                },

        'toplevel_reload': function() {
                    if (top_level_dirty) {
                        SFX.tracker_mod.status_display({display: 'block', 'background-color': 'blue', html: 'Loading...', 'z-index': '100'});
                        if (jQuery.browser.msie && jQuery.browser.version == '6.0') {
                            jQuery("#main-form select").each(function(i) {
                                jQuery(this).show();
                            });
                        }

                        jQuery.ajax({url: document.location.href + "&modal=1", success:SFX.tracker_mod.toplevel_reload_success, failure: SFX.tracker_mod.toplevel_reload_failure, cache: false});
                    }
        },

        'toplevel_reload_success': function(data, textStatus) {
                    SFX.tracker_mod.status_display({display: 'none'});
                    jQuery("#main-form").replaceWith(data);
        },

        'toplevel_reload_failure': function(request, textStatus, errorThrown) {
                    SFX.tracker_mod.status_display({display: 'block', 'background-color': 'red', html: 'Error'});
        },

        'check_for_new_comments': function() {
                    var last_comment_adddate;
                    if (checking_for_new_comments == false) {
                        checking_for_new_comments = true;
                    }
                    else {
                        return false;
                    }

                    if (jQuery('.artifact_comment:first input[type="hidden"]:first').length > 0) {
                        last_comment_adddate = jQuery('.artifact_comment:first input[type="hidden"]:first').attr('value');
                    }
                    else {
                        last_comment_adddate = 0;
                    }

                    var get_data = {"func": "get_messages_since_last_update", "artifact_id": artifact_id, "atid": atid,
                        "group_id": group_id, "last_comment_adddate": last_comment_adddate};

                    jQuery.ajax({url: '/tracker/index.php', data: get_data, type: 'GET', success: SFX.tracker_mod.check_for_new_comments_success,
                        failure: SFX.tracker_mod.check_for_new_comments_failure, cache: false});
        },


        'check_for_new_comments_success': function(data, textStatus) {
                    checking_for_new_comments = false;
                    if (jQuery.trim(data) != "") {
                        jQuery("#comment_table_container").show();
                        jQuery("#no_comments_message").hide();
                        jQuery(".comments tbody").prepend(data);
                        var comment_number = jQuery(".artifact_comment").length;
                        var titlebar_text = "Comment" + (comment_number == 1 ? '' : 's') + " " + (comment_number == 0 ? "" : "( " + comment_number + " )");
                        jQuery("#commentbar").text(titlebar_text);

						jQuery('.comment_unhide').unbind();
						jQuery('.comment_hide').unbind();
						jQuery('.comment_unhide').click(function () { SFX.tracker_mod.comment_unhide(this); return(false); });
						jQuery('.comment_hide').click(function () { SFX.tracker_mod.comment_hide(this); return(false); });
                    }
        },

        'check_for_new_comments_failure':
	    function(request, textStatus, errorThrown) {
		checking_for_new_comments = false;
            },

        'comment_submit': function(form) {
                    var form_data = jQuery(form).serializeArray();
                    jQuery("form.commentbox input").attr("disabled", "disabled");
                    jQuery("form.commentbox textarea").attr("disabled", "disabled");
                    form_data.push({name: 'post_changes', value: 'Submit'});
                    jQuery.ajax({url: "/tracker/index.php", type: 'POST', data: form_data, success: SFX.tracker_mod.comment_submit_success, failure: SFX.tracker_mod.comment_submit_failure, cache: false});
                    return false;
        },
        'comment_submit_success': function(data, textStatus) {
                    jQuery("#comment_ajax_feedback").html(jQuery(data).find('#top_feedback'));
                    jQuery('.monitorspan').html('');
                    jQuery('#tracker_monitor_submit').attr('value','Un-monitor');
                    jQuery("form.commentbox input").removeAttr("disabled");
                    jQuery("form.commentbox textarea").removeAttr("disabled");
                    jQuery("form.commentbox textarea").each(function() {
                        this.value = "";
                    });
                    SFX.tracker_mod.check_for_new_comments();
        },
        'comment_submit_failure': function(request, textStatus, errorThrown) {
                    jQuery("#comment_ajax_feedback").html(jQuery(data).find('#top_feedback'));
                    jQuery("form.commentbox input").removeAttr("disabled");
                    jQuery("form.commentbox textarea").removeAttr("disabled");
        },

		'comment_pulse': function(id)
		{
			if(jQuery(id).hasClass('pulsate'))
			{
				jQuery(id).fadeTo(1000, 0.1);
				jQuery(id).fadeTo(1000, 1, function () { SFX.tracker_mod.comment_pulse(id); });
			}
		},

		'comment_unhide': function(obj)
		{
			var comment_id = jQuery(obj).attr('comment_id');
			var href = jQuery(obj).attr('href');
			var trelement = ('#artifact_comment_' + comment_id);

			checking_for_new_comments = true;

			jQuery.ajax({url: href, success: function(data, status)
			{
				jQuery(trelement).removeClass('pulsate');

				var feedback = jQuery(data).find('#top_feedback');
				jQuery("#comment_ajax_feedback").append(feedback);
				jQuery("#comment_ajax_feedback h4:last").oneTime('5s', feedback, function () { jQuery(this).slideUp(1000, function () { jQuery(this).remove(); }); });

				if(feedback.attr('class') == 'message')
				{
					var atid = jQuery('form.commentbox input[name="atid"]').attr('value');
					var artifact_id = jQuery('form.commentbox input[name="artifact_id"]').attr('value');
					var group_id = jQuery('form.commentbox input[name="group_id"]').attr('value');

					jQuery(obj).parent().html('<a href="/tracker/?func=removecomment&aid=' + artifact_id + '&group_id=' + group_id + '&atid=' + atid + '&comment_id=' + comment_id + '" class="comment_hide" comment_id="' + comment_id + '">Hide</a>');

					jQuery(trelement).removeClass('hide');
					jQuery(trelement).show();

					jQuery('.comment_unhide').unbind();
					jQuery('.comment_hide').unbind();
					jQuery('.comment_unhide').click(function () { SFX.tracker_mod.comment_unhide(this); return(false); });
					jQuery('.comment_hide').click(function () { SFX.tracker_mod.comment_hide(this); return(false); });
				}

				if(jQuery('.artifact_comment.hide').size() == 0)
					jQuery('.show_hidden').hide();

				checking_for_new_comments = false;
			},
			error: function(request, textStatus, errorThrown)
			{
				jQuery(trelement).removeClass('pulsate');

				jQuery("#comment_ajax_feedback").html('<h4 class="error">Error making connection to server, please try again.</h4>');

				checking_for_new_comments = false;
			},
			cache: false});

			jQuery(trelement).addClass('pulsate');
			SFX.tracker_mod.comment_pulse(trelement);
		},

		'comment_hide': function(obj)
		{
			jQuery("#comment_ajax_feedback").html('');

			var comment_id = jQuery(obj).attr('comment_id');
			var href = jQuery(obj).attr('href');
			var trelement = ('#artifact_comment_' + comment_id);

			checking_for_new_comments = true;

			jQuery.ajax({url: href, success: function(data, status)
			{
				jQuery(trelement).removeClass('pulsate');

				var feedback = jQuery(data).find('#top_feedback');
				jQuery("#comment_ajax_feedback").append(feedback);
				jQuery("#comment_ajax_feedback h4:last").oneTime('5s', feedback, function () { jQuery(this).slideUp(1000, function () { jQuery(this).remove(); }); });

				if(feedback.attr('class') == 'message')
				{
					var atid = jQuery('form.commentbox input[name="atid"]').attr('value');
					var artifact_id = jQuery('form.commentbox input[name="artifact_id"]').attr('value');
					var group_id = jQuery('form.commentbox input[name="group_id"]').attr('value');

					jQuery(obj).parent().html('<a href="/tracker/?func=unremovecomment&aid=' + artifact_id + '&group_id=' + group_id + '&atid=' + atid + '&comment_id=' + comment_id + '" class="comment_unhide" comment_id="' + comment_id + '">Unhide</a>');

					jQuery(trelement).addClass('hide');

					if(!showhidden)
						jQuery(trelement).hide();
					else
						jQuery(trelement).show();

					jQuery('.comment_unhide').unbind();
					jQuery('.comment_hide').unbind();
					jQuery('.comment_unhide').click(function () { SFX.tracker_mod.comment_unhide(this); return(false); });
					jQuery('.comment_hide').click(function () { SFX.tracker_mod.comment_hide(this); return(false); });
				}

				jQuery('.show_hidden').show();

				checking_for_new_comments = false;
			},
			error: function(request, textStatus, errorThrown)
			{
				jQuery(trelement).removeClass('pulsate');

				jQuery("#comment_ajax_feedback").html('<h4 class="error">Error making connection to server, please try again.</h4>');

				checking_for_new_comments = false;
			},
			cache: false});

			jQuery(trelement).addClass('pulsate');
			SFX.tracker_mod.comment_pulse(trelement);
		},

        'modal_back': function() {
                    modal_stack.pop();
                    SFX.tracker_mod.modal_box(modal_stack.pop());
        },

        'init': function() {
                    jQuery.facebox.settings.overlay = false;
                    jQuery.facebox.settings.closeImage = '/images/phoneix/close.png';
                    jQuery.facebox.settings.loadingImage = '/images/facebox/loading.gif';

                    comment_interval = setInterval(SFX.tracker_mod.check_for_new_comments, 5000);

                    jQuery("form.commentbox").submit(function() {
                        return SFX.tracker_mod.comment_submit(this);
                    });

					if(!jQuery.browser.msie || parseInt(jQuery.browser.version) != 6){
						jQuery('.comment_unhide').click(function () { SFX.tracker_mod.comment_unhide(this); return(false); });
						jQuery('.comment_hide').click(function () { SFX.tracker_mod.comment_hide(this); return(false); });
				    }

                    jQuery(document).bind('loading.facebox', function() {
                        jQuery("#facebox .popup").draggable();
                    });
                    jQuery(document).bind('reveal.facebox', function() {
                        jQuery("#facebox .popup").draggable();
                    });
                    jQuery(document).bind('close.facebox', function() {
                        modal_stack = [];
                        SFX.tracker_mod.toplevel_reload();
                    });
        },

        'stop': function() {
                    clearInterval(comment_interval);
                }
    };

}();

jQuery(function() {
    SFX.tracker_mod.init();
});
