$j = jQuery.noConflict();

// Miscelaneous javascript functionality for Asterion
(function($) {
    $.asterion = $.asterion || {};

    $.asterion.required = [];

    // this utility function creates a function named +name+ on +object+
    // which can be called in two ways:
    // name([function]) -- add +callback+ to the array of functions to call
    // name([any other args]) -- call all functions in the array with [args]
    // (stops and returns false if any callbacks return false)
    $.createCallbacks = function(object, names) {
      names = $.makeArray(names);
      $.each(names, function() {
        var name = this;
        object['_callbacks'] = object['_callbacks'] || {};
        object['_callbacks'][name] = [];
        object[name] = function() {
          if(typeof(arguments[0]) == 'function' && arguments.length == 1) {
            var callback = arguments[0];
            this._callbacks[name][this._callbacks[name].length] = callback;
            return this;
          } else {
            var result;
            for(var i = 0; i < this._callbacks[name].length; i++) {
              result = this._callbacks[name][i].apply(this, $.makeArray(arguments));
              if(result === false) return false;
            }
            return true;
          }
        };
      });
    };

    // humanize text. foo_bar => Foo Bar
    $.asterion.humanize = function(text) {
      return text.replace('_',' ').replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase();
      });
    };

    // Used by the Visual editor toolbar to provide switching between Visual and HTML mode
    $.asterion.switchContentEditor = function (type, id) {
      if(type === 'visual') {
        $j('#' + id).tinymce().show();
        $j('#tiny_templates').show();
        $j('#html_editor_link').removeClass('active');
        $j('#visual_editor_link').addClass('active');
      } else {
        $j('#' + id).tinymce().hide();
        $j('#tiny_templates').hide();
        $j('#visual_editor_link').removeClass('active');
        $j('#html_editor_link').addClass('active');

        $j('#' + id).addClass('html_editor');
        $j('#' + id).css({'visibility' : 'visible', 'width' : '762px' });
      }
    };

    // Teeny little tooltip.
    $.asterion.showTooltip = function( contents, x, y ) {
      $('<div id="asterion_tooltip">' + contents + '</div>').css( {
          top: y + 5,
          left: x + 5
      }).appendTo("body").fadeIn(200);
    };

    $.asterion.hideTooltip = function() {
      $j('#asterion_tooltip').remove();
    };

    $.asterion.parseBackgroundPosition = function(strg) {
      if(typeof(strg) !== 'string' || strg.length === 0) { return [0, 'px', 0, 'px']; }
      strg = strg.replace(/left|top/g,'0px');
      strg = strg.replace(/right|bottom/g,'100%');
      strg = strg.replace(/(\d+)(\s|\)|$)/g,"$1px$2");
      var res = strg.match(/(\d+)(px|\%|em|pt)\s(\d+)(px|\%|em|pt)/);
      return [parseFloat(res[1]),res[2],parseFloat(res[3]),res[4]];
    };


    /** Account selection stuff for linked accounts in blog posts **/
    $.asterion.showLinkedAccounts = function(type) {
      $('#select_' + type + '_account ul.account_selector').show();
    };

    $.asterion.changeLinkedAccount = function(type, account) {
      $('#announce_' + type).val( account );
      $('#select_' + type + '_account label a').text( $('#' + type + '_account_' + account + ' a').text() );
      $('#select_' + type + '_account ul.account_selector').hide();
    };

   /**
    * Open a flickr image selection dialog, and run the supplied callback
    * when the user selects an image. Callback is called with two arguments:
    * the flickr ID of the image, and the full url of the image.
    */
    $.asterion.flickrSelect = function( callback ) {
      var options = arguments[1] || {};
      var params = '';
      if(options.username) {
        params = '?filter='+options.username;
      }
      return this.dialog.open( '/resource/flickr/browse' + params, {
        name: 'flickr_browse',
        close: function() {
          // only call the callback if we received some data
          if(arguments[0] && arguments[1]) {
            callback.apply(this, $.makeArray(arguments));
          }
        }
      });
    };

   /**
    * Open a youtube video selection dialog, and run the supplied callback
    * when the user selects a video. Callback is called with one argument:
    * the youtube url of the video.
    */
    $.asterion.youtubeSelect = function( callback ) {
      return $.asterion.dialog.open( '/resource/youtube/search', {
        name: 'youtube_browse',
        close: function() {
          // only call the callback if we received some data
          if(arguments[0]) {
            callback.apply(this, $.makeArray(arguments));
          }
        }
      });
    };

   /**
    * Open an internal asset selection dialog, and run the supplied callback
    * when the user selects an asset. Callback is called with two arguments:
    * the flickr ID of the image, and the full url of the image.
    *
    * Valid options:
    *   type: the type of asset to select (such as 'image'), or 'any'.
    *   upload: start the asset manager in upload mode, which automatically selects if they upload one valid file.
    *
    * @param {Function} callback The function to run when a selection is made
    * @param {Object} extended options (see docs above)
    */
    $.asterion.assetSelect = function( callback ) {
      var options = arguments[1] || {}, url;
      options.type = options.type || 'all';

      var wrapped_callback = function() {
        // only call the callback if we received some data
        if(arguments[0] && arguments[1]) {
          callback.apply(this, $.makeArray(arguments));
        }
      };

      if (options.upload) {
        url = (options.type == 'all' ? '/resource/select/all/upload' : '/resource/select;' + options.type + '/upload');
        if (options.collection !== '' && typeof(options.collection) !== 'undefined') { url += '/collection/' + options.collection; }

        url += '?direct_upload=true';

        if (options.content_type !== '' && typeof(options.content_type) !== 'undefined') { url += '&content_type=' + options.content_type; }
        if (options.file_types !== '' && typeof(options.file_types) !== 'undefined') { url += '&file_types=' + options.file_types; }
        if (options.file_types_description !== '' && typeof(options.file_types_description) !== 'undefined') { url += '&file_types_description=' + options.file_types_description; }

        return $.asterion.dialog.open( url, {
          name: 'asset_manager_browse',
          complete: function() {
            swfupload_manager.completion_callback = function() {
              if (options.closeOnUpload) {
                callback.apply(this); // Closing won't fire the callback since it has no arguments... so call it now.
                $.asterion.dialog.close();
                return false;
              }

              // if they uploaded one file and it is of an acceptable type, short-circuit the selection process
              var successful_upload = $j('.successful_upload');
              if(successful_upload.length == 1) {
                if(options.type == 'all' || options.type == successful_upload.data('file_data').type.toLowerCase()) {
                  $.asterion.dialog.close({data: [successful_upload.data('file_data').id, successful_upload.data('file_data').url] });
                  return false;
                }
              }
            };
          },
          close: wrapped_callback
        });
      } else {
        url = (options.type == 'all' ? '/resource/select' : '/resource/select;' + options.type);
        if (options.content_type !== '' && typeof(options.content_type) !== 'undefined') { url += '?content_type=' + options.content_type; }
        if (options.file_types !== '' && typeof(options.file_types) !== 'undefined') { url += '&file_types=' + options.file_types; }
        if (options.file_types_description !== '' && typeof(options.file_types_description) !== 'undefined') { url += '&file_types_description=' + options.file_types_description; }
        return $.asterion.dialog.open( url, {name: 'asset_manager_browse', close: wrapped_callback} );
      }
    };

    // Sadly, we can't just strip non-word chars.. international characters
    $.asterion.makePermalink = function(text) {
      return text.toLowerCase().replace(/[&#'"\(\)\:%\$\?\+;,?\/\s.]/g,'-').replace(/--+/g, '-');
    };

    // bind the function to the passed-in context
    $.bind_function = function(func, obj) {
      return function() {
        return func.apply(obj, $.makeArray(arguments));
      };
    };

    $.asterion.relativeDate = function(time) {
      var date = new Date(parseInt(time, 10)),
      diff = (((new Date()).getTime() - date.getTime()) / 1000),
      day_diff = Math.floor(diff / 86400);

      if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 365 )
        return '';

      return day_diff === 0 && (
        diff < 60 && "just now" ||
        diff < 120 && "1 minute ago" ||
        diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
        diff < 7200 && "1 hour ago" ||
        diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
      day_diff == 1 && "Yesterday" ||
      day_diff < 7 && day_diff + " days ago" ||
      day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
      day_diff < 360 && Math.ceil( day_diff / 30 ) + " months ago" ||
      Math.ceil( day_diff / 365 ) + " years ago";
    };

    $.fn.relativeDate = function() {
      return this.each(function() {
        var date = $.asterion.relativeDate(this.title);
        if ( date ) {
          $(this).text( date );
        }
      });
    };

    // temp workaround for jQuery 1.2.6 bug: .replaceWith() does .after().remove()
    // which leaves duplicate ids in the document during script execution.
    // .before().remove() does the same thing, but with before(), getElementById
    // gets the new elements, which means stuff like component editors requires
    // less tomfoolery to work.
    $.fn.replaceWith = function(content) {
      return this.before( content ).remove();
    };

    // disable text selection on collection. jquery ui has a version of this that
    // doesnt seem to work in ie.
    $.fn.disableSelection = function() {
      return this.each(function() {
        this.unselectable = "on";
        this.onselectstart = function() { return false; };
        if (this.style) { this.style.MozUserSelect = "none"; }
      });
    };

    // reverse the order of elements in a jquery collection. used by our super duper sortables.
    $.fn.reverse = [].reverse;

    // return the first element of a collection that contains the passed-in coordinates
    // or false, if none
    // third param allows you to catch nearby coordinates that are outside the element,
    // e.g. using 50 will return an element that is less than 50 pixels from the x, y coordinates
    $.fn.contains_coordinates = function(x, y, max_distance) {
        max_distance = max_distance || 0;
        var container = false;
        this.each(function() {
            var position = $(this).offset();
            position.right = position.left + $(this).get(0).offsetWidth;
            position.bottom = position.top + $(this).get(0).offsetHeight;
            var distance = Math.max(position.left - x, x - position.right, 0) + Math.max(position.top - y, y - position.bottom, 0);
            if( distance <= max_distance )
            {
              container = $(this);
              return false;
            }
        });
        return container;
    };

    // return the proportion by which the first element overlaps the passed-in coordinates
    // (useful for telling whether the mouse is pointing at the top or bottom half of an element)
    $.fn.overlap = function(x, y, axis) {
        var container = $(this).contains_coordinates(x,y);
        if(!container) return false;
        var height = container.get(0).offsetHeight;
        var relative_position = (y) - container.offset().top;
        return relative_position / height;
    };

    // ripoff of prototype's Form.observe()
    // TODO: figure out how to cancel observers when the elements go away
    $.fn.observe = function( time, callback ){
      return this.each(function() {
        var element = this, prevVal = $(element).serialize(), observer, newValConfirm;

        observer = setInterval(function(){
          // stop watching if the element has been removed from the body
          if(!$j(element).parents('body')[0]) { clearInterval(observer); return; }
          var newVal;
          newVal = $(element).serialize();
          if ( prevVal != newVal ) {

            if (newVal == newValConfirm) {
              newValConfirm = '';
              prevVal = newVal;
              callback.call( element );
            }
            else
            {
              newValConfirm = newVal;
            }
          }

         }, time * 1000);
      });
    };

    /**
     * Ajax scrolling currently implemented in theme selection and file manager. You can
     * reset the page counter by clobbering `$.asterion._ajax_page_counter`
     * 
     * === Options
     * url : passes option to $.ajax jquery method
     * data : passes option to $.ajax jquery method
     * style : additional style options for html loader ie. `text-align:center` 
     * start : page you want to start fetching items from
     * trigger_area : trigger ajax event within # of pixels to reaching the bottom
     * loader : custom html loader
     * insertLoaderAfter: id of element to insert loader after
     * success : $.ajax callback
     */
    $.fn.ajaxScroll = function(options) {
 
      var defaults = {
        style : '',
        data : {},
        start: 1, 
        trigger_area: 200, 
        insertLoaderAfter : $(this),
        loader : '<img src="/images/loading.gif"> Loading, please wait ...',
        success: function() { return true; }, // callback for ajax success
      }; 

      options = $.extend(defaults, options);
      var in_progress = false; // don't keep triggering if we're fetching
      var inner_wrap = null;
      var prev_height = $(options.insertLoaderAfter).height(); // tells us when to stop fetching 
      var self = this;
      $.asterion._ajax_page_counter = options.start;   

      // reset all the bindings we dont want any shenanigans
      $(this).unbind('scroll');
      $(this).scroll(function() {
        inner_wrap = $('.ajax_scroll_inner_wrap', this);
        if (inner_wrap.length == 0) {
          $(this).wrapInner('<div class="ajax_scroll_inner_wrap"></div>');
          inner_wrap = $('.ajax_scroll_inner_wrap', this);
        }

        if ($(this).scrollTop() + options.trigger_area > inner_wrap.height() - $(this).height()) {
          if (in_progress == false) {
            in_progress = true;
                
            $(options.insertLoaderAfter).after('<div style="'+options.style+'" id="ajax_scroll_loader">' + options.loader + '</div>');
            $.ajax($.extend({}, options, {
              data: $.extend({
                page: $.asterion._ajax_page_counter
              }, options.data),
              success: function(data) {
                $.asterion._ajax_page_counter++;
                $('#ajax_scroll_loader').remove();
                options.success(data);
                
                // we want to unbind the event if our container wasn't populated
                var new_height = $(options.insertLoaderAfter).height();
                if (new_height == prev_height) {
                  $(self).unbind('scroll');
                } else {
                  prev_height = new_height;
                }

                in_progress = false;
              }
            }));
          }
        }
      });
    };

    // onchange() on select boxes is handled in a variety of retarded ways by different browsers.
    // this patch (hopefully) makes them all work like you would expect them to.
    $.event.special.change = {
      setup: function() {
        // only monkeypatch if we're dealing with a select element and we're not dealing with Safari.
        if(this.tagName.toLowerCase() != 'select' || $.browser.safari) return false;
        $(this).data('oldVal', $(this).val());
        $(this).bind("click keydown", $.event.special.change.handler);
        return true;
      },

      teardown: function() {
        $(this).unbind("click keydown", $.event.special.change.handler);
      },

      handler: function(event) {
        var args = arguments;
        setTimeout($.bind_function(function() {
          if($(this).val() != $(this).data('oldVal')) {
            $(this).data('oldVal', $(this).val());
            args[0].type = 'change';
            return $.event.handle.apply(this, args);
          } else {
            return true;
          }
        }, this), 1);
        return true;
      }
    };

    // monkeypatch to allow background position animation
    $.extend($.fx.step,{
      backgroundPosition: function(fx) {
        if (fx.state === 0 && typeof fx.end === 'string') {
          var start = $.curCSS(fx.elem,'backgroundPosition');
          start = $.asterion.parseBackgroundPosition(start);
          fx.start = [start[0],start[2]];
          var end = $.asterion.parseBackgroundPosition(fx.end);
          fx.end = [end[0],end[2]];
          fx.unit = [end[1],end[3]];
        }
        var nowPosX = [];
        nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
        nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
        fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];
      }
    });


    // We add our own JS datatype because the 'script' datatype is automatically eval'd
    // and we want to be able to skip evaluation under certain conditions.
    $.ajaxSettings.accepts.asterionJavascript = 'text/javascript, application/javascript';

    // only monkeypatch ui if it's actually loaded
    if($.ui) {
      // this is used when you drag a component when the toolbar is on the bottom -- without
      // this method, the component editor shrinks up to the top and the editor basically
      // disappears as soon as you start dragging. this method allows it to "shrink down"
      // rather than "shrink up".
      //
      // if you read the jquery docs, it appears you can do this already, but they do it when
      // the draggable is setup. We have to do it when the drag is started, so their code won't
      // work.'
      $.ui.draggable.prototype.reset_position = function(newCursorAt) {
        var o = this.options;
        if(newCursorAt) o.cursorAt = $.extend(o.cursorAt, newCursorAt);

        this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };//Cache the helper size

        if(o.cursorAt) {
                if(o.cursorAt.left != undefined) this.offset.click.left = o.cursorAt.left + this.margins.left;
                if(o.cursorAt.right != undefined) this.offset.click.left = this.helperProportions.width - o.cursorAt.right + this.margins.left;
                if(o.cursorAt.top != undefined) this.offset.click.top = o.cursorAt.top + this.margins.top;
                if(o.cursorAt.bottom != undefined) this.offset.click.top = this.helperProportions.height - o.cursorAt.bottom + this.margins.top;
        }
      };

      // this patch adds a "static" tolerance type to sortable positioning.
      $.ui.sortable.prototype._originalIntersectsWithEdge = $.ui.sortable.prototype._intersectsWithEdge;
      $.ui.sortable.prototype._intersectsWithEdge = function(item) {
        if(this.options.tolerance == "static") {
          var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width,
            y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height;

          var l = item.left, r = l + item.width,
            t = item.top, b = t + item.height;

          var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
          var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;

          if(!isOverElement) {
            return false;
          }

          if(this.floating) {
            return ((l + r) / 2 > (dxClick + x1)) ? 1 : 2;
          } else {
            return ((t + b) / 2 > (dyClick + y1)) ? 1 : 2;
          }

          return false;
        } else {
          return this._originalIntersectsWithEdge(item);
        }
      };
    }

   /*
    * Initialize admin toolbar behaviors
    */
    $(function($) {
      if(!$('#asterion_toolbar_wrapper').get(0)) { return; }

      $('#asterion_my_website, #asterion_my_content, #asterion_page_select').hover(
        function(event, manualTrigger) {
          if(!$.asterion.componentEditor.draggingEditor || manualTrigger) {
            $(this).find('ul.asterion_toolbar_dropdown_menu').fadeIn('fast');
          }
        },
        function(event, manualTrigger) {
          if(!$.asterion.componentEditor.draggingEditor || manualTrigger) {
            $(this).find('ul.asterion_toolbar_dropdown_menu').hide();
          }
        }
      );

      $('li#asterion_show_all_services a').toggle(function() {
          $('#asterion_my_content li.inactive_service').slideDown('fast');
          $(this).css('background-image','url(/images/toolbar/less_content.png)');
        }, function() {
          $('#asterion_my_content li.inactive_service').slideUp('fast');
          $(this).css('background-image','url(/images/toolbar/more_content.png)');
        }
      );

      /* Status bar tooltips */
      $('#asterion_statusbar ul.status_actions li').hover(
        function() { $(this).find('div.status_action_tooltip').css({ display: 'block' }); },
        function() { $(this).find('div.status_action_tooltip').css({ display: 'none' }); }
      );

      /* Status bar toggle buttons */
      $("#asterion_layout_mode").toggle(function() {
          $.asterion.component.toggleLayoutMode();
          $(this).addClass('active_status_link');
        }, function() {
          $.asterion.component.toggleLayoutMode();
          $(this).removeClass('active_status_link');
        }
      );

      $("#asterion_orphaned_content_link").toggle(function() {
        if ($('#asterion_notification_window').css('display') == 'block') { $('#asterion_notification_count_link').click(); }
        $(".status_action_tooltip").css("display","none");
        $("#asterion_orphaned_components_window").show();
        $(this).addClass('active_status_link');
       }, function() {
        $("#asterion_orphaned_components_window").hide();
        $(this).removeClass('active_status_link');
      });

      $("#asterion_notification_count_link").toggle(function() {
        if ($('#asterion_orphaned_components_window').css('display') == 'block') { $('#asterion_orphaned_content_link').click(); }
        $(".status_action_tooltip").css("display","none");
        $("#asterion_notification_window").show();
        $(this).addClass('active_status_link');
       }, function() {
        $("#asterion_notification_window").hide();
        $(this).removeClass('active_status_link');
      });

      // pop down the body background if one exists
      var body_bg_position = $.asterion.parseBackgroundPosition($('body').css('background-position'));
      if(body_bg_position[2] === 0 || body_bg_position[3] === 'px') {
        var body_bg_positions = {
          original: body_bg_position[0] + body_bg_position[1] + ' ' + (body_bg_position[2]) + 'px',
          lowered: body_bg_position[0] + body_bg_position[1] + ' ' + (body_bg_position[2] + 48) + 'px'
        };
        $('body').css('background-position', body_bg_positions.lowered);
      }

      // activate the "hide" link
      $('#asterion_hide_link').click(function() {
                                if ( $.asterion.component.layoutMode === true ) {
                                        $.asterion.component.toggleLayoutMode();
          $('#asterion_layout_mode').removeClass('active_status_link');
                                }
        var show_tab = $('<div id="show_tab">\
          <div id="asterion_hide_explanation" />\
          <a href="javascript:void(0)" id="asterion_show_link" class="toggle_tab">Show</a>\
          </div>').prependTo(document.body);
        show_tab[0].timeout = setTimeout(function() { $j("#asterion_hide_explanation").slideUp(); }, 5000);

        $('#asterion_show_link').click(function() {
          if(show_tab[0].timeout) { clearTimeout(show_tab[0].timeout); }
          show_tab.animate({top: '-38px'}, {
            complete: function() {
              $j(this).remove();
              $('.unpublished, .invisible').slideDown();
              $j("#asterion_toolbar_wrapper").slideDown();
              $j("#asterion_statusbar_wrapper").fadeIn();
              $j("#asterion_page_wrapper").animate({paddingTop: '48px', paddingBottom: '25px'});
              if(body_bg_positions) {
                $j('body').animate({backgroundPosition: '(' + body_bg_positions.lowered + ')'});
              }
              document.cookie = 'toolbar_status=show; path=/';
            }
          });
        });

        $('.unpublished, .invisible').slideUp();
        $j("#asterion_toolbar_wrapper").slideUp();
        $j("#asterion_statusbar_wrapper").fadeOut();
        $j("#asterion_page_wrapper").animate(
          { paddingTop: 0, paddingBottom: 0 },
          { complete: function() {show_tab.animate({top:'-2px'});} }
        );
        if(body_bg_positions) {
          $j('body').animate({backgroundPosition: '(' + body_bg_positions.original + ')'});
        }
        document.cookie = 'toolbar_status=hide; path=/';
        return false;
      });

      if(document.cookie.indexOf('toolbar_status=hide') != -1) {
        setTimeout(function() {$('#asterion_hide_link').click();}, 400);
      }

      if ($.browser.msie && $.browser.version < 7) {
        // IE6 toolbar fixed-positioning and png transparency hacks
        if ($('#asterion_toolbar_wrapper')[0]) {
          $('#asterion_toolbar_wrapper').css({ background: 'url(/images/toolbar/main_ie_bg.png) repeat-x top center', top: '0px', position: 'absolute'});
          $('#asterion_statusbar_wrapper').css( { position: 'absolute', top: $(window).scrollTop() + $(window).height() - 25 + 'px' });
          var statusbar_height = $('#asterion_statusbar_wrapper').height();
          $(window).scroll(function() {
            $('#asterion_toolbar_wrapper').css('top', $(window).scrollTop()  + "px");
            $('#asterion_statusbar_wrapper').css({ top: $(window).scrollTop() + $(window).height() - statusbar_height - 1 + 'px' });
          });
        }
      }
      $('#asterion_toolbar_wrapper').disableSelection();

    });

})(jQuery);

//
// return the id of an id node by removing the element_type_ from the id
//

function get_id(component,element_type) { return $j(component).attr('id').replace(element_type + "_","");  }

//
// Ajax Load Indicator shortcuts
//

function show_loading_indicator(el, message) { $j('#' + el).addClass('loading_indicator'); }
function remove_loading_indicator() { $j('.loading_indicator').removeClass('loading_indicator'); }

//
// button_change: push button replacement for checkboxes
//

function button_change(element) {
  var value = $j(element).attr('checked');
  var name = $j(element).attr('name');

  elements = $j('#label_' + name + ', #div_' + name);

  // toggle the label and div class to reflect the on or off status
  if (value) {
    elements.addClass('asterion_button_change_on');
  }
  else {
    elements.removeClass('asterion_button_change_on');
  }
}

// Submit the form in the asterion dialog
function submit_dialog_form(element_id) {
  var form = $j(element_id).parents().andSelf().filter('form')[0];
  if (form) {
    $j(form).submit();
    return false;
  }
}

function dialog_form_disable(form) { $j(form).addClass('disabled').find('.asterion_dialog_submit .dialog_button').addClass( 'button_disabled' ); }
function dialog_form_enable(form) { $j(form).removeClass('disabled').find('.asterion_dialog_submit .dialog_button').removeClass( 'button_disabled' ); }

