(function($)
{
  function uniquealertPlusNum(alertPlusId)
  {
    return ($('#alertPlus_'+alertPlusId).length) ? uniquealertPlusNum(alertPlusId+1) : alertPlusId;
  }
  
  var alertPlusId = 1;
  var zIndex = 1;
  var alertPluss;
  
  $.alertPlus = function(properties)
  {
    // Set unique id for new window
    var alertPlusId = uniquealertPlusNum(alertPlusId);
    
    // Check if properties is a string or object
    if(typeof properties == 'string')
    {
      message = properties;
      properties = {options:{}, style:{}};
    }
    else
    {
      message = properties.message || $.alertPlus.defaults.message;
      properties.options = properties.options || $.alertPlus.defaults.options;
      properties.style = properties.options || $.alertPlus.defaults.style;
    }
    
    // Close button (X)
    var closeButton = '';
    noCloseButton = properties.options.noCloseButton || $.alertPlus.defaults.options.noCloseButton;
    if(!noCloseButton)
      closeButton = '<div class="close_alertPlus" id="close_alertPlus_'+alertPlusId+'" title="Close this window" onclick="$.alertPlus.closeAlertPlus('+alertPlusId+')"><span>Close</span></div>';
    
    // Start building HTML string of buttons from buttonsObj
    buttonsHTML = "\n  <div class=\"alertPlus_buttons\" id=\"alertPlus_buttons_"+alertPlusId+"\">";
    
    var buttonsObj = properties.buttons || $.alertPlus.defaults.buttons;
    for(button in buttonsObj)
    {
      // build HTML string of attributes to add to the anchor tag
      attributeHTML = '';
      var numAttributes = 0;
      if(buttonsObj[button]['close'] == true)
        buttonsObj[button]['onclick']+= '; $.alertPlus.closeAlertPlus('+alertPlusId+')';

      for(attribute in buttonsObj[button])
      {
        numAttributes++;
        attributeHTML+= ' '+attribute+'="'+buttonsObj[button][attribute]+'"';
      }
      
      // If no attributes are specified set onclick as $.alertPlus.closeAlertPlus();
      if(numAttributes < 1)attributeHTML+= ' onclick="$.alertPlus.closeAlertPlus('+alertPlusId+')"';
      
      // Add anchor tag to button div        
      buttonsHTML+= "\n    <a class=\"alertPlus_button "+button.replace(/[^a-z]/ig, '_')+"\" id=\"alertPlus_button_"+alertPlusId+"_"+button.replace(/[^a-z]/ig, '_')+"\""+attributeHTML+" ><span>"+button+"</span></a>";
    }
    buttonsHTML+= "\n  </div>";
    
    // Append alertPlus elements to document body
    
    // fade out background if set
    var notModal = properties.options.notModal || $.alertPlus.defaults.options.notModal;
    if(!notModal)
    {
      //$('body').append('test');
      $('body').append('\n<div class="alertPlus_bg" id="alertPlus_bg_'+alertPlusId+'" style="display:none">test</div>');
      $('#alertPlus_bg_'+alertPlusId).css({'display':'none', 'position':'fixed', 'width':'100%', 'height':'100%', 'top':'0px', 'left':'0px', 'backgroundColor':(properties.options.bgColour || $.alertPlus.defaults.options.bgColour), 'opacity':(properties.options.bgOpacity || $.alertPlus.defaults.options.bgOpacity), 'zIndex':zIndex+=1});
    }
    $('body').append('\n<div class="alertPlus" id="alertPlus_'+alertPlusId+'" style="display:none">'+
                     '\n  <div class="title_bar" id="title_bar_'+alertPlusId+'">'+closeButton+(properties.title || $.alertPlus.defaults.title)+'</div>'+
                     '\n  <p class="message" id="message_'+alertPlusId+'">'+message+'</p>'+
                     '\n'+(properties.html || $.alertPlus.defaults.html)+
                     buttonsHTML+
                     '\n  <div class="status_bar" id="status_bar_'+alertPlusId+'">&nbsp;</div>'+
                     '\n</div>');
    
    // Apply alert CSS
    $('#alertPlus_'+alertPlusId).css(properties.style.alertPlus || $.alertPlus.defaults.style.alertPlus);
    $('#alertPlus_'+alertPlusId+' #title_bar_'+alertPlusId).css(properties.style.titleBar || $.alertPlus.defaults.style.titleBar);
    $('#alertPlus_'+alertPlusId+' p#message_'+alertPlusId).css(properties.style.p || $.alertPlus.defaults.style.p);
    $('#alertPlus_'+alertPlusId+' div#alertPlus_buttons_'+alertPlusId).css(properties.style.alertPlusButtons || $.alertPlus.defaults.style.alertPlusButtons);
    $('#alertPlus_'+alertPlusId+' a.alertPlus_button').css(properties.style.alertPlusButton || $.alertPlus.defaults.style.alertPlusButton);
    $('#alertPlus_'+alertPlusId+' a.alertPlus_button').hover(function(){$(this).css(properties.style.buttonHover || $.alertPlus.defaults.style.buttonHover)}, function(){$(this).css(properties.style.alertPlusButton || $.alertPlus.defaults.style.alertPlusButton)});
    $('#alertPlus_'+alertPlusId+' div#close_alertPlus_'+alertPlusId).css(properties.style.closeAlertPlus || $.alertPlus.defaults.style.closeAlertPlus);
    $('#alertPlus_'+alertPlusId+' div#close_alertPlus_'+alertPlusId+' span').css(properties.style.closeSpan || $.alertPlus.defaults.style.closeSpan);
    
    // Set alertPlus window position and depth
    var left = $(window).scrollLeft() + ($(window).width()/2) - ($('#alertPlus_'+alertPlusId).width()/2);
    var top  = $(window).scrollTop() + ($(window).height()/2) - ($('#alertPlus_'+alertPlusId).height());
    $('#alertPlus_'+alertPlusId).css({'left':left+'px', 'top':top+'px', 'zIndex':zIndex+=1});
    
    // Allow clicking to bring to front
    $('.alertPlus').mousedown(function(){$(this).css('zIndex', zIndex+=1); });
    
    // Set draggability
    $('.alertPlus').draggable();
    $('.alertPlus').draggable('disable');
    if(properties.options.draggable || $.alertPlus.defaults.options.draggable)
    {
      $('#title_bar_'+alertPlusId).css({cursor:'grab', cursor:'-moz-grab'});
      $('#title_bar_'+alertPlusId).mousedown(function(){$(this).css({cursor:'url()grabbing', cursor:'-moz-grabbing'})});
      $('#title_bar_'+alertPlusId).mouseup(function(){$(this).css({cursor:'grab', cursor:'-moz-grab'});});
      $('#title_bar_'+alertPlusId).bind('mouseenter', (function(){$(this).parent().draggable('enable')}));
      $('#title_bar_'+alertPlusId).bind('mouseleave', (function(){$(this).parent().draggable('disable')}));
    }
    
    // fade elements in
    if(!notModal)
      $('#alertPlus_bg_'+alertPlusId).fadeIn('slow');
    $('#alertPlus_'+alertPlusId).fadeIn('slow');
    
    // Set keypress function
    $(document).keypress(function(e){
      // Escape to close
      if(!notModal)
        if(e.keyCode==27)$.alertPlus.closeAlertPlus(alertPlusId);
    });
  };
  
  $.alertPlus.closeAlertPlus = function(id)
  {
    // close individual
    if($('#alertPlus_'+id).length)
    {
      $('#alertPlus_bg_'+id).fadeOut('slow', function(){$(this).remove()});
      $('#alertPlus_'+id).fadeOut('def', function(){$(this).remove()});
      // Alter the escape function
      $(document).unbind();
      $(document).keypress(function(e){
        if(e.keyCode==27)$.alertPlus.closeAlertPlus(numPopups);
      });
    }
  }
  
  $.alertPlus.defaults = {
    title: 'System Message',
    message: 'This is the default message',
    html: '',
    buttons: {
      OK:{}
    },
    options : {
      bgColour: '#454545',
      bgOpacity: 0.5,
      noCloseButton: false,
      notModal: false
    },
    html: '',
    style: {
      alertPlus:{
        'display': 'none',
        'position': 'absolute',
        'background': '#eee',
        'border': '3px solid #666',
        'width': '280px',
        'padding': '5px',
        'textAlign': 'center'},
      titleBar:{
        'background': '#666',
        'margin': '-5px -5px 15px -5px',
        'padding': '5px',
        'color': '#fff',
        'fontWeight': 'bold',
        'fontSize': '14px'},
      alertPlusButtons:{
        'marginTop': '20px'},
      p:{
        'margin': '20px',
        'color': '#333'},
      alertPlusButton:{
        'textDecoration': 'none',
        'border': '1px solid #666',
        'background': '#eee',
        'padding': '2px 5px',
        'color': '#666',
        'cursor': 'pointer',
        'margin': '5px 2px'},
      buttonHover:{
        'background': '#666',
        'color': '#fff'},
      closeAlertPlus:{
        'background': 'url(data:image/gif;base64,R0lGODlhEAAQALMNALhkZPh5efx+fu6YmOhmZvNzc/+BgeNgYO1tbfOhof2zs/GcnPuwsP///wAAAAAAACH5BAEAAA0ALAAAAAAQABAAAAQ+sMlJq704XwAo34bRNUA4eoogcKpyekwgB8xbAUVe2DfiI7wJgEBIJIhBwOGw4CyWPMBgMJJSN6+PZsvtViIAOw==) no-repeat',
        'float': 'right',
        'width': '16px',
        'height': '16px',
        'cursor': 'pointer'},
      closeSpan:{
        'display':'none'}
    }
  };

  })(jQuery);