/* Version 2.0 of the NovelProjects Modal Popup
 * Author: Chris Keenan
 * Author: Nathan Wilkinson
 * Website: http://www.novelprojects.com/ */
  
(function($){   

  var ie = $.browser.msie;
  var ie6 = ($.browser.msie  && parseInt($.browser.version.substr(0,1)) < 7);
  var c, c0, currentSettings;
  
	$.fn.npModal = function(params) {
	  //-- Default Settings --//
    var settings = {
      containerTarget: '#modalTarget',
      targetClass: '.npContent',
      overlayClass: '.npOverlay',
      closeClass: '.npClose',      
      dragClass: '.npTitle', 
      enableOverlayClose: false,
      enableEscape: true,
      title: false, // set to a string value to be the modal windows title   
      enableDrag: false, // if true, you must include jquery ui core, and jquery ui drag
      isModal: true, // if false, no overlay is displayed and you can still interact with the page
      animate: false, // when set to true, animations will fire
      ajax: false, // set to a path as a string of your requested page
      toTop: false, // always positions modal 15% from top of inner browser height
      destroyOverlay: true, // set to false if using parent/child modals so child doesn't remove overlay on it's close
      toggleHide: true, // used for parent/child modals whether to hide the parent on opening child
      sender: null, // used for parent/child modals as the parent sender
      overlay: 50, // percentage of opacity for overlay
      width: '620px',
      height: 'auto',
      closeCallback: null
    };
    var o = $.extend(settings, params);
	  currentSettings = o;
    
    return this.each(function() {   
      doModal(o);
    });   
  };
  
  //-- Remove the modal from DOM --//
  //-- Passing now parameters will remove last open modal --//
	$.fn.npModalDestroy = function(params) {
		if(params!=null)
		{
		  currentSettings.containerTarget = (params.containerTarget!=null && params.containerTarget!=currentSettings.containerTarget) ? params.containerTarget : currentSettings.containerTarget;
		  currentSettings.destroyOverlay = (params.destroyOverlay!=null && params.destroyOverlay) ? params.destroyOverlay : true;
		  currentSettings.animate = (params.animate!=null && params.animate) ? params.animate : false;
    }
		destroyModal();
	};
  
  function doModal(o)
  {
    c0 = "";
    c = "";
    c = o.containerTarget;
    
    var zIndex = 3000;
    var ov = $('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':zIndex-1,opacity:o.overlay/100 });
        
    if($(':has('+o.overlayClass+')').length==0)
      ov.addClass(o.overlayClass.substring(1,o.overlayClass.length)).prependTo('body');
    
    $(c).css({width:o.width,height:o.height,'z-index':zIndex}).appendTo('form');
        
    var cw = parseInt($(c).width(),10);
    var ch = parseInt($(c).height(),10);
    
    if(ie6){
      $('html,body').css({height:'100%',width:'100%','z-index':zIndex-1});      
      ov=ov.css({position:'absolute'});
      var pt = parseInt($(c).css('padding-top').replace('px',''), 10);
      var pb = parseInt($(c).css('padding-bottom').replace('px',''), 10);
      var pl = parseInt($(c).css('padding-left').replace('px',''), 10);
      var pr = parseInt($(c).css('padding-right').replace('px',''), 10);            
            
      var ifr = $('<iframe></iframe>').css({opacity:0,width:cw+pl+pr+'px',height:ch+pt+pb+'px',left:0,top:0,'z-index':'-1',position:'absolute'});
      $(c).prepend(ifr);   
    }
    
    //-- Get Window Height and position in middle --//
    var top = 0;    
    var h = getHeight();
    var s = getScroll();
        
    if(o.toTop) top = '15%'; else top = (s==0) ? ((h-ch) / 2): (((h-ch) / 2) + s);    
    $(c).css("top", top);
    
    //-- Get Window Width and position in middle --//
    var left = 0;    
    var w = getWidth();
    left = ((w-cw) / 2);
    $(c).css("left", left);
 
    if(o.enableDrag){ try{$(c).draggable({handle: o.dragClass}); $(o.dragClass).css({cursor:"move"})}catch(err){/*alert('Draggable Import Needed')*/}}
        
    if(o.isModal) $(o.overlayClass).css("display","block");
    else $(o.overlayClass).css("display","none");
    
    if(o.animate && !ie)
      $(c).fadeIn(); 
    else
      $(c).show();
    
    if (o.title!=false)
		$(c + ' ' + o.dragClass + " h1").text(o.title);
    
    if(o.ajax!=false)
    {
      $.ajax({
        type:"GET",
        url:o.ajax,
        success:function(data, textStatus){
           $(c+' '+o.targetClass).html(data);
           //-- adjust height --//
           ch = parseInt($(c).height(),10);
           if(!o.toTop){
            top = (s==0) ? ((h-ch) / 2): (((h-ch) / 2) + s);
              if(top<0) top=0;
                $(c).css("top", top);
           }
           //-- show --//
           if (o.animate && !ie) $(c).slideDown();
           else $(c).show();
        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
          alert('Error Loading \'' + o.ajax + '\'');
        }
      });
    }
    else
    {
      if(o.animate && !ie)
        $(c).fadeIn();
      else
        $(c).show();
    }
    
    if(o.sender!=null)
    {
      c0 = o.sender;
      if(o.toggleHide) $(c0).hide();
    }
    else
      c0 = c;
    
    //-- Adds container target id to the close class item and binds the destroy function --//
    $(c + ' ' + o.closeClass).attr('cid', o.containerTarget);
    $(c + ' ' + o.closeClass).attr('d', o.destroyOverlay);
    $(c + ' ' + o.closeClass).attr('a', o.animate);
    $(c + ' ' + o.closeClass).click(destroyModal);    
    //if(o.closeCallback!=null) $(c + ' ' + o.closeClass).attr('onclick', o.closeCallback);
    
    //-- Keydown of escape key closes the modal --//
    if(o.enableEscape) $(document).keydown(keyHandler);    
    if(o.isModal && o.enableOverlayClose) $(o.overlayClass).click(function(){destroyModal();});    
  }
  
  function destroyModal(e) 
  {
    var cbtn = $(this);
    var containerTarget = currentSettings.containerTarget;
    var d = currentSettings.destroyOverlay;
    var a = currentSettings.animate;    
    
    if(cbtn!=null)
    {
      containerTarget = (cbtn.attr('cid')!=null) ? cbtn.attr('cid') : containerTarget;
      //callback = (cbtn.attr('callback')!=null) ? cbtn.attr('callback') : null;
      d = ((cbtn.attr('d')!=null) && (cbtn.attr('d')=="false")) ? false : true;
      a = ((cbtn.attr('a')!=null) && (cbtn.attr('a')=="false")) ? false : true;
    }
    
    var o = currentSettings;
  
    var hasCallback = (o.closeCallback!=null) ? true : false;
    if(o.isModal && d) $(o.overlayClass).css("display","none");

    if(a && !ie)
    {
      if(hasCallback) $(containerTarget).fadeOut("normal", o.closeCallback);
      else $(containerTarget).fadeOut();
    }
    else
    {
      if(hasCallback) $(containerTarget).hide(1, o.closeCallback);
      else $(containerTarget).hide();
    }
    
    if(c0!=c && o.toggleHide)
    {
      c = containerTarget = c0;
      d = true;
      o.sender = null;
      
      if(o.animate && !ie)
        $(c0).fadeIn();
      else
        $(c0).show();
    }
  }
  
  function keyHandler(e) 
  {
		if (e.keyCode == 27) destroyModal();
  }
  
  function getHeight() {
    var h = 0;
    if( typeof( window.innerHeight ) == 'number' ) {
      h = window.innerHeight;
    } else if( document.documentElement && document.documentElement.clientHeight ) {
      h = document.documentElement.clientHeight;
    } else if( document.body && document.body.clientHeight ) {
      h = document.body.clientHeight;
    }
    return h;
  }

  function getWidth() {
    var w = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
      w = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth ) {
      w = document.documentElement.clientWidth;
    } else if( document.body && document.body.clientWidth ) {
      w = document.body.clientWidth;
    }
    return w;
  }

  function getScroll() {
    var s = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
      s = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      s = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      s = document.documentElement.scrollTop;
    }
    return s;
  }
  
})(jQuery);