/**
 * UploadEaseHelper.js (Version 1.4): Copyright (C) Firm Software Solutions, 2009.
 */

function ueAppletHelper( ps, debug ) {
  var a = undefined;
  var _ = this;
  var u = undefined;
  if (encodeURIComponent) {
    _.encode = encodeURIComponent; // Fixes 1.3.8
  } else {
    _.encode = escape;
  }
  // Helper
  _.H = function( ds, ps ) {
    var me = this;
    me.gp = function( ds, ps ) {
      var w = [];
      for (var p in ps) {
        var _p = '_'+p;
        if (ds[_p] == u) {
          if (debug && ds[p] == u) {
            w.push("'"+p+"' parameter is unknown");
          }
          ds[p] = ps[p];
        } else {
          ds[_p] = ps[p];
        }
      }
      if (w.length > 0) {
        _.dO("* "+w.join("\n* "), "WARNING:");
      }
      return ds;
    }
    me.sp = function( p, v ) {
      var _p = '_'+p;
      if (me.params[_p] != u) {
        p = _p;
      }
      if (me.params[p] != u) {
        var pt = typeof (me.params[p]);
        var vt = typeof (v);
        if (pt == 'object') {
          if (vt == 'string') {
            v = String(v).split(';');
          }
        } else if (pt == 'boolean') {
          if (vt == 'string') {
            v = !v.match(/(false|off|no)/i);
          } else if (vt == 'number') {
            v = (v != 0);
          }
        }
        me.params[p] = v;
      } else {
        if (debug) {
          _.dO("'"+p+"' parameter is unknown", "WARNING:");
        }
      }
      return me;
    }
    me.ap = function( p, v ) {
      var _p = '_'+p;
      if (me.params[_p] != u) {
        p = _p;
      }
      if (me.params[p] != u) {
        var pt = typeof (me.params[p]);
        var vt = typeof (v);
        if (pt == 'object') {
          if (vt == 'string') {
            v = String(v).split(';');
          } else if (vt != 'object') {
            v = [];
          }
          if (me.params[p].constructor == Array) {
            me.params[p] = me.params[p].concat(v);
          } else {
            for (var i in v) {
              me.params[p][i] = v[i];
            }
          }
        } else if (pt == 'string') {
          if (vt == 'object') {
            v = v.join(';');
          }
          me.params[p] += String(v);
        } else {
          me.params[p] = v;
        }
      } else {
        if (debug) {
          _.dO("'"+p+"' parameter is unknown", "WARNING");
        }
      }
      return me;
    }
    me.appendParam = me.ap;
    me.setParam = me.sp;
    me.params = me.gp(ds, ps);
    return me;
  }
  // Applet Helper
  _.AH = function( ps ) {
    var defs = {
      allowFolderUploads: false,
      acceptSelfSignedCertificates: false,
      _alt: '', // Alternate content to display if applet cannot be rendered
      appendParameterIndices: false, // Deprecated
      archive: 'UploadEase.jar',
      _boxbgcolor: null, // Whilst applet downloading
      _boxfgcolor: null, // Whilst applet downloading
      _boxmessage: null, // Whilst applet downloading
      _callbacks: {fileParams: false, onAbort: false, onFileUploaded: false, onUploadDone: false, uploadParams: false},
      _classid: 'CLSID:8AD9C840-044E-11d1-B3E9-00805F499D93',
      code: 'com.firmsoft.uploader.UploadEaseApplet',
      codebase: 'java/',
      compressionExclude: [],
      compressionInclude: [],
      compressionMethod: 'none', // none, zip, gzip
      cookiePolicy: '',
      _cookies: { /** See reference **/ },
      copyCookies: true,
      _debug: false,
      debugLevel: -1,
      exclude: [],
      fileIndexBase: 1,
      fileIndexPlaceholder: '#',
      hashAlgorithm: 'none', // none, md2, md5, sha
      hashExclude: [],
      hashInclude: [],
      _hashParameterName: '', // Deprecated
      _height: 450,
      _id: 'upload_ease',
      _image: null, // Whilst applet downloading
      imageAutoRotate: true, // if true uses Exif data to determine orientation and automatically rotate
      imageRotateButtons: true, // (+ to allow manual rotations, - to deny)
      images: [],
      include: [],
      lastFolderVisitedCookie: '',
      maxFileSize: 0,
      maxFileCount: 0,
      maxFilesPerRequest: 0,
      maxRedirects: 1,
      maxUploadSize: -1,
      mayscript: true, // 'yes' doesn't work on Macs.
      _name: 'UploadEase',
      _notesParameterName: '', // Deprecated
      _onUploadDone: '', // Deprecated
      _pathsParameterName: '', // Deprecated
      _progressbar: null, // Whilst applet downloading
      _progresscolor: null, // Whilst applet downloading
      _properties: { /** See reference **/ },
      rememberLastFolderVisited: false, // Deprecated
      rememberLastFolderVisitedCookieName: 'ueLastFolderVisited', // Deprecated
      restartFileIndices: true,
      scriptable: true,
      sessionID: '', // Deprecated
      sessionName: '', // Deprecated
      showHiddenFiles: false,
      tokens: [],
      uploadURL: '',
      _variables: {
        bundleGroupId: true, bundleCount: true, bundleIndex: true, bundleSize: true, bundleStart: true,
        totalFileCount: true, fileCount: true,
        fileHashes: false, fileNames: false, fileParams: false, fileParts: false, filePaths: false, fileCanonicalPaths: false
      },
      _width: 600
    };
    var me = new _.H(defs, ps);
    me.im = function( o, f ) {
      var x = [];
      for (var i in o) {
        var v = o[i];
        if (f && typeof(v) == 'boolean') {
          if (!v) {
            continue;
          } else {
            v = i;
          }
        }
        x.push(""+_.encode(i)+"="+_.encode(v));
      }
      return x.join(';');
    }
    me.gh = function() {
      var h = '';
      var _a = navigator.appName;
      if (_a == 'Netscape') {
         h += '<object type="application/x-java-applet"\n';
      }
      else if (_a == 'Microsoft Internet Explorer') {
          h += '<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"\n';
      }
      else {
         h += '<object type="application/x-java-applet"\n';
      }
      // Object attributes
      if (me.params._width != null) h += 'width="'+me.params._width+'"\n';
      if (me.params._height != null) h += 'height="'+me.params._height+'"\n';
      if (me.params._name != null) h += 'name="'+me.params._name+'"\n';
      if (me.params._id != null) h += 'id="'+me.params._id+'"\n';
      if (me.params._boxbgcolor != null) h += 'boxbgcolor="'+me.params._boxbgcolor+'"\n';
      if (me.params._boxfgcolor != null) h += 'boxfgcolor="'+me.params._boxfgcolor+'"\n';
      if (me.params._boxmessage != null) h += 'boxmessage="'+me.params._boxmessage+'"\n';
      if (me.params._image != null) h += 'image="'+me.params._image+'"\n';
      if (me.params._progressbar != null) h += 'progressbar="'+me.params._progressbar+'"\n';
      if (me.params._progresscolor != null) h += 'progresscolor="'+me.params._progresscolor+'"\n';

      h += '>\n';

      // Add params
      for (var p in me.params) {
        if (p.toString().charAt(0) != '_') {
          var v = me.params[p];
          if (v != null) {
            if (typeof (v) == 'object') {
              if (v.constructor == Array) {
                v = v.join(';');
              } else {
                v = me.im(v);
              }
            }
            h += '<param name="'+p+'" value="'+v+'">\n';
          }
        }
      }
      // Provide support for deprecated items...
      if (me.params.sessionName != '') {
        me.setSession(me.params.sessionName, me.params.sessionID);
      }
      if (me.params._onUploadDone != '') {
        me.setCallbacks({onUploadDone: me.params._onUploadDone});
      }
      if (me.params._hashParameterName != '') {
        me.setVariables({fileHashes: me.params._hashParameterName});
      }
      if (me.params._notesParameterName != '') {
        me.setVariables({fileParams: me.params._notesParameterName});
      }
      if (me.params._pathsParameterName != '') {
        me.setVariables({filePaths: me.params._pathsParameterName});
      }
      // Handle special params (callbacks, properties, variableNames)
      h += '<param name="callbacks" value="'+me.im(me.params._callbacks, true)+'">\n';
      h += '<param name="cookies" value="'+me.im(me.params._cookies, false)+'">\n';
      h += '<param name="properties" value="'+me.im(me.params._properties)+'">\n';
      h += '<param name="variables" value="'+me.im(me.params._variables, true)+'">\n';
      // Alternate content
      if (me.params._alt == '') {
        me.params._alt = "<div>"
          + "<h1>WARNING: Java does not appear to be installed or enabled in your browser!</h1>"
          + "<p><a target='_blank' href='http://UploadEase.com/'>UploadEase</a> is a Java file and image upload applet that requires Java to be installed and enabled "
          + "in your browser in order for it to function.</p>"
          + "<p>To test whether Java is working on your computer and for help on installing or enabling it "
          + "in your browser please visit the <a target='_blank' href='http://www.java.com/en/download/help/testvm.xml' "
          + "title='Get help installing or enabling Java (opens in a new window)'>"
          + "help pages at the Java website</a>."
          + "</p></div>"
          ;
      }
      h += me.params._alt;
      // Close Object
      h += '</object>\n';
      if (debug) {
        _.dO(h, "<h1>Embedding HTML</h1>");
      }
      return h;
    }
    me.addImage = function (i) {
      return me.ap('images', typeof(i) == 'object' ? i.ais() : i);
    }
    me.addImageDefaults = function (i) {
      return me.ap('images', typeof(i) == 'object' ? i.aid() : i);
    }
    me.addToken = function( t ) {
      return me.ap('tokens', t);
    }
    me.ImageHelper = function( ps ) {
      var defs = {
        callback: '',
        distort: false, // true | false
        enlarge: false, // true | false
        exif: '',
        _height: '',
        pad: '', // Colour specifier
        progressive: false, // true | false
        quality: '', // 0-10 | 'nn%' | '0.0' - '1.0': use quote except for 0-10
        raw: false, // true | false
        scaleHint: '', // smooth | fast | averaging | replicate
        tag: null, // suffix string
        type: '', // 'jpg', 'png' etc
        _width: '',
        _watermark: {}
      };
      var opts = _.clone(defs); // Clone
      var ich = new _.H(opts, ps);
      ich.defs = defs;
      ich.io = function( opts ) {
        var parts = [];
        var os = [];
        if (opts != u) {
          // +/-distort (- to preserve aspect ratio)
          // +/-enlarge (+ to allow upscaling)
          // +/-raw (+ indicates raw image & other options ignored)
          // pad=color (#xxx,#xxxxxx,black,blue,cyan,darkgray,gray,green,lightgray,magenta,orange,pink,red,white,yellow)
          // tag= (string to insert before image file type extension. If not provided WxH is the default)
          // type=(bmp|gif|jpg|png) (upload image in _ format)
          for (var o in opts) {
            if (!String(o).match(/^_/)) {
              var v = opts[o];
              if (v != ich.defs[o]) {
                var opt;
                if (typeof(v) == 'boolean') {
                  opt = (v ? '+' : '-') + o;
                } else {
                  opt = o+'='+v;
                }
                os.push(opt);
              }
            }
          }
        }
        parts.push(os.join(','));

        var wm = opts['_watermark'];
        if (wm != null) {
          var w = [];
          for (var i in wm) {
            w.push(i+"="+_.encode(wm[i]));
          }
          parts.push(w.join(','));
        }
        return parts.join(':');
      }
      ich.ais = function() {
        var p = [];
        p.push(ich.params['_width']+'x'+ich.params['_height']);
        p.push(ich.io(ich.params));
        return p.join(':');
      }
      ich.aid = function() {
        var p = [];
        p.push('');
        p.push(ich.io(ich.params));
        return p.join(':');
      }
      ich.asString = ich.ais;
      ich.setCallback = function(c) {
        ich.sp('callback', c);
        return ich;
      }
      ich.setProgressive = function(p) {
        ich.sp('progressive', p);
        return ich;
      }
      ich.setQuality = function(q) {
        ich.sp('quality', q);
        return ich;
      }
      ich.setSize = function(w,h) {
        ich.sp('width', w);
        ich.sp('height', h);
        return ich;
      }
      ich.setWatermark = function (w) {
        if (typeof(w) == 'object' && w.constructor != Array) {
          return ich.ap('_watermark', w);
        } else {
          if (debug) {
            _.dO("Expected object in setWatermark, got non-object or Array.", "ERROR");
          }
          return false;
        }
      }
      return ich;
    }
    me.setCallbacks = function( c ) {
      if (typeof(c) == 'object' && c.constructor != Array) {
        return me.ap('_callbacks', c);
      } else {
        if (debug) {
          _.dO("Expected object in setCallbacks, got non-object or Array.", "ERROR");
        }
        return false;
      }
    }
    me.setCompression = function( m, i, e ) {
      me.sp('compressionMethod', m || 'zip');
      me.sp('compressionInclude', i || []);
      me.sp('compressionExclude', e || []);
    }
    me.setCookies = function( c ) {
      if (typeof(c) == 'object') {
        return me.ap('_cookies', c);
      } else {
        if (debug) {
          _.dO("Expected object or array in setCookies, got scalar.", "ERROR");
        }
        return false;
      }
    }
    me.setFileFilter = function( i, e ) {
      me.sp('include', i || []);
      me.sp('exclude', e || []);
    }
    me.setHashing = function( a, n, i, e ) {
      me.sp('hashAlgorithm', a || 'MD5');
      //me.sp('hashParameterName', n || 'hash');
      me.sv({fileHashes: n || true});
      me.sp('hashInclude', i || []);
      me.sp('hashExclude', e || []);
    }
    me.setLastFolderVisitedCookie = function( x, p, d, n ) {
      var c = [n || me.params['rememberLastFolderVisitedCookieName']];
      if (x != u) {
        var t = typeof(x);
        var s;
        if (t == 'string') {
          s = (new Date(x)).toGMTString();
        } else if (t == 'object' && typeof(x.toGMTString) == 'function') {
          s = x.toGMTString();
        } else if (t == 'number') {
          var now = new Date() - 0;
          var then = new Date(now+x*1000);
          s = then.toGMTString();
        } else {
          s = null;
        }
        if (s != null) {
          c.push('expires='+s);
        }
      }
      if (p != u) {
        c.push('path='+p);
      }
      if (d != u) {
        c.push('domain='+d);
      }
      me.sp('lastFolderVisitedCookie', c.join(';'));
    }
    me.setProperties = function( p ) {
      if (typeof(p) == 'object' && p.constructor != Array) {
        return me.ap('_properties', p);
      } else {
        if (debug) {
          _.dO("Expected object in setProperties, got non-object or Array.", "ERROR");
        }
        return false;
      }
    }
    me.setSession = function( n, i ) {
      var a = new Array();
      a[n] = i;
      me.setCookies(a);
    }
    me.sv = function( v ) {
      if (typeof(v) == 'object' && v.constructor != Array) {
        return me.ap('_variables', v);
      } else {
        if (debug) {
          _.dO("Expected object in setVariables, got non-object or Array.", "ERROR");
        }
        return false;
      }
    }
    me.setVariables = me.sv;
    me.write = function () {
      document.write(me.gh());
      a = document.getElementById(me.params['_id']);
    }

    // Callable applet methods...
    me.getSelectedFileCount = function () { return a ? a.getSelectedFileCount() : null; }
    me.setBusy = function ( busy, msg ) { if (a) a.setBusy(busy,msg); }
    me.uploadShouldAbort = function () { return a ? a.uploadShouldAbort() : null; }
    me.uploadWillAbort = function () { if (a) a.uploadWillAbort(); }
    me.uploadShouldBegin = function () { return a ? a.uploadShouldBegin() : null; }
    me.uploadWillBegin = function () { if (a) a.uploadWillBegin(); }

    return me;
  }

  _.clone = function (o, deep) {
    var c = new o.constructor();
    for (var p in o) {
      if (o[p] == o) {
        c[p] = c;
      } else if (!deep) {
        c[p] = o[p];
      } else if (typeof o[p] == 'object') {
        c[p] = o[p].clone(deep);
      } else {
        c[p] = o[p];
      }
    }
    return c;
  }

  _.dDoc = null;
  _.di = function () {
    if (_.dDoc == null) {
      _.dDoc = window.open("", "ueDebugWindow").document;
      _.dDoc.title = "UploadEase Debug Window";
      _.dDoc.writeln("<html><head><style type='text/css'>html,body {font-family:sans-serif;}</style></head><body>");
    }
  }
  _.dO = function ( s, t ) {
    if (_.dDoc) {
      if (t) {
        _.dDoc.writeln('<h1>'+t+'</h1>');
      }
      _.dDoc.writeln('<pre>'+s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")+'</pre>');
    }
  }

  if (debug) {
    _.di();
  }
  return new _.AH(ps);
}