// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/ for more information
//
// Usage:
//      jAlert( message, [title, callback] )
//      jConfirm( message, [title, callback] )
//      jPrompt( message, [value, title, callback] )
//      jFrame( url, [title, callback] )      //Added by Chuck Hill 6/4/2010
// 
// History:
//
//      1.00 - Released (29 December 2008)
//      1.01 - Fixed bug where unbinding would destroy all resize events
//    6/4/2010 Chuck Hill - added jFrame() iframe popup
//    6/4/2010 Chuck Hill - added window animations
//    6/4/2010 Chuck Hill - changed overlay color to dark pink and overlay opacity to 70%
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
   $.alerts = {
      // These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
      verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
      horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
      repositionOnResize: true,           // re-centers the dialog on window resize
      overlayOpacity: .70,                // transparency level of overlay (available only when windowAnimations==true)
      overlayColor: '#000',            // base color of overlay
      draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin and/or UI Resizables plugin)
      okButton: '&nbsp;OK&nbsp;',         // text for the OK button
      cancelButton: '&nbsp;Cancel&nbsp;', // text for the Cancel button
      dialogClass: null,                  // if specified, this class will be applied to all dialogs
      windowAnimations: false,            //enable window animations (e.g. slide up from bottom and fade out background)
                                          //window animation is enabled in the dialog box 'type' case statement
      _disableOverlay : false,            //private global variable. Under IE, we cannot use an overlay over an overlay because the IE filters do not support it.

      // Public methods
      
      alert: function(message, title, callback) {
         if( title == null ) title = 'Alert';
         $.alerts._show(title, message, null, 'alert', function(result) { if( callback ) callback(result); });
      },
      
      confirm: function(message, title, callback) {
         if( title == null ) title = 'Confirm';
         $.alerts._show(title, message, null, 'confirm', function(result) { if( callback ) callback(result); });
      },
         
      prompt: function(message, value, title, callback) {
         if( title == null ) title = 'Prompt';
         $.alerts._show(title, message, value, 'prompt', function(result) { if( callback ) callback(result); });
      },
      
      frame: function(url, title, callback) {
         if( title == null ) title = 'Popup';
         $.alerts._show(title, url, null, 'frame', function(result) { if( callback ) callback(result); });
      },

      close: function(how) {
         var val= null;
         switch(how) {
         case 'ok':
            var val = ($("#popup_prompt").length>0 ? $("#popup_prompt").val() : true);
            $.alerts._hide(); 
            if($.alerts.callback) $.alerts.callback(val);
            return false;
         case 'cancel':
            var val = ($("#popup_prompt").length>0 ? null : false);
            $.alerts._hide(); 
            if($.alerts.callback) $.alerts.callback(val);
            return false;
         default:
            alert("unknown close type");
            return true;
         }
      },

      // Private methods
      
      _show: function(title, msg, value, type, callback) {
         $.alerts._hide();  //close any outstanding popups
         
         var zindex = $(parent.document).find("#popup_container").css('zIndex');
         if (zindex==undefined || zindex=='auto')
         {
            zindex = 98999;
            $.alerts._disableOverlay = false;
         }
         else
         {
            zindex += 100;
            $.alerts._disableOverlay = true;
         }

         $("BODY").append(
           '<div id="popup_container" style="visibility:hidden">' +
             //'<h1 id="popup_title"></h1>' +                                               //Doesn't work in IE. Cancel button visible but non-functional.
             //'<div style="display:inline-block; width:100%;" id="popup_title"></div>' +   //Doesn't work in IE. defaults to width of the first ancestor container that has width defined (e.g. 900px).
             '<div id="popup_content">' +                                                   //both work fine in FireFox!
             '<div id="popup_message"></div>' +
            '</div>' +
           '</div>');
         
         if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);  //add custom class

         // IE6 Fix
         var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
         $("#popup_container").css({
            position: pos,
            zIndex: zindex,
            padding: 0,
            margin: 0
         });
         
         $("#popup_content").addClass(type);
         $("#popup_message").text(msg);
         $("#popup_message").addClass(type);
         $("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
         
         //$("#popup_container").css({ minWidth: $("#popup_container").outerWidth(), maxWidth: $("#popup_container").outerWidth() });
         $("#popup_container").css({ 
            width: $("#popup_container").outerWidth(),           //compute width BEFORE we insert title. min/maxwidth are suggestions and don't do anything when title width:100%
            minWidth: $("#popup_container").outerWidth(), 
            maxWidth: $("#popup_container").outerWidth()
         });
         
         $("#popup_container").prepend('<div style="display:inline-block; width:100%" id="popup_title">'+title+'</div>');  //Now we insert the title
         //$("#popup_title").text(title);
         $("#popup_container").append('<div id="cancelX"><a href="" onclick="return $.alerts.close(\'cancel\')"><div></div></a></div>');  //optionally add cancel button on title bar
         
         $.alerts._reposition();
         $.alerts._maintainPosition(true);

         switch( type ) {
         case 'alert':
               $("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
               $("#popup_ok").click( function() { $.alerts._hide(); callback(true); });
               $("#popup_ok").focus().keypress( function(e) { if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click'); });
            break;
            case 'confirm':
               $("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
               $("#popup_ok").click( function() { $.alerts._hide(); if( callback ) callback(true); });
               $("#popup_cancel").click( function() { $.alerts._hide(); if( callback ) callback(false); });
               $("#popup_ok").focus();
               $("#popup_ok, #popup_cancel").keypress( function(e) { if( e.keyCode == 13 ) $("#popup_ok").trigger('click'); if( e.keyCode == 27 ) $("#popup_cancel").trigger('click'); });
            break;
            case 'prompt':
               $("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
               $("#popup_prompt").width( $("#popup_message").width() );
               $("#popup_ok").click( function() { var val = $("#popup_prompt").val(); $.alerts._hide(); if( callback ) callback( val ); });
               $("#popup_cancel").click( function() { $.alerts._hide(); if( callback ) callback( null ); });
               $("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) { if( e.keyCode == 13 ) $("#popup_ok").trigger('click'); if( e.keyCode == 27 ) $("#popup_cancel").trigger('click'); });
               if( value ) $("#popup_prompt").val(value);
               $("#popup_prompt").focus().select();
            break;
         case 'frame':
            $("#popup_content").css({ padding: 0, margin: 0 });     //HACK! ie6 does not recognize #popup_content.frame to override padding and margin.
            $.alerts.windowAnimations = true;        //because the iFrame modal dialog is much bigger, we enable animations
            var newWidth = Math.floor(0.75 * parseInt($(window).width())); //the iFrame modal dialog is much bigger than the above popup messageboxes.
            var newHeight = Math.floor(0.75 * parseInt($(window).height()));;
            var newLeft = Math.floor(parseInt($(window).width() / 2) - parseInt(newWidth) / 2);
            var newTop = Math.floor(parseInt($(window).height() - newHeight) / 2);
            $("#popup_container").css({ minWidth: 0, maxWidth: 9999 });
            $("#popup_container").css({ top: newTop + 'px', left: newLeft + 'px' });
            $("#popup_container").css({ width: newWidth + 'px', height: newHeight + 'px' });
            var frame = '<iframe src="'+msg+'" width="100%" scrolling="auto" height="100%" style="margin:0; padding:0; border: green 0px solid; z-index:999;"></iframe>';
            $("#popup_message").text("");
            $("#popup_message").html(frame);
            //$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
            //$("#popup_ok").click( function() { $.alerts._hide(); callback(true); });
            //$("#popup_ok").focus().keypress( function(e) { if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click'); });
            var content_margin = $("#popup_content").outerHeight(true) - $("#popup_content").height();
            var h = $("#popup_container").height() - $("#popup_title").outerHeight(true) - $("#popup_panel").outerHeight(true) - content_margin;
            $("#popup_message").height(h);
            break;
         }

         // Make draggable
         if( $.alerts.draggable ) {
            try {
               $("#popup_container").draggable({ handle: $("#popup_title") });
               $("#popup_title").css({ cursor: 'move' });
            } catch(e) { /* requires jQuery UI draggables */ }
//            try {
//                $("#popup_container").resizable({ handles: 'all'});
//            } catch(e) {  /* requires jQuery UI resizables */ }
         }

         $.alerts._overlay('show');
         if($.alerts.windowAnimations)
         {
            var t = $("#popup_container").css('top');  //this is position where we want to end up
            $("#popup_container").css({ opacity:0, visibility:'visible', top:$(window).height() }).animate({top:t,opacity:1},1800,"easeOutBack");
         }
         else
         {
            $("#popup_container").css({ visibility:'visible' });
         }
         $.alerts.alertDepth++;
      },
      
      _hide: function() {
         if($.alerts.windowAnimations) $("#popup_container").fadeOut(600,function(){ $(this).remove();});
         else                          $("#popup_container").remove();
         $.alerts.windowAnimations = false;  //need to turn off window animations here because another type of popup may be displayed later 
         $.alerts._overlay('hide');
         $.alerts._maintainPosition(false);
      },
      
      _overlay: function(status) {  //used to fade out background
         if ($.alerts._disableOverlay) return;
         switch( status ) {
            case 'show':
               $.alerts._overlay('hide');
               $("BODY").append('<div id="popup_overlay"></div>');
               $("#popup_overlay").css({
                  position: 'absolute',
                  zIndex: $("#popup_container").css('zIndex')-1,  //The overlay is BEHIND the alert container
                  top: '0px',
                  left: '0px',
                  width: $(document).width(),  //100% does not work in IE6
                  height: $(document).height(),
                  background: $.alerts.overlayColor,
                  opacity: 0
               });
               if($.alerts.windowAnimations) $("#popup_overlay").fadeTo(600,$.alerts.overlayOpacity);
               //else                          $("#popup_overlay").css({ opacity: $.alerts.overlayOpacity });
            break;
         case 'hide':
               if($.alerts.windowAnimations)
                  $("#popup_overlay").fadeOut(600,function(){ $(this).remove();});
               else
                  $("#popup_overlay").remove();
            break;
         }
      },
      
      _reposition: function() {
         var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
         var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
         if( top < 0 ) top = 0;
         if( left < 0 ) left = 0;

         // IE6 fix
         if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();

         $("#popup_container").css({ top: top + 'px', left: left + 'px' });

         if (!$.alerts._disableOverlay)
         {
            $("#popup_overlay").width( $(document).width() );
            $("#popup_overlay").height( $(document).height() );
         }
      },
      
      _maintainPosition: function(status) {
         if( $.alerts.repositionOnResize ) {
            switch(status) {
               case true:
                  $(window).bind('resize', $.alerts._reposition);
               break;
               case false:
                  $(window).unbind('resize', $.alerts._reposition);
               break;
            }
         }
      }

   }

   // Shortcut functions
   jAlert = function(message, title, callback) { $.alerts.alert(message, title, callback); }
   jConfirm = function(message, title, callback) { $.alerts.confirm(message, title, callback); };
   jPrompt = function(message, value, title, callback) { $.alerts.prompt(message, value, title, callback); };
   jFrame = function(url, title, callback) { $.alerts.frame(url, title, callback); };
})(jQuery);
