/**
 * PluginAutoLoad: Load your plugins on html DOM without javascript code.
 * http://marcbuils.github.com/jquery.pluginautoload/
 * https://github.com/leiming/jquery.loadscript
 *
 * Par Marc Buils ( marc.buils@marcbuils.fr )
 * Lei Ming ( poetcoders@gmail.com )
 * Sous licence LGPL v3 (http://www.gnu.org/licenses/lgpl-3.0.txt)
 *
 * v0.1.1 - 09/16/2015:
 * First release
 *
 * v0.1.2 - 12/09/2015;
 * Fix lazyLoad bug
 */
// lazyload script
// ref: http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
var _loadScript = function (url, params, callback) {

  var script = document.createElement("script");
  script.type = "text/javascript";

  if (script.readyState) { //IE
    script.onreadystatechange = function () {
      if (script.readyState == "loaded" || script.readyState == "complete") {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else { //Others
    script.onload = function () {
      callback();
    };
  }

  var scriptsProperties = [
    'type', 'src', 'htmlFor', 'event', 'charset', 'async', 'defer', 'crossOrigin', 'text', 'onerror'
  ];

  if (typeof params === 'object' && !jQuery.isEmptyObject(params)) {
    for (var key in params) {
      if (params.hasOwnProperty(key) && jQuery.inArray(key, scriptsProperties)) {
        script[key] = params[key];
      }
    }
  }

  //当设置script的text属性时，需要在加载script DOM节点前设置src属性，否则会执行text文本内容
  script.src = url;
  document.getElementsByTagName(params['lazyLoad'] ? 'body' : 'head')[0].appendChild(script);
};

jQuery.loadScript = function (p_url, p_params, p_callback) {

  // Handle p_params is exist
  if (arguments.length === 2 && typeof arguments[1] === 'function') {
    p_callback = arguments[1];
    p_params = {}
  }

  p_params = p_params || {};

  var _return = jQuery.Deferred();

  // Call callback if necessary
  if (typeof( p_callback ) === 'function') {
    _return.done(function () {
      p_callback();
    });
  }

  // Load javascript file
  _loadScript(p_url, p_params, function () {
    _return.resolve();
  });

  return _return.promise();
};
