//-----------------------------------------------------------------------
// Module name   : LmooPopup
// Author        : Paul Battersby
// Creation Date : Sept 11/08
//
// This is basically a wrapper for window.open
//
//  This origially came from CNET popup.js
//
//  Script: Popup.js
//    Defines the Popup class useful for making popup windows.
//
//  License:
//    http://clientside.cnet.com/wiki/cnet-libraries#license
//
//  Usage :
//     var myPopup = new LmooPopup('http://www.mootools.net',{
//       width: 500,
//       height: 600
//    });
//
//    myPopup.openWin();
//
//               --- OR ---
//
//     var myPopup = new LmooPopup(null,{
//       width: 500,
//       height: 600
//    });
//
//    myPopup.openWin('http://www.mootools.net');
//
//  NOTE:
//    By passing a parameter through the url, like this:
//
//     var myPopup = new LmooPopup('myChildPopup.php?callback=mainFunc',{
//       width: 500,
//       height: 600
//    });
//
//    We can callback a function in the parent of the popup.
//
//    In the popup, use
//      var args = LmooPopup.getQueryArgs();
//
//    to get the name of the callback function, then use
//
//      LmooPopup.callback(args["callback"],val1,val2);
//
//    to call the callback function with (for example) 2 parameters
//
//  NOTE:
//    If the popup is going to do something clever like POST a form back to
//    itself before calling the callback function, be sure to call the following:
//
//      LmooPopup.addQueryStringToFormAction("myFormId");
//
//    and be sure the method is POST, not GET
//
//  $Log: lmoopopup.js $
//  Revision 1.10  2009-10-31 15:26:58-04  Battersby
//  - added   "Implements: [Events, Options]" for use with latest mootools
//
//  Revision 1.9  2009-05-01 13:00:19-04  Battersby
//  - constructor no longer opens a popup window
//
//  Revision 1.8  2009-01-15 18:15:35-04  Battersby
//  - focus(), close(), openWin() no longer return an object. It causes problems in
//  javascript links
//
//  Revision 1.7  2009-01-15 18:12:00-04  Battersby
//  - added getScreenSize()
//
//  Revision 1.6  2008-12-22 13:00:00-04  Battersby
//  - moved some code around
//  - added usage info
//
//  Revision 1.5  2008-12-12 16:24:53-04  Battersby
//  - passes jsLint test
//
//  Revision 1.4  2008-10-06 14:16:42-04  Battersby
//  - added addQueryStringToFormAction()
//
//  Revision 1.3  2008-09-29 18:31:51-04  Battersby
//  - added getQueryArgs(), callback() and close() methods
//
//  Revision 1.2  2008-09-18 12:55:06-04  Battersby
//  - scrollbars was set to 'auto' but needed to be set to 1 or 0
//
//  Revision 1.1  2008-09-17 12:42:18-04  Battersby
//  Initial revision
//
//------------------------------------------------------------------------

//---------------------------- INCLUDE FILES -----------------------------

var LmooPopup = new Class({
  Implements: [Events, Options],

//----------------------------- CONSTANTS --------------------------------


//----------------------------- VARIABLES --------------------------------

  options: {
    width: 500,         // start width
    height: 300,        // start height
    x: -1,              // start position -1 = centered
    y: -1,              // start position -1 = centered
    toolbar: 0,         // 1 = include toolbar
    location: 0,        // 1 = show location bar
    directories: 0,     // 1 = show Netscape "What's New" type buttons
    status: 0,          // 1 = show status bar
    scrollbars: 1,      // 1 = show scroll bars if needed, 0 = no scroll bars even if needed
    resizable: 1,       // 1 = window is resizable
    name: 'popup',      // name of the window (more like an id, this is not a title)

    onBlock : Class.empty
	},

  focusTries: 0,
	blocked: null,

//----------------------------- FUNCTIONS --------------------------------

  focus: function() {
    if (this.window) {
      this.window.focus();
    } else if (this.focusTries<10) {
      this.focus.delay(100, this); //try again
    } else {
			this.blocked = true;
			this.fireEvent('onBlock');
		}
//    return this;
	},


  close: function(){
		this.window.close();
//    return this;
  },

  openWin: function(url){
		url = url || this.url;
		var options = 'toolbar='+this.options.toolbar+
			',location='+this.options.location+
			',directories='+this.options.directories+
			',status='+this.options.status+
			',scrollbars='+this.options.scrollbars+
			',resizable='+this.options.resizable+
			',width='+this.options.width+
			',height='+this.options.height+
			',top='+this.options.y+
			',left='+this.options.x;

    // NOTE: this.options.name is not a title but more like a variable name
    //       by which this window can be referred in the future
    this.window = window.open(url, this.options.name, options);
		if (!this.window) {
			this.window = window.open('', this.options.name, options);
			this.window.location.href = url;
		}
		this.focus.delay(100, this);
//    return this;
	},

  //************************************************************************
  // Name   : initialize (constructor)
  //
  //  (string) url     - (optional) indicates the url to be used when the window
  //                     is opened
  //  (object) options - (optional) configuration options. See options declaration
  //                     above for the available options
  //
  //  NOTE: The object you get back, the instance of the LmooPopup class,
  //        has a few useful properties.
  //
  //        .focus() focuses the popup,
  //        .close() will close the popup, and
  //        .window is the window element itself
  //
  //  See javascript documentation for window.open() for more info
  //
  // Returns : (nothing)
  //*************************************************************************
  initialize : function(url,options) {
    this.url = url || false;
    this.setOptions(options);

    // if window is to be horiontally centered
    if ( this.options.x == -1 ) {
      this.options.x = (screen.width  - this.options.width) / 2;
    } // endif

    // if window is to be vertically centered
    if ( this.options.y == -1 ) {
      this.options.y = (screen.height - this.options.height) / 2;
    } // endif

  }

});

//************************************************************************
// Name   : getQueryArgs (static)
//
// This retrieves the parameters what were passed to the current web page
//  or that were given in the optional url parameter
//
// <!-- Original:  Doug Lawson (dlawson@clark.net) -->
//
// <!-- This script and many more are available free online at -->
// <!-- The JavaScript Source!! http://javascript.internet.com -->
//
// Returns : (object) args - a structure of arguements input from the
//                           document location string has been returned to
//                           the caller.
//
//  For example, if the url is:
//      clicktst.htm?value1=1&value2=3
//
//  And we do this:
//      args = LmooPopup.getQueryArgs();
//
//  then this function will return
//      args.value1
//      args.value2
//
//  set to
//      1, 3
//************************************************************************
LmooPopup.getQueryArgs = function() {
  // gets the arguments the page was loaded with - that is,
  // everything after the first '?'
  //
  // values are ALWAYS case sensitive

  // use the url of the current web page
  url = window.location;

  var args  = new Object();
  var query = unescape(url.search.substring(1));
  var pairs = query.split("&");

  // store the full query string
  args["queryString"] = query;

  for (var i = 0; i< pairs.length; i++) {
    pairs[i]= unescape(pairs[i]);
    var pos=pairs[i].indexOf('=');

    if(-1 == pos) {continue;}

    var argname;
    argname = pairs[i].substring(0,pos);

    var value = pairs[i].substring(pos+1);
    args[argname] = value;
  }
  return args;

};

//************************************************************************
// Name   : callback (static)
//  This calls the given callback function with an arbitrary list of
//  parameters
//
//  (string) callbackFn - the name of a function from the opener of the current
//                        web page that is to be called
//  (arguments) arguments - as many function parameters as are needed by
//                          the callbackFn
//
//  Usage:
//   LmooPopup.callback("myClass.method","some string",5)
//
//  The above example will call the following class method in the opener
//  window:
//
//    myClass.method("some string",5);
//
// This will work with any arbitrary function or method that exists in
// the opener window
//
// Returns : (nothing)
//************************************************************************
LmooPopup.callback = function(callbackFn) {
  var params = [];


  // convert the arguments object into an array so we can work with it
  // NOTE: skipping the first arguement because it's the callbackFn name
  for ( var i=1; i < arguments.length; i++ ) {
    params[i-1] = arguments[i];

    // if the argument is a string, surround it with quotes
    if ( $type(params[i-1]) == "string" ) {
      params[i-1] = "'" + params[i-1] + "'";
    } // endif
  } // end for

  // call the callback function with the parameter list
  eval("opener." + callbackFn + "(" + $splat(params) + ")");
};

//************************************************************************
// Name   : addQueryStringToFormAction (static)
//  This takes the arguments that were part of the url the current web page
//  and appends them to the given form's action parameter
//
//    (mixed) formId - form id or form obj whose action parameter is to be
//                     altered
//
// Returns : (nothing)
//************************************************************************
LmooPopup.addQueryStringToFormAction = function(formId) {
  $(formId).setProperty("action",$(formId).getProperty("action") + "?" + unescape(window.location.search.substring(1)));
};

//************************************************************************
// Name   : getScreenSize (static)
//  This returns an array with width and height of the screen. This is
//  useful for customizing the size of the popup window to be relative
//  to the size of the screen
//
// Returns : (object) {width : widthOfScreen, height : heightOfScreen}
//************************************************************************
LmooPopup.getScreenSize = function() {
  return {width:screen.width,height:screen.height};
};

//************************************************************************
// Name   : close (static)
//  This closes the given window object or closes the current window
//
//  (window object) windowObj - (optional) the window object to be closed.
//                              Likely the return value from the LmooPopup
//                              constructor. If this parameter is not given,
//                              the current window will be closed
//
// Returns : (nothing)
//************************************************************************
LmooPopup.close = function(windowObj) {

  // if a window object was given, close it
  if ( windowObj ) {
    windowObj.close();

  // close the current window
  } else {
    window.close();
  } // endif
};


