/**
 * Tongue box
 */
(function($) {
 $.fn.worktongue = function(options, loaded_callback) {
     
     // options
      var options = $.extend({
          'height': 200,
          'width': 614,
          'speed': 300,
          'position': 'relative'
      }, options);
     
      
     return this.each(function() {
         
         // VAR
         
         var obj = $(this);

         // FUNCTIONS

         function get_content(url, param, callback) {
             $.get(url, param, callback, 'html');
         }
         
         function bind_submit_event() {
             $("#tongue").find('form').bind('submit', function() {
                 $(this).ajaxSubmit({
                     success : is_form_valid
                 });
                 return false;
             });
         }
         
         function set_content(html) {
             $("#tongue").html(html);
             bind_submit_event();
             loaded_callback();
         }
         
         function is_form_valid(html) {
             if ($('.form-error-header', html).length != 0) {
                 set_content(html);
             } else {
                 message_engine.alert('', html);
                 $("#tongue").tongue('close');
                 set_content('');
             }
         }
         
         // RUN
         
         if ($("#tongue").tongue("isbuild") != true) {
             $("#tongue").tongue({
                                    'height': options.height,
                                    'width': options.width,
                                    'speed': options.speed,
                                    'position': options.position
                                    });
         }

         obj.click(function() {
              
              var url = options.url;
              var tongueElem = $("#tongue");
              
              if (tongueElem.tongue("isopen") != true) {tongueElem.tongue("open");}
              tongueElem.tongue("resize", {'width': options.width,'height': options.height});
              if (options.url == 'self') {url = $(this).attr('href');}
          
              get_content(url, {}, set_content);
              
              return false;
         });
     });
 };
})(jQuery);