Intialize the dropzone component with element and form url to provide a
dnd feature for the file upload.
773058
protected void initDropzone(Element e, Element template, String previews, Element uploadPreview, Element uploadedFiles) {
        JQueryElement previewNode = $(template);
        previewNode.asElement().setId("");
        String previewTemplate = previewNode.parent().html();
        options.previewTemplate = previewTemplate;
        options.previewsContainer = "#" + previews;
        uploader = new Dropzone(e, options);

        uploader.on(FileUploaderEvents.DROP, event -> {
            fireDropEvent();
            if (preview) {
                $(e).removeClass(CssName.ACTIVE);
            }
            return true;
        });

        uploader.on(FileUploaderEvents.DRAG_START, event -> {
            DragStartEvent.fire(this);
            return true;
        });

        uploader.on(FileUploaderEvents.DRAG_END, event -> {
            DragEndEvent.fire(this);
            return true;
        });

        uploader.on(FileUploaderEvents.DRAG_ENTER, event -> {
            DragEnterEvent.fire(this, null);
            if (preview) {
                $(e).addClass(CssName.ACTIVE);
            }
            return true;
        });

        uploader.on(FileUploaderEvents.DRAG_OVER, event -> {
            DragOverEvent.fire(this);
            return true;
        });

        uploader.on(FileUploaderEvents.DRAG_LEAVE, event -> {
            DragLeaveEvent.fire(this, null);
            if (preview) {
                $(e).removeClass(CssName.ACTIVE);
            }
            return true;
        });

        uploader.on(FileUploaderEvents.ADDED_FILE, file -> {
            AddedFileEvent.fire(this, convertUploadFile(file));
            totalFiles++;

            if (isPreview()) {
                $(uploadedFiles).html("Uploaded files " + totalFiles);
                getUploadPreview().getUploadHeader().getProgress().setPercent(0);
                getUploadPreview().setVisibility(Style.Visibility.VISIBLE);
            }
        });

        uploader.on(FileUploaderEvents.REMOVED_FILE, file -> {
            RemovedFileEvent.fire(this, convertUploadFile(file));
            totalFiles -= 1;
            $(uploadedFiles).html("Uploaded files " + totalFiles);

            if (totalFiles == 0 && isPreview()) {
                getUploadPreview().setVisibility(Style.Visibility.HIDDEN);
            }
        });

        uploader.on("error", (file, response) -> {
            int code = 200;
            String statusText = "";

            if (file.xhr != null) {
                code = file.xhr.status;
                statusText = file.xhr.statusText;
            }

            String body = "";

            if (response instanceof String) {
                body = (String)response;
            } else {
                statusText = getResponseMessage(response);
            }

            if (code == 401) {
                statusText = statusText.isEmpty() ? "Unauthorized. Your session may have expired. Log in and try again." : statusText;
                globalResponse = response;
                UnauthorizedEvent.fire(this, convertUploadFile(file), new UploadResponse(code, statusText, body));
            }

            if (code == 404) {
                statusText = statusText.isEmpty() ? "There is a problem uploading your file." : statusText;
                globalResponse = response;
            }

            if (code == 500) {
                statusText = statusText.isEmpty() ? "There is a problem uploading your file." : statusText;
                globalResponse = response;
            }


            ErrorEvent.fire(this, convertUploadFile(file), new UploadResponse(code, statusText, body));
        });

        uploader.on(FileUploaderEvents.TOTAL_UPLOAD_PROGRESS, (progress, file, response) -> {
            TotalUploadProgressEvent.fire(this, progress);
            if (isPreview()) {
                getUploadPreview().getUploadHeader().getProgress().setPercent(progress);
            }
        });

        uploader.on(FileUploaderEvents.UPLOAD_PROGRESS, (progress, file, response) -> {
            CurrentUploadProgressEvent.fire(this, progress);
            if ($this != null) {
                $this.find(".progress .determinate").css("width", progress + "%");
            }
        });

        uploader.on(FileUploaderEvents.SENDING, file -> {
            SendingEvent.fire(this, convertUploadFile(file),
                    new UploadResponse(file.xhr.status, file.xhr.statusText));
        });

        uploader.on(FileUploaderEvents.SUCCESS, (file, response) -> {
            globalResponse = response;
            String message = getResponseMessage(response);
            SuccessEvent.fire(this, convertUploadFile(file),
                    new UploadResponse(file.xhr.status, file.xhr.statusText, message));
        });

        uploader.on(FileUploaderEvents.COMPLETE, file -> {
            String message = getResponseMessage(globalResponse);
            CompleteEvent.fire(this, convertUploadFile(file),
                    new UploadResponse(file.xhr.status, file.xhr.statusText, message));
        });

        uploader.on(FileUploaderEvents.CANCELED, file -> {
            CanceledEvent.fire(this, convertUploadFile(file));
        });

        uploader.on(FileUploaderEvents.MAX_FILES_REACHED, file -> {
            MaxFilesReachedEvent.fire(this, convertUploadFile(file));
        });

        uploader.on(FileUploaderEvents.MAX_FILES_EXCEEDED, file -> {
            MaterialToast.fireToast("You have reached the maximum files to be uploaded.");
            MaxFilesExceededEvent.fire(this, convertUploadFile(file));
        });
    }
1071245
function onDroppableReturnedDefaultAnnouncement({dragEvent, dropzone}) {
  const sourceText = dragEvent.source.textContent.trim() || dragEvent.source.id || 'draggable element';
  const dropzoneText = dropzone.textContent.trim() || dropzone.id || 'droppable element';

  return `Returned ${sourceText} from ${dropzoneText}`;
}
871906
function generateDropZones() {
    $ColGroupContainer
      .find(DROP_ZONE).remove().end() // ensure no drop zone exists
      .find('li').each(function (idx) {
        const $this = $(this)
        $this
          .attr('draggable', 'true')
          .attr('source-idx', idx)
          .before(
            dropZoneGen(
              $this.is('li:first-of-type') ? idx - 0.25 : idx
            )
          )

        $this.is('li:last-of-type') && $this.after(dropZoneGen(idx + 0.25))
      })
  }
122868
protected function InitForm()
    {
        $this->logout = $this->LoadElement();
        $this->AddNextUrlField();
        $this->AddCssIDField();
        $this->AddCssClassField();
        $this->AddTemplateField();
        $this->AddSubmit();
    }
1078616
function (dragElement) {
            // get dropzones and their elements that could receive the draggable
            var possibleDrops = this.collectDrops(dragElement, true);

            this.activeDrops.dropzones = possibleDrops.dropzones;
            this.activeDrops.elements  = possibleDrops.elements;
            this.activeDrops.rects     = [];

            for (var i = 0; i < this.activeDrops.dropzones.length; i++) {
                this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]);
            }
        }
142954
function() {

      var x, dz, arr, card, list, item, path, url, title, description,
        params, xhr, value, el, options;

      // check for dropzone
      if(Dropzone != undefined && Dropzone != null) {

        // set dropzone options
        var options = {
          url: hashedit.uploadUrl
        };

        // setup token headers
        if(hashedit.useToken == true) {
          options.headers = {};
          options.headers[hashedit.authHeader] = hashedit.authHeaderPrefix + ' ' + localStorage.getItem(hashedit.tokenName);
        }

        // create the dropzone
        dz = new Dropzone("#hashedit-dropzone", options);

        dz.on("complete", function(file) {
          dz.removeFile(file);
        });

        dz.on("success", function(file, response) {

          var value = 'files/' + file.name;

          // set value
          el = document.getElementById('hashedit-image-src');
          el.value = value;

          // add item to list
          list = document.getElementById('images-list');

          item = document.createElement('div');
          item.setAttribute('class', 'hashedit-list-item');
          item.innerHTML = 'images/' + value;
          item.setAttribute('data-value', 'images/' + value);

          list.appendChild(item);

          // fire input event
          el.dispatchEvent(new Event('input', {
            'bubbles': true
          }));

          // flip card
          card = document.getElementById('hashedit-image-settings-modal');
          card.removeAttribute('hashedit-card-flipped');

        });

      }

      // handle click on images list
      list = document.getElementById('images-list');

      ['click'].forEach(function(e) {
        list.addEventListener(e, function(e) {

          if (e.target.hasAttribute('data-value') === true) {
            value = e.target.getAttribute('data-value');

            // set value
            el = document.getElementById('hashedit-image-src');
            el.value = value;

            // fire input event
            el.dispatchEvent(new Event('input', {
              'bubbles': true
            }));

            // flip card
            card = document.getElementById(
              'hashedit-image-settings-modal');
            card.removeAttribute('hashedit-card-flipped');
          }

        });
      });

      // handle click on images list
      list = document.getElementById('pages-list');

      ['click'].forEach(function(e) {
        list.addEventListener(e, function(e) {

          if (e.target.hasAttribute('data-value') === true) {
            value = e.target.getAttribute('data-value');

            // set value
            el = document.getElementById('hashedit-link-href');
            el.value = value;

            // fire input event
            el.dispatchEvent(new Event('input', {
              'bubbles': true
            }));

            // flip card
            card = document.getElementById('hashedit-link-settings-modal');
            card.removeAttribute('hashedit-card-flipped');
          }

        });
      });

      // setup config events
      arr = document.querySelectorAll('.toggle-select-image');

      for (x = 0; x < arr.length; x += 1) {

        // delegate on .hashedit-config
        ['click'].forEach(function(e) {

          arr[x].addEventListener(e, function(e) {

            // flip the card
            card = document.querySelector(
              '#hashedit-image-settings-modal');

            if(card.hasAttribute('hashedit-card-flipped')) {
              card.removeAttribute('hashedit-card-flipped');
            } else {
              card.setAttribute('hashedit-card-flipped', 'true');
            }

            if (hashedit.imagesListLoaded === false) {

              // set default auth
              var obj = {
                credentials: 'include'
              }

              // enable token based auth
              if(hashedit.useToken) {

                // set obj headers
                obj = {
                  headers: {}
                };

                obj.headers[hashedit.authHeader] = hashedit.authHeaderPrefix + ' ' + localStorage.getItem(hashedit.tokenName);
              }

              // load the images
              fetch(hashedit.imagesListUrl, obj)
                .then(function(response) {

                  return response.json();

                }).then(function(json) {

                  list = document.getElementById('images-list');
                  list.innerHTML = '';

                  for (x = 0; x < json.length; x += 1) {
                    item = document.createElement('div');
                    item.setAttribute('class',
                      'hashedit-list-item');
                    item.innerHTML = json[x];
                    item.setAttribute('data-value', json[x]);

                    list.appendChild(item);
                  }

                  hashedit.imagesListLoaded = true;

                }).catch(function(ex) {
                  console.log('parsing failed', ex);
                });
            }

          });

        });
      }

      // setup config events
      arr = document.querySelectorAll('.toggle-select-url');

      for(x = 0; x < arr.length; x += 1) {

        // delegate on .hashedit-config
        ['click'].forEach(function(e) {

          arr[x].addEventListener(e, function(e) {

            // flip the card
            card = document.querySelector('#hashedit-link-settings-modal');

            if(card.hasAttribute('hashedit-card-flipped')) {
              card.removeAttribute('hashedit-card-flipped');
            }
            else {
              card.setAttribute('hashedit-card-flipped', 'true');
            }

            if(hashedit.pagesListLoaded === false) {

              // set default auth
              var obj = {
                credentials: 'include'
              }

              // enable token based auth
              if(hashedit.useToken) {

                // set obj headers
                obj = {
                  headers: {}
                };

                obj.headers[hashedit.authHeader] = hashedit.authHeaderPrefix + ' ' + localStorage.getItem(hashedit.tokenName);
              }

              // load the pages
              fetch(hashedit.pagesListUrl, obj)
                .then(function(response) {

                  return response.json();

                }).then(function(json) {

                  list = document.getElementById('pages-list');
                  list.innerHTML = '';

                  for (x = 0; x < json.length; x += 1) {
                    item = document.createElement('div');
                    item.setAttribute('class', 'hashedit-list-item');
                    item.innerHTML = json[x].url;
                    item.setAttribute('data-value', json[x].url);

                    list.appendChild(item);
                  }

                  hashedit.pagesListLoaded = true;

                }).catch(function(ex) {
                  console.log('parsing failed', ex);
                });


            }

          });

        });
      }

    }
1290276
protected function submitAddZone()
    {
        $this->setSubmitted(null, $this->getParam());
        $this->validateComponent('zone');
        $this->addZone();
    }
311658
protected function InitForm()
    {
        $this->htmlWrap = $this->LoadElement();
        $name = 'Html';
        $this->AddRichTextField($name, $this->htmlWrap->GetHtml());
        $this->AddCssClassField();
        $this->AddCssIDField();
        $this->AddSubmit();
    }
1199468
@Override
	public void dragAndDrop(IElement element) throws WidgetException {
		try {
			Actions builder = new Actions(getGUIDriver().getWrappedDriver());
	        synchronized (InteractiveElement.class) {
	            getGUIDriver().focus();
	            builder.dragAndDrop(this.getWebElement(),
	            		new InteractiveElement(element.getByLocator()).getWebElement()).build().perform();
	        }
		} catch (Exception e) {
			throw new WidgetException(
					"Error while performing drag and drop from " + getByLocator()
							+ " to " + element.getByLocator(), getByLocator(), e);
		}
	}
1248763
function(data, options) {

        var $target = this.target , id = $target.getAttribute('id');
        var $form = instance.$forms[id] || this;

        // forward callback to HTML attribute
        listenToXhrEvents($form);

        if (options) {
            var options = merge(options, xhrOptions);
        } else {
            var options = xhrOptions;
        }

        var url         = $target.getAttribute('action') || options.url;
        var method      = $target.getAttribute('method') || options.method;
        method          = method.toUpperCase();
        options.method  = method;
        options.url     = url;

        // to upload, use `multipart/form-data` for `enctype`
        var enctype = $target.getAttribute('enctype');

        if ( options.withCredentials ) {

            if ('withCredentials' in xhr) {
                // XHR for Chrome/Firefox/Opera/Safari.
                if (options.isSynchrone) {
                    xhr.open(options.method, options.url, options.isSynchrone)
                } else {
                    xhr.open(options.method, options.url)
                }
            } else if ( typeof XDomainRequest != 'undefined' ) {
                // XDomainRequest for IE.
                xhr = new XDomainRequest();
                xhr.open(options.method, options.url);
            } else {
                // CORS not supported.
                xhr = null;
                var result = 'CORS not supported: the server is missing the header `"Access-Control-Allow-Credentials": true` ';
                triggerEvent(gina, $target, 'error.' + id, result);

                return
            }

            xhr.withCredentials = true;
        } else {
            if (options.isSynchrone) {
                xhr.open(options.method, options.url, options.isSynchrone)
            } else {
                xhr.open(options.method, options.url)
            }
        }

        // setting up headers
        for (var hearder in options.headers) {
            if ( hearder == 'Content-Type' && typeof (enctype) != 'undefined' && enctype != null && enctype != '') {
                options.headers[hearder] = enctype
            }

            xhr.setRequestHeader(hearder, options.headers[hearder]);
        }

        if (xhr) {
            // catching ready state cb
            xhr.onreadystatechange = function (event) {

                if (xhr.readyState == 4) {
                    // 200, 201, 201' etc ...
                    if( /^2/.test(xhr.status) ) {

                        try {
                            var result = xhr.responseText;
                            if ( /json$/.test( xhr.getResponseHeader("Content-Type") ) ) {
                                result = JSON.parse(xhr.responseText)
                            }

                            $form.eventData.success = result;

                            var XHRData = result;
                            if ( gina && typeof(window.ginaToolbar) == "object" && XHRData ) {
                                try {

                                    if ( typeof(XHRData) != 'undefined' ) {
                                        window.ginaToolbar.update("data-xhr", XHRData);
                                    }

                                } catch (err) {
                                    throw err
                                }
                            }

                            triggerEvent(gina, $target, 'success.' + id, result)

                        } catch (err) {
                            var result = {
                                status:  422,
                                error : err.message,
                                stack : err.stack

                            };

                            $form.eventData.error = result;

                            // // update toolbar
                            // var XHRData = result;
                            // if ( gina && typeof(window.ginaToolbar) == "object" && XHRData ) {
                            //     try {
                            //
                            //         // forward backend appplication errors to forms.errors when available
                            //         if ( XHRData.error && typeof(XHRData.error) == 'object' && $form.fields ) {
                            //             var formsErrors = {}, errCount = 0;
                            //             for (var e in XHRData.error) {
                            //                 if ( typeof($form.fields[e]) != 'undefined' ) {
                            //                     ++errCount;
                            //                     formsErrors[e] = XHRData.error[e];
                            //
                            //                     if ( typeof(XHRData.stack) != 'undefined' )
                            //                         formsErrors[e].stack = XHRData.stack;
                            //                 }
                            //             }
                            //
                            //             if (errCount > 0) {
                            //                 handleErrorsDisplay($form.target, formsErrors);
                            //             }
                            //         }
                            //         // update toolbar
                            //         ginaToolbar.update("data-xhr", XHRData );
                            //
                            //     } catch (err) {
                            //         throw err
                            //     }
                            // }

                            var XHRData = result;
                            if ( gina && typeof(window.ginaToolbar) == "object" && XHRData ) {
                                try {

                                    if ( typeof(XHRData) != 'undefined' ) {
                                        window.ginaToolbar.update("data-xhr", XHRData);
                                    }

                                } catch (err) {
                                    throw err
                                }
                            }

                            triggerEvent(gina, $target, 'error.' + id, result)
                        }

                    } else if ( xhr.status != 0) {

                        var result = { 'status': xhr.status };

                        if ( /^(\{|\[).test( xhr.responseText ) /) {

                            try {
                                result = JSON.parse(xhr.responseText);
                            } catch (err) {
                                result = merge(result, err)
                            }

                        } else if ( typeof(xhr.responseText) == 'object' ) {
                            result = xhr.responseText
                        } else {
                            result.message = xhr.responseText
                        }

                        $form.eventData.error = result;

                        // update toolbar
                        var XHRData = result;
                        if ( gina && typeof(window.ginaToolbar) == "object" && XHRData ) {
                            try {

                                // forward backend appplication errors to forms.errors when available
                                if ( XHRData.error && typeof(XHRData.error) == 'object' && $form.fields ) {
                                    var formsErrors = {}, errCount = 0;
                                    for (var e in XHRData.error) {
                                        if ( typeof($form.fields[e]) != 'undefined' ) {
                                            ++errCount;
                                            formsErrors[e] = XHRData.error[e];

                                            if ( typeof(XHRData.stack) != 'undefined' )
                                                formsErrors[e].stack = XHRData.stack;
                                        }
                                    }

                                    if (errCount > 0) {
                                        handleErrorsDisplay($form.target, formsErrors);
                                    }
                                }
                                // update toolbar
                                ginaToolbar.update('data-xhr', XHRData );

                            } catch (err) {
                                throw err
                            }
                        }

                        triggerEvent(gina, $target, 'error.' + id, result)
                    }
                }
            };

            // catching request progress
            xhr.onprogress = function(event) {
                // console.log(
                //    'progress position '+ event.position,
                //    '\nprogress total size '+ event.totalSize
                // );

                var percentComplete = (event.position / event.totalSize)*100;
                var result = {
                    'status': 100,
                    'progress': percentComplete
                };

                $form.eventData.onprogress = result;

                triggerEvent(gina, $target, 'progress.' + id, result)
            };

            // catching timeout
            xhr.ontimeout = function (event) {
                var result = {
                    'status': 408,
                    'error': 'Request Timeout'
                };

                $form.eventData.ontimeout = result;

                triggerEvent(gina, $target, 'error.' + id, result)
            };


            // sending
            if (!data)
                data = event.detail.data;

            if (data) {
                if ( typeof(data) == 'object' ) {
                    try {
                        data = JSON.stringify(data)
                    } catch (err) {
                        triggerEvent(gina, $target, 'error.' + id, err)
                    }
                }
                //console.log('sending -> ', data);
                //try {
                    xhr.send(data)
                // } catch (err) {
                //     var XHRData = result;
                //     if ( gina && typeof(window.ginaToolbar) == "object" && XHRData ) {
                //         try {
                //
                //             if ( typeof(XHRData) != 'undefined' ) {
                //                 window.ginaToolbar.update("data-xhr", XHRData);
                //             }
                //
                //         } catch (err) {
                //             throw err
                //         }
                //     }
                // }

            } else {
                xhr.send()
            }
            $form.sent = true;


        }
    }
881322
function() {
            var DDM = YAHOO.util.DDM;
            if ( YAHOO.util.Event && document ) {
                DDM._onLoad();
            } else {
                if (DDM._timeoutCount > 2000) {
                    YAHOO.log("DragDrop requires the Event Utility", "error", "DragDropMgr");
                } else {
                    setTimeout(DDM._addListeners, 10);
                    if (document && document.body) {
                        DDM._timeoutCount += 1;
                    }
                }
            }
        }
1236781
function() {
	
	   // Create a DIV element to wrap the editing el and the image
	   this.divEl = inputEx.cn('div', {className: 'inputEx-fieldWrapper'});
	   if(this.options.id) {
	      this.divEl.id = this.options.id;
	   }
	   if(this.options.required) {
	      Dom.addClass(this.divEl, "inputEx-required");
	   }
	   
	   // Label element
	   if(this.options.label) {
	      this.labelDiv = inputEx.cn('div', {id: this.divEl.id+'-label', className: 'inputEx-label', 'for': this.divEl.id+'-field'});
	      this.labelEl = inputEx.cn('label');
	      this.labelEl.appendChild( document.createTextNode(this.options.label) );
	      this.labelDiv.appendChild(this.labelEl);
	      this.divEl.appendChild(this.labelDiv);
      }
      
      this.fieldContainer = inputEx.cn('div', {className: this.options.className}); // for wrapping the field and description
	
      // Render the component directly
      this.renderComponent();
      
      // Description
      if(this.options.description) {
         this.fieldContainer.appendChild(inputEx.cn('div', {id: this.divEl.id+'-desc', className: 'inputEx-description'}, null, this.options.description));
      }
      
   	this.divEl.appendChild(this.fieldContainer);
      
	   // Insert a float breaker
	   this.divEl.appendChild( inputEx.cn('div',null, {clear: 'both'}," ") );
	
	}
1037489
function fileUploadIframe(a) {
        var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
        var useProp = !!$.fn.prop;

        if ($(':input[name=submit],:input[id=submit]', form).length) {
            // if there is an input with a name or id of 'submit' then we won't be
            // able to invoke the submit fn on the form (at least not x-browser)
            alert('Error: Form elements must not have name or id of "submit".');
            return;
        }
        
        if (a) {
            // ensure that every serialized input is still enabled
            for (i=0; i < elements.length; i++) {
                el = $(elements[i]);
                if ( useProp )
                    el.prop('disabled', false);
                else
                    el.removeAttr('disabled');
            }
        }

        s = $.extend(true, {}, $.ajaxSettings, options);
        s.context = s.context || s;
        id = 'jqFormIO' + (new Date().getTime());
        if (s.iframeTarget) {
            $io = $(s.iframeTarget);
            n = $io.attr('name');
            if (!n)
                 $io.attr('name', id);
            else
                id = n;
        }
        else {
            $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
            $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
        }
        io = $io[0];


        xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function(status) {
                var e = (status === 'timeout' ? 'timeout' : 'aborted');
                log('aborting upload... ' + e);
                this.aborted = 1;
                $io.attr('src', s.iframeSrc); // abort op in progress
                xhr.error = e;
                if (s.error)
                    s.error.call(s.context, xhr, e, status);
                if (g)
                    $.event.trigger("ajaxError", [xhr, s, e]);
                if (s.complete)
                    s.complete.call(s.context, xhr, e);
            }
        };

        g = s.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && 0 === $.active++) {
            $.event.trigger("ajaxStart");
        }
        if (g) {
            $.event.trigger("ajaxSend", [xhr, s]);
        }

        if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
            if (s.global) {
                $.active--;
            }
            return;
        }
        if (xhr.aborted) {
            return;
        }

        // add submitting element to data if we know it
        sub = form.clk;
        if (sub) {
            n = sub.name;
            if (n && !sub.disabled) {
                s.extraData = s.extraData || {};
                s.extraData[n] = sub.value;
                if (sub.type == "image") {
                    s.extraData[n+'.x'] = form.clk_x;
                    s.extraData[n+'.y'] = form.clk_y;
                }
            }
        }
        
        var CLIENT_TIMEOUT_ABORT = 1;
        var SERVER_ABORT = 2;

        function getDoc(frame) {
            var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
            return doc;
        }
        
        // Rails CSRF hack (thanks to Yvan Barthelemy)
        var csrf_token = $('meta[name=csrf-token]').attr('content');
        var csrf_param = $('meta[name=csrf-param]').attr('content');
        if (csrf_param && csrf_token) {
            s.extraData = s.extraData || {};
            s.extraData[csrf_param] = csrf_token;
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        function doSubmit() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');

            // update form attrs in IE friendly way
            form.setAttribute('target',id);
            if (!method) {
                form.setAttribute('method', 'POST');
            }
            if (a != s.url) {
                form.setAttribute('action', s.url);
            }

            // ie borks in some cases when setting encoding
            if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (s.timeout) {
                timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
            }
            
            // look for server aborts
            function checkState() {
                try {
                    var state = getDoc(io).readyState;
                    log('state = ' + state);
                    if (state && state.toLowerCase() == 'uninitialized')
                        setTimeout(checkState,50);
                }
                catch(e) {
                    log('Server abort: ' , e, ' (', e.name, ')');
                    cb(SERVER_ABORT);
                    if (timeoutHandle)
                        clearTimeout(timeoutHandle);
                    timeoutHandle = undefined;
                }
            }

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (s.extraData) {
                    for (var n in s.extraData) {
                        if (s.extraData.hasOwnProperty(n)) {
                            extraInputs.push(
                                $('<input type="hidden" name="'+n+'">').attr('value',s.extraData[n])
                                    .appendTo(form)[0]);
                        }
                    }
                }

                if (!s.iframeTarget) {
                    // add iframe to doc and submit the form
                    $io.appendTo('body');
                    if (io.attachEvent)
                        io.attachEvent('onload', cb);
                    else
                        io.addEventListener('load', cb, false);
                }
                setTimeout(checkState,15);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                form.setAttribute('action',a);
                if(t) {
                    form.setAttribute('target', t);
                } else {
                    $form.removeAttr('target');
                }
                $(extraInputs).remove();
            }
        }

        if (s.forceSync) {
            doSubmit();
        }
        else {
            setTimeout(doSubmit, 10); // this lets dom updates render
        }

        var data, doc, domCheckCount = 50, callbackProcessed;

        function cb(e) {
            if (xhr.aborted || callbackProcessed) {
                return;
            }
            try {
                doc = getDoc(io);
            }
            catch(ex) {
                log('cannot access response document: ', ex);
                e = SERVER_ABORT;
            }
            if (e === CLIENT_TIMEOUT_ABORT && xhr) {
                xhr.abort('timeout');
                return;
            }
            else if (e == SERVER_ABORT && xhr) {
                xhr.abort('server abort');
                return;
            }

            if (!doc || doc.location.href == s.iframeSrc) {
                // response not received yet
                if (!timedOut)
                    return;
            }
            if (io.detachEvent)
                io.detachEvent('onload', cb);
            else    
                io.removeEventListener('load', cb, false);

            var status = 'success', errMsg;
            try {
                if (timedOut) {
                    throw 'timeout';
                }

                var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
                log('isXml='+isXml);
                if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
                    if (--domCheckCount) {
                        // in some browsers (Opera) the iframe DOM is not always traversable when
                        // the onload callback fires, so we loop a bit to accommodate
                        log('requeing onLoad callback, DOM not available');
                        setTimeout(cb, 250);
                        return;
                    }
                    // let this fall through because server response could be an empty document
                    //log('Could not access iframe DOM after mutiple tries.');
                    //throw 'DOMException: not available';
                }

                //log('response detected');
                var docRoot = doc.body ? doc.body : doc.documentElement;
                xhr.responseText = docRoot ? docRoot.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                if (isXml)
                    s.dataType = 'xml';
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': s.dataType};
                    return headers[header];
                };
                // support for XHR 'status' & 'statusText' emulation :
                if (docRoot) {
                    xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
                    xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
                }

                var dt = (s.dataType || '').toLowerCase();
                var scr = /(json|script|text)/.test(dt);
                if (scr || s.textarea) {
                    // see if user embedded response in textarea
                    var ta = doc.getElementsByTagName('textarea')[0];
                    if (ta) {
                        xhr.responseText = ta.value;
                        // support for XHR 'status' & 'statusText' emulation :
                        xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
                        xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
                    }
                    else if (scr) {
                        // account for browsers injecting pre around json response
                        var pre = doc.getElementsByTagName('pre')[0];
                        var b = doc.getElementsByTagName('body')[0];
                        if (pre) {
                            xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
                        }
                        else if (b) {
                            xhr.responseText = b.textContent ? b.textContent : b.innerText;
                        }
                    }
                }
                else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
                    xhr.responseXML = toXml(xhr.responseText);
                }

                try {
                    data = httpData(xhr, dt, s);
                }
                catch (e) {
                    status = 'parsererror';
                    xhr.error = errMsg = (e || status);
                }
            }
            catch (e) {
                log('error caught: ',e);
                status = 'error';
                xhr.error = errMsg = (e || status);
            }

            if (xhr.aborted) {
                log('upload aborted');
                status = null;
            }

            if (xhr.status) { // we've set xhr.status
                status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (status === 'success') {
                if (s.success)
                    s.success.call(s.context, data, 'success', xhr);
                if (g)
                    $.event.trigger("ajaxSuccess", [xhr, s]);
            }
            else if (status) {
                if (errMsg === undefined)
                    errMsg = xhr.statusText;
                if (s.error)
                    s.error.call(s.context, xhr, status, errMsg);
                if (g)
                    $.event.trigger("ajaxError", [xhr, s, errMsg]);
            }

            if (g)
                $.event.trigger("ajaxComplete", [xhr, s]);

            if (g && ! --$.active) {
                $.event.trigger("ajaxStop");
            }

            if (s.complete)
                s.complete.call(s.context, xhr, status);

            callbackProcessed = true;
            if (s.timeout)
                clearTimeout(timeoutHandle);

            // clean up
            setTimeout(function() {
                if (!s.iframeTarget)
                    $io.remove();
                xhr.responseXML = null;
            }, 100);
        }

        var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else {
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            }
            return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
        };
        var parseJSON = $.parseJSON || function(s) {
            /*jslint evil:true */
            return window['eval']('(' + s + ')');
        };

        var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4

            var ct = xhr.getResponseHeader('content-type') || '',
                xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
                data = xml ? xhr.responseXML : xhr.responseText;

            if (xml && data.documentElement.nodeName === 'parsererror') {
                if ($.error)
                    $.error('parsererror');
            }
            if (s && s.dataFilter) {
                data = s.dataFilter(data, type);
            }
            if (typeof data === 'string') {
                if (type === 'json' || !type && ct.indexOf('json') >= 0) {
                    data = parseJSON(data);
                } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
                    $.globalEval(data);
                }
            }
            return data;
        };
    }
1046508
public function init() {
		$htmlId = $this->fileUploadControl->getHtmlId();
		
		foreach($this->elements as $type => $value) {
			if($type == "input") {
				$element = Html::el("input type='file' multiple='multiple'")->addAttributes([
					"id" => $htmlId,
					"name" => $this->fileUploadControl->getHtmlName(),
					"data-upload-component" => $htmlId
				]);
			} else if($type == "delete") {
				$element = Html::el("button type='button'")->addAttributes([
					"data-upload-component" => sprintf($this->idTemplate, $htmlId, $type)
				]);
			} else if($type == "imagePreview") {
				$element = Html::el("img")->addAttributes([
					"data-upload-component" => sprintf($this->idTemplate, $htmlId, $type)
				]);
			} else {
				$element = Html::el("div")->addAttributes([
					"data-upload-component" => sprintf($this->idTemplate, $htmlId, $type)
				]);
			}
			
			$this->elements[ $type ] = $element;
		}
	}
1329898
def add_form(self, **kwargs):
        """"""
        vocabularies = kwargs.get('vocabularies', None)
        qualifier = kwargs.get('qualifier', None)
        content = kwargs.get('content', None)
        parent_tag = kwargs.get('parent_tag', None)
        superuser = kwargs.get('superuser', False)
        # Element has both the qualifier and content.
        if qualifier is not None and content is not None:
            # Create the form attribute.
            self.form = UNTL_FORM_DISPATCH[self.tag](
                vocabularies=vocabularies,
                qualifier_value=qualifier,
                input_value=content,
                untl_object=self,
                superuser=superuser,
            )
        # Element just has a qualifier.
        elif qualifier is not None:
            # Create the form attribute.
            self.form = UNTL_FORM_DISPATCH[self.tag](
                vocabularies=vocabularies,
                qualifier_value=qualifier,
                untl_object=self,
                superuser=superuser,
            )
        # Element just has content.
        elif content is not None:
            # If the element is a child element,
            # create the form attribute.
            if parent_tag is None:
                self.form = UNTL_FORM_DISPATCH[self.tag](
                    vocabularies=vocabularies,
                    input_value=content,
                    untl_object=self,
                    superuser=superuser,
                )
            else:
                # Create the form attribute.
                self.form = UNTL_FORM_DISPATCH[self.tag](
                    vocabularies=vocabularies,
                    input_value=content,
                    untl_object=self,
                    parent_tag=parent_tag,
                    superuser=superuser,
                )
        # Element has children and no qualifiers or content
        # or is blank (not originally in the UNTL record).
        else:
            # Element is a child element.
            if parent_tag is None:
                # Create the form attribute.
                self.form = UNTL_FORM_DISPATCH[self.tag](
                    vocabularies=vocabularies,
                    untl_object=self,
                    superuser=superuser,
                )
            else:
                # Create the form attribute.
                self.form = UNTL_FORM_DISPATCH[self.tag](
                    vocabularies=vocabularies,
                    untl_object=self,
                    parent_tag=parent_tag,
                    superuser=superuser,
                )
339933
function uploadIndexPages(pagePaths, config, options, callback) {
    var requestOptions = {
      method: 'POST',
      url: options.airport + '/dev/' + config.appId + '/simulator',
      form: {}
    };

    // Attach the files as multi-part
    var request = api(config, requestOptions, callback);
    var form = request.form();

    pagePaths.forEach(function(pagePath) {
      grunt.log.debug("Uploading " + pagePath);
      form.append(path.basename(pagePath, '.html'), fs.createReadStream(pagePath));
    });
  }
31133
public void onModuleLoad() {
        final Button sendButton = new Button( "Send" );
        final TextBox nameField = new TextBox();
        nameField.setText( "GWT User" );
        final Label errorLabel = new Label();

        // We can add style names to widgets
        sendButton.addStyleName( "sendButton" );

        // Add the nameField and sendButton to the RootPanel
        // Use RootPanel.get() to get the entire body element
        RootPanel.get( "nameFieldContainer" ).add( nameField );
        RootPanel.get( "sendButtonContainer" ).add( sendButton );
        RootPanel.get( "errorLabelContainer" ).add( errorLabel );

        // Focus the cursor on the name field when the app loads
        nameField.setFocus( true );
        nameField.selectAll();

        // Create the popup dialog box
        final DialogBox dialogBox = new DialogBox();
        dialogBox.setText( "Remote Procedure Call" );
        dialogBox.setAnimationEnabled( true );
        final Button closeButton = new Button( "Close" );
        // We can set the id of a widget by accessing its Element
        closeButton.getElement().setId( "closeButton" );
        final Label textToServerLabel = new Label();
        final HTML serverResponseLabel = new HTML();
        VerticalPanel dialogVPanel = new VerticalPanel();
        dialogVPanel.addStyleName( "dialogVPanel" );
        dialogVPanel.add( new HTML( "<b>Sending name to the server:</b>" ) );
        dialogVPanel.add( textToServerLabel );
        dialogVPanel.add( new HTML( "<br><b>Server replies:</b>" ) );
        dialogVPanel.add( serverResponseLabel );
        dialogVPanel.setHorizontalAlignment( VerticalPanel.ALIGN_RIGHT );
        dialogVPanel.add( closeButton );
        dialogBox.setWidget( dialogVPanel );

        // Add a handler to close the DialogBox
        closeButton.addClickHandler( new ClickHandler() {
            public void onClick( ClickEvent event ) {
                dialogBox.hide();
                sendButton.setEnabled( true );
                sendButton.setFocus( true );
            }
        } );

        // Create a handler for the sendButton and nameField
        class MyHandler implements ClickHandler, KeyUpHandler {

            /**
             * Fired when the user clicks on the sendButton.
             */
            public void onClick( ClickEvent event ) {
                sendNameToServer();
            }

            /**
             * Fired when the user types in the nameField.
             */
            public void onKeyUp( KeyUpEvent event ) {
                if ( event.getNativeKeyCode() == KeyCodes.KEY_ENTER ) {
                    sendNameToServer();
                }
            }

            /**
             * Send the name from the nameField to the server and wait for a response.
             */
            private void sendNameToServer() {
                // First, we validate the input.
                errorLabel.setText( "" );
                String textToServer = nameField.getText();
                if ( !FieldVerifier.isValidName( textToServer ) ) {
                    errorLabel.setText( "Please enter at least four characters" );
                    return;
                }

                // Then, we send the input to the server.
                sendButton.setEnabled( false );
                textToServerLabel.setText( textToServer );
                serverResponseLabel.setText( "" );

                try {
                    new RequestBuilder( RequestBuilder.POST, "hello/greet" ).sendRequest( GREETING_REQUEST_WRITER
                            .write( new GreetingRequest( textToServer ) ), new RequestCallback() {
                        @Override
                        public void onResponseReceived( Request request, Response response ) {
                            GreetingResponse result = GREETING_RESPONSE_READER.read( response.getText() );

                            dialogBox.setText( "Remote Procedure Call" );
                            serverResponseLabel.removeStyleName( "serverResponseLabelError" );
                            serverResponseLabel.setHTML( new SafeHtmlBuilder().appendEscaped( result.getGreeting() )
                                    .appendHtmlConstant( "<br><br>I am running " ).appendEscaped( result.getServerInfo() )
                                    .appendHtmlConstant( ".<br><br>It looks like you are using:<br>" ).appendEscaped( result
                                            .getUserAgent() ).toSafeHtml() );
                            dialogBox.center();
                            closeButton.setFocus( true );
                        }

                        @Override
                        public void onError( Request request, Throwable throwable ) {
                            onRequestFailure();
                        }
                    } );
                } catch ( RequestException e ) {
                    onRequestFailure();
                }
            }

            private void onRequestFailure() {
                // Show the RPC error message to the user
                dialogBox.setText( "Remote Procedure Call - Failure" );
                serverResponseLabel.addStyleName( "serverResponseLabelError" );
                serverResponseLabel.setHTML( SERVER_ERROR );
                dialogBox.center();
                closeButton.setFocus( true );
            }
        }

        // Add a handler to send the name to the server
        MyHandler handler = new MyHandler();
        sendButton.addClickHandler( handler );
        nameField.addKeyUpHandler( handler );
    }