<commit_before>// Server-side validation plugin
;(function($, window, document) {

    $.widget('qcode.validation', {

        options: {
            qtip: {
                position: {
                    my: 'bottom center',
                    at: 'bottom center',
                    viewport: $(window)
                },
                show: {
                    event: false,
                    ready: true
                },
                hide: {
                    event: 'click focus blurs reset keydown paste cut',
                    delay: 0
                },
                style: {
                    classes: 'qtip-qcode'
                },
                events: {
		    render: function(event, api) {
                        // Clicking on the tooltip causes the target element to gain focus and hides the tooltip.
			api.elements.tooltip.on('click', function(event) {
                            api.elements.target.focus();
                            // Call the hide method in case the default hide events were overwritten
                            api.hide();
                        });
		    }
                }
            },
            hints: {},
            messages: {
                error: {
                    classes: 'message-area error'
                },
                notify: {
                    classes: 'message-area notify'
                },
                alert: {
                    classes: 'message-area alert'
                }
            },
	    submit: true,
            timeout: 20000
        },

        _create: function() {
            var widget = this;
            var $form = $(this.element);
            this.message = [];

            // Logic for default http method to be used for validation service.
            if ( typeof this.options.method === 'undefined' ) {
                if ( typeof $form.attr('method') === 'undefined' || $form.attr('method') === 'GET' ) {
                    var method = 'VALIDATE';
                } else {
                    var method = 'POST';
                }
            } else {
                method = this.options.method;
            }

            // Default url used for validation service.
            if ( typeof this.options.url === 'undefined' ) {
                var url = $form.attr('action');
            }

            // Click handlers for submit buttons on the form.
            // Used to add hidden input elements with the button's name and value because jQuery form.serialize() function does not
            // include submit button data since it has no way of knowing which button was used to submit the form.
            $form.find('button:not([type]), button[type="submit"], input[type="submit"]').click(function(event) {
                var name = $(this).attr('name');
                var value = $(this).attr('value');

                if ($form.find('input[type="hidden"][name="' + name + '"]').length === 0) {
                    $(this).before('<input type="hidden" name="' + name  + '" value="' + value  + '">');
                }
            });

            // Handler function for submit event.
            function validate (event) {
                // Stop the form submission.
                event.preventDefault();
                var $form = $(this);

                // Do not allow concurrent validation requests
                if ( ! $form.is('.validating') ) {
                    $form.addClass('validating');

                    // blur() then focus() any text inputs in the form that currently have focus
                    // hack to fix bug where autocomplete popup can become detached from input when page layout changes (when error messages displayed/hidden)
                    $('input:focus', $form).filter('[type=text],[type=email],[type=tel],[type=password]').blur().focus();

                    // Hide any existing validation messages
                    $('[data-hasqtip]:visible').qtip('hide');
                    $form.validation('hideMessage', 'alert');
                    $form.validation('hideMessage', 'notify');
                    $form.validation('hideMessage', 'error');

                    // Set up form data
                    var data = $form.serializeArray();
                    var ajax_method;
                    if ( method === 'POST' || method === 'GET' ) {
                        ajax_method = method;
                    } else {
                        // Emulate HTTP method
                        ajax_method = 'POST';
                        var found = false;
                        $.each(data, function(index, item) {
                            if ( item.name === '_method' ) {
                                item.value = method;
                                found = true;
                                return;
                            }
                        });

                        if ( !found ) {
                            data.push({
                                name: '_method',
                                value: method
                            });
                        }
                    }

                    // Send the form data
                    $.ajax({
                        url: url,
                        data: data,
                        method: ajax_method,
                        dataType: 'JSON',
                        headers: {
                            'X-Authenticity-Token': Cookies.get('authenticity_token')
                        },
                        timeout: widget.options.timeout,
                        success: function(response, success, request) {
                            $form.validation('parseResponse', response);

                            // Trigger validationComplete event
                            $form.trigger({
                                type: 'validationComplete',
                                response: response
                            });
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            var returnType = jqXHR.getResponseHeader('content-type');

                            if ( returnType == "application/json; charset=utf-8" && jqXHR.status != 200 && jqXHR.status != 0 ) {
                                // HTTP Error with JSON response
                                var response = $.parseJSON(jqXHR.responseText)
                                $form.validation('parseResponse', response);

                                // Trigger validationComplete event
                                $form.trigger({
                                    type: 'validationComplete',
                                    response: response
                                });

                            } else {
                                if ( textStatus == "parsererror" ) {
                                    // Parse error
                                    var errorMessage = "Sorry, we were unable to parse the server's response. Please try again.";
                                } else if ( textStatus == "timeout" ) {
                                    // Timeout
                                    var errorMessage = "Sorry, your request timed out. Please try again.";
                                } else {
                                    // Generic error message
                                    var errorMessage = "Sorry, something went wrong. Please try again.";
                                }

                                // Show error message
                                $form.validation('showMessage', 'error', errorMessage);
                                scrollToElement($form.validation('getMessage', 'error'), 200);

                                // Trigger validationError event
                                $form.trigger({
                                    type: 'validationError',
                                    errorMessage: errorMessage
                                });
                            }
                        },
                        complete: function(jqXHR, textStatus) {
                            $form.removeClass('validating');
                        }
                    });
                }
            }

            $form.on('submit.validate', validate);
        },

        parseResponse: function(response) {
            // Parses the response to show qtips and messages where necessary.
            var $form = $(this.element);
            var $scrollElement = undefined;
            // Check each record item is valid.
            $.each(response.record, function (name, object) {
                var $element = $form.find('[name=' + name + ']');
                if ( ! object.valid ) {
                    // Record item not valid - mark invalid and display message to user.
                    if ( $element.length !== 0 ) {
                        $form.validation('showValidationMessage', $element, object.message);
                        $element.addClass('invalid');

                        // Compare to highest element on page so far
                        if ( typeof $scrollElement === 'undefined' || $element.offset().top < $scrollElement.offset().top ) {
                            $scrollElement = $element;
                        }
                    }
                } else {
                    $element.removeClass('invalid');
                }
            });

            // Show messages if action redirect is not given
            var showMessages = true;
            if ( response.action && response.action.redirect ) {
                // don't show messages if redirect action was given
                showMessages = false;
            }
            if ( response.action && response.action.resubmit && $form.data('resubmit-disabled')!==true ) {
                // don't show messages if resubmit action was given and resubmission has not been disabled
                showMessages = false;
            }
            if ( showMessages && response.message ) {
                $.each(response.message, function(type, object) {
                    $form.validation('showMessage', type, object.value);
                    // Compare message to highest element on page
                    var $message = $form.validation('getMessage', type);
                    if ( typeof $scrollElement === 'undefined' ||
                         ($message.is(':visible') && $message.offset().top < $scrollElement.offset().top) ) {
                        $scrollElement = $message;
                    }
                });
            }

            if ( response.status === 'valid' ) {
                // submission was valid

                // re-enable future resubmit actions
                $form.data('resubmit-disabled',false);

                // redirect action
                if ( response.action && response.action.redirect ) {
                    // Redirect if record was valid and the redirect action was given
                    window.location.href = response.action.redirect.value;
                    return;
                } else if ( this.options.submit ) {
                    // default action
                    // resubmit form without validation
                    $form.off('submit.validate').submit();
                    return;
                }
            } else {
                // submission was invalid

                // resubmit action - used for authenticity token errors
                if ( response.action && response.action.resubmit && $form.data('resubmit-disabled')!==true ) {
                    // remove the validating flag before auto-resubmission
                    $form.removeClass('validating');
                    // resubmit the form
                    $form.submit();
                    // disable future resubmit actions to prevent inifite loop
                    $form.data('resubmit-disabled',true);
                    return;
                } else {
                    // re-enable future resubmit actions
                    $form.data('resubmit-disabled',false);
                }
            }

            // Scroll to the element if there is one to scroll to
            if ( typeof $scrollElement !== 'undefined' && typeof $scrollElement.qtip('api') !== 'undefined' ) {
                // $scrollElement exists and has has a qtip

                var scrollToHighest = function(api) {
                    // Scrolls to the highest element on the page out of three possible elements:
                    // the qtip, the element the qtip is bound to, and the label for the element if it has one.

                    // Check if element has a label
                    var $label = $form.find('label[for=' + $scrollElement.attr('id') + ']');
                    if ( $label.length === 0 ) {
                        $label = $scrollElement.closest('label');
                    }

                    // If a label was found then check if the label is higher than the element on the page
                    if ( $label.length > 0 && $label.offset().top < $scrollElement.offset().top ) {
                        $scrollElement = $label
                    }

                    // Compare the top offset of highest elements to the qtip tooltip
                    if ( api.tooltip.offset().top < $scrollElement.offset().top ) {
                        $scrollElement = api.tooltip;
                    }

                    scrollToElement($scrollElement, 200);
                }

                if ( $scrollElement.qtip('api').rendered ) {
                    // Qtip for element has been rendered so can scroll to it
                    scrollToHighest($scrollElement.qtip('api'));
                } else {
                    // Qtip hasn't been rendered yet - listen for render event then scroll to element
                    $scrollElement.qtip('api').set('events.render', function(event, api) {
                        // Clicking on the tooltip causes the target element to gain focus and hides the tooltip.
			api.elements.tooltip.on('click', function(event) {
                            api.elements.target.focus();
                            // Call the hide method in case the default hide events were overwritten
                            api.hide();
                        });
                        scrollToHighest(api);
		    });
                }
            } else if ( typeof $scrollElement !== 'undefined' ) {
                // $scrollElement exists but has no qtip - scroll to the $scrollElement
                scrollToElement($scrollElement, 200);
            }
        },

        showValidationMessage: function($element, message) {
            // Show the validation message with the message as the content for the given element.
            var api = $element.qtip('api');
            if ( api === undefined ) {
                var qtipOptions = {
                    content: message,
                    position: {
                        target: $element
                    }
                };
                $.extend(true, qtipOptions, this.options.qtip);
                $.each(this.options.hints, function(selector, hintOptions) {
                    if ( $element.is(selector) ) {
                        $.extend(true, qtipOptions, hintOptions);
                    }
                });
                // initialise qtip
                $element.qtip(qtipOptions);
            } else {
                // Update existing qtip and show
                api.set('content.text', message);
                api.reposition();
                api.show();
            }
            return $element;
        },

        hideValidationMessage: function($element) {
            // Hide the validation message for the given element.
            $element.qtip('hide');
            return $element;
        },

        showMessage: function(type, message) {
            // Show the message of the type given with message as the content.
            if (! this.message[type]) {
                // Message area doesn't exist so create it.
                var messageDiv = $('

').addClass(this.options.messages[type].classes)
                var messageContent = $('

').html(message).addClass('message-content');

                messageDiv.append(messageContent).hide();
                var validationElement = $(this.element);
                messageDiv.click(function(event){
                    validationElement.validation('hideMessage', type);
                    validationElement.validation('reposition');
                });

                if (this.options.messages[type].before) {
                    $(this.options.messages[type].before).before(messageDiv);
                } else if (this.options.messages[type].after) {
                    $(this.options.messages[type].after).after(messageDiv);
                } else {
                    $('body').append(messageDiv);
                }

                this.message[type] = messageDiv;
                messageDiv.show(200, $.proxy(function() {
                    this.reposition();
                }, this));
            } else {
                // Update the message
                this.message[type].find('.message-content').html(message);
                this.message[type].show(200, $.proxy(function() {
                    this.reposition();
                }, this));
            }
        },

        hideMessage: function(type) {
            // Hide the message with the given type.
            if (this.message[type]) {
                this.message[type].hide(100, $.proxy(function() {
                    this.reposition();
                }, this));
            }
        },

        getMessage: function(type) {
            // Returns the jquery object for the message of the given type
            return this.message[type];
        },

        reposition: function() {
            // Reposition or hide all validation messages.
            $('[data-hasqtip]').each(function() {
                if ( ! $(this).is(':visible') ) {
                    $(this).qtip('hide');
                } else {
                    $(this).qtip('reposition');
                }
            });
        },

        _destroy: function() {
            // Remove the elements created by this plugin.
            this.element.unbind('submit.validate');
            $(this.element).removeClass('validating');
            this._validationMessagesDestroy();
            this._messagesDestroy();
        },

        _validationMessagesDestroy: function() {
            // Destroy any tooltips associated with this element or it's descendants.
            $(this.element).find('[data-hasqtip]').qtip('destroy');
        },

        _messagesDestroy: function() {
            // Remove all messages added by this plugin.
            if ( this.message['alert'] ) {
                this.message['alert'].remove();
            }
            if ( this.message['error'] ) {
                this.message['error'].remove();
            }
            if ( this.message['notify'] ) {
                this.message['notify'].remove();
            }
        }

    });

})(jQuery, window, document);
<commit_msg>Added setFormValues function to validaiton plugin<commit_after>// Server-side validation plugin
;(function($, window, document) {

    $.widget('qcode.validation', {

        options: {
            qtip: {
                position: {
                    my: 'bottom center',
                    at: 'bottom center',
                    viewport: $(window)
                },
                show: {
                    event: false,
                    ready: true
                },
                hide: {
                    event: 'click focus blurs reset keydown paste cut',
                    delay: 0
                },
                style: {
                    classes: 'qtip-qcode'
                },
                events: {
		    render: function(event, api) {
                        // Clicking on the tooltip causes the target element to gain focus and hides the tooltip.
			api.elements.tooltip.on('click', function(event) {
                            api.elements.target.focus();
                            // Call the hide method in case the default hide events were overwritten
                            api.hide();
                        });
		    }
                }
            },
            hints: {},
            messages: {
                error: {
                    classes: 'message-area error'
                },
                notify: {
                    classes: 'message-area notify'
                },
                alert: {
                    classes: 'message-area alert'
                }
            },
	    submit: true,
            timeout: 20000
        },

        _create: function() {
            var widget = this;
            var $form = $(this.element);
            this.message = [];

            // Logic for default http method to be used for validation service.
            if ( typeof this.options.method === 'undefined' ) {
                if ( typeof $form.attr('method') === 'undefined' || $form.attr('method') === 'GET' ) {
                    var method = 'VALIDATE';
                } else {
                    var method = 'POST';
                }
            } else {
                method = this.options.method;
            }

            // Default url used for validation service.
            if ( typeof this.options.url === 'undefined' ) {
                var url = $form.attr('action');
            }

            // Click handlers for submit buttons on the form.
            // Used to add hidden input elements with the button's name and value because jQuery form.serialize() function does not
            // include submit button data since it has no way of knowing which button was used to submit the form.
            $form.find('button:not([type]), button[type="submit"], input[type="submit"]').click(function(event) {
                var name = $(this).attr('name');
                var value = $(this).attr('value');

                if ($form.find('input[type="hidden"][name="' + name + '"]').length === 0) {
                    $(this).before('<input type="hidden" name="' + name  + '" value="' + value  + '">');
                }
            });

            // Handler function for submit event.
            function validate (event) {
                // Stop the form submission.
                event.preventDefault();
                var $form = $(this);

                // Do not allow concurrent validation requests
                if ( ! $form.is('.validating') ) {
                    $form.addClass('validating');

                    // blur() then focus() any text inputs in the form that currently have focus
                    // hack to fix bug where autocomplete popup can become detached from input when page layout changes (when error messages displayed/hidden)
                    $('input:focus', $form).filter('[type=text],[type=email],[type=tel],[type=password]').blur().focus();

                    // Hide any existing validation messages
                    $('[data-hasqtip]:visible').qtip('hide');
                    $form.validation('hideMessage', 'alert');
                    $form.validation('hideMessage', 'notify');
                    $form.validation('hideMessage', 'error');

                    // Set up form data
                    var data = $form.serializeArray();
                    var ajax_method;
                    if ( method === 'POST' || method === 'GET' ) {
                        ajax_method = method;
                    } else {
                        // Emulate HTTP method
                        ajax_method = 'POST';
                        var found = false;
                        $.each(data, function(index, item) {
                            if ( item.name === '_method' ) {
                                item.value = method;
                                found = true;
                                return;
                            }
                        });

                        if ( !found ) {
                            data.push({
                                name: '_method',
                                value: method
                            });
                        }
                    }

                    // Send the form data
                    $.ajax({
                        url: url,
                        data: data,
                        method: ajax_method,
                        dataType: 'JSON',
                        headers: {
                            'X-Authenticity-Token': Cookies.get('authenticity_token')
                        },
                        timeout: widget.options.timeout,
                        success: function(response, success, request) {
                            $form.validation('parseResponse', response);

                            // Trigger validationComplete event
                            $form.trigger({
                                type: 'validationComplete',
                                response: response
                            });
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            var returnType = jqXHR.getResponseHeader('content-type');

                            if ( returnType == "application/json; charset=utf-8" && jqXHR.status != 200 && jqXHR.status != 0 ) {
                                // HTTP Error with JSON response
                                var response = $.parseJSON(jqXHR.responseText)
                                $form.validation('parseResponse', response);

                                // Trigger validationComplete event
                                $form.trigger({
                                    type: 'validationComplete',
                                    response: response
                                });

                            } else {
                                if ( textStatus == "parsererror" ) {
                                    // Parse error
                                    var errorMessage = "Sorry, we were unable to parse the server's response. Please try again.";
                                } else if ( textStatus == "timeout" ) {
                                    // Timeout
                                    var errorMessage = "Sorry, your request timed out. Please try again.";
                                } else {
                                    // Generic error message
                                    var errorMessage = "Sorry, something went wrong. Please try again.";
                                }

                                // Show error message
                                $form.validation('showMessage', 'error', errorMessage);
                                scrollToElement($form.validation('getMessage', 'error'), 200);

                                // Trigger validationError event
                                $form.trigger({
                                    type: 'validationError',
                                    errorMessage: errorMessage
                                });
                            }
                        },
                        complete: function(jqXHR, textStatus) {
                            $form.removeClass('validating');
                        }
                    });
                }
            }

            $form.on('submit.validate', validate);
        },

        parseResponse: function(response) {
            // Parses the response to show qtips and messages where necessary.
            var $form = $(this.element);
            var $scrollElement = undefined;
            // Check each record item is valid.
            $.each(response.record, function (name, object) {
                var $element = $form.find('[name=' + name + ']');
                if ( ! object.valid ) {
                    // Record item not valid - mark invalid and display message to user.
                    if ( $element.length !== 0 ) {
                        $form.validation('showValidationMessage', $element, object.message);
                        $element.addClass('invalid');

                        // Compare to highest element on page so far
                        if ( typeof $scrollElement === 'undefined' || $element.offset().top < $scrollElement.offset().top ) {
                            $scrollElement = $element;
                        }
                    }
                } else {
                    $element.removeClass('invalid');
                }
            });

            // Show messages if action redirect is not given
            var showMessages = true;
            if ( response.action && response.action.redirect ) {
                // don't show messages if redirect action was given
                showMessages = false;
            }
            if ( response.action && response.action.resubmit && $form.data('resubmit-disabled')!==true ) {
                // don't show messages if resubmit action was given and resubmission has not been disabled
                showMessages = false;
            }
            if ( showMessages && response.message ) {
                $.each(response.message, function(type, object) {
                    $form.validation('showMessage', type, object.value);
                    // Compare message to highest element on page
                    var $message = $form.validation('getMessage', type);
                    if ( typeof $scrollElement === 'undefined' ||
                         ($message.is(':visible') && $message.offset().top < $scrollElement.offset().top) ) {
                        $scrollElement = $message;
                    }
                });
            }

            if ( response.status === 'valid' ) {
                // submission was valid

                // re-enable future resubmit actions
                $form.data('resubmit-disabled',false);

                // redirect action
                if ( response.action && response.action.redirect ) {
                    // Redirect if record was valid and the redirect action was given
                    window.location.href = response.action.redirect.value;
                    return;
                } else if ( this.options.submit ) {
                    // default action
                    // resubmit form without validation
                    $form.off('submit.validate').submit();
                    return;
                }
            } else {
                // submission was invalid

                // resubmit action - used for authenticity token errors
                if ( response.action && response.action.resubmit && $form.data('resubmit-disabled')!==true ) {
                    // remove the validating flag before auto-resubmission
                    $form.removeClass('validating');
                    // resubmit the form
                    $form.submit();
                    // disable future resubmit actions to prevent inifite loop
                    $form.data('resubmit-disabled',true);
                    return;
                } else {
                    // re-enable future resubmit actions
                    $form.data('resubmit-disabled',false);
                }
            }

            // Scroll to the element if there is one to scroll to
            if ( typeof $scrollElement !== 'undefined' && typeof $scrollElement.qtip('api') !== 'undefined' ) {
                // $scrollElement exists and has has a qtip

                var scrollToHighest = function(api) {
                    // Scrolls to the highest element on the page out of three possible elements:
                    // the qtip, the element the qtip is bound to, and the label for the element if it has one.

                    // Check if element has a label
                    var $label = $form.find('label[for=' + $scrollElement.attr('id') + ']');
                    if ( $label.length === 0 ) {
                        $label = $scrollElement.closest('label');
                    }

                    // If a label was found then check if the label is higher than the element on the page
                    if ( $label.length > 0 && $label.offset().top < $scrollElement.offset().top ) {
                        $scrollElement = $label
                    }

                    // Compare the top offset of highest elements to the qtip tooltip
                    if ( api.tooltip.offset().top < $scrollElement.offset().top ) {
                        $scrollElement = api.tooltip;
                    }

                    scrollToElement($scrollElement, 200);
                }

                if ( $scrollElement.qtip('api').rendered ) {
                    // Qtip for element has been rendered so can scroll to it
                    scrollToHighest($scrollElement.qtip('api'));
                } else {
                    // Qtip hasn't been rendered yet - listen for render event then scroll to element
                    $scrollElement.qtip('api').set('events.render', function(event, api) {
                        // Clicking on the tooltip causes the target element to gain focus and hides the tooltip.
			api.elements.tooltip.on('click', function(event) {
                            api.elements.target.focus();
                            // Call the hide method in case the default hide events were overwritten
                            api.hide();
                        });
                        scrollToHighest(api);
		    });
                }
            } else if ( typeof $scrollElement !== 'undefined' ) {
                // $scrollElement exists but has no qtip - scroll to the $scrollElement
                scrollToElement($scrollElement, 200);
            }
        },

        showValidationMessage: function($element, message) {
            // Show the validation message with the message as the content for the given element.
            var api = $element.qtip('api');
            if ( api === undefined ) {
                var qtipOptions = {
                    content: message,
                    position: {
                        target: $element
                    }
                };
                $.extend(true, qtipOptions, this.options.qtip);
                $.each(this.options.hints, function(selector, hintOptions) {
                    if ( $element.is(selector) ) {
                        $.extend(true, qtipOptions, hintOptions);
                    }
                });
                // initialise qtip
                $element.qtip(qtipOptions);
            } else {
                // Update existing qtip and show
                api.set('content.text', message);
                api.reposition();
                api.show();
            }
            return $element;
        },

        hideValidationMessage: function($element) {
            // Hide the validation message for the given element.
            $element.qtip('hide');
            return $element;
        },

        showMessage: function(type, message) {
            // Show the message of the type given with message as the content.
            if (! this.message[type]) {
                // Message area doesn't exist so create it.
                var messageDiv = $('

').addClass(this.options.messages[type].classes)
                var messageContent = $('

').html(message).addClass('message-content');

                messageDiv.append(messageContent).hide();
                var validationElement = $(this.element);
                messageDiv.click(function(event){
                    validationElement.validation('hideMessage', type);
                    validationElement.validation('reposition');
                });

                if (this.options.messages[type].before) {
                    $(this.options.messages[type].before).before(messageDiv);
                } else if (this.options.messages[type].after) {
                    $(this.options.messages[type].after).after(messageDiv);
                } else {
                    $('body').append(messageDiv);
                }

                this.message[type] = messageDiv;
                messageDiv.show(200, $.proxy(function() {
                    this.reposition();
                }, this));
            } else {
                // Update the message
                this.message[type].find('.message-content').html(message);
                this.message[type].show(200, $.proxy(function() {
                    this.reposition();
                }, this));
            }
        },

        hideMessage: function(type) {
            // Hide the message with the given type.
            if (this.message[type]) {
                this.message[type].hide(100, $.proxy(function() {
                    this.reposition();
                }, this));
            }
        },

        getMessage: function(type) {
            // Returns the jquery object for the message of the given type
            return this.message[type];
        },

        reposition: function() {
            // Reposition or hide all validation messages.
            $('[data-hasqtip]').each(function() {
                if ( ! $(this).is(':visible') ) {
                    $(this).qtip('hide');
                } else {
                    $(this).qtip('reposition');
                }
            });
        },

        _destroy: function() {
            // Remove the elements created by this plugin.
            this.element.unbind('submit.validate');
            $(this.element).removeClass('validating');
            this._validationMessagesDestroy();
            this._messagesDestroy();
        },

        _validationMessagesDestroy: function() {
            // Destroy any tooltips associated with this element or it's descendants.
            $(this.element).find('[data-hasqtip]').qtip('destroy');
        },

        _messagesDestroy: function() {
            // Remove all messages added by this plugin.
            if ( this.message['alert'] ) {
                this.message['alert'].remove();
            }
            if ( this.message['error'] ) {
                this.message['error'].remove();
            }
            if ( this.message['notify'] ) {
                this.message['notify'].remove();
            }
        }

	setValuesFromResponse: function(response) {
	    // Set form values from the response
	    var $form = $(this.element);
	    if (typeof response !== "undefined" && 'record' in response ) {
		$.each(response.record, function (name, object) {
		    var $element = $form.find('[name=' + name + ']');
		    if ( 'valid' in object && object.valid && 'value' in object ) {
			// Set the value of the field
			$element.val(object.value);
		    }
		});
	    }
	}

    });

})(jQuery, window, document);
<|endoftext|>


<commit_before>var config      = require('config'),
    pg          = require('pg-query')

var pg_config   = config.pg_config,
    schema_name = config.schema_name;
pg.connectionParameters = pg_config + '/' + schema_name;

var error_response = "Schema already exists - bypassing db initialization step\n";

function create_db_schema(err, rows, result) {
  if(err && err.code == "ECONNREFUSED"){
    return console.error("DB connection unavailable, see README notes for setup assistance\n", err);
  }
  // drop tables first
  // errors in this part are ignored - tables may and may not be present so DROP can fail
  console.info('Dropping table ODPAD');
  pg('DROP TABLE odpad;', function(err, rows, result){
    console.info('Dropping table KNOWN_PLACES');
    pg('DROP TABLE known_places;', create_odpad_table);
  });
}

function create_odpad_table(err, rows, result) {
  var table_name = 'odpad';
  var query = "CREATE TABLE "+table_name+" ( " +
    "gid serial NOT NULL," +
    "place_name character varying(240), " +
    "time_from TIMESTAMP NOT NULL, " +
    "time_to TIMESTAMP NOT NULL, " +
    "the_geom geometry, " +
    "CONSTRAINT "+table_name+ "_pkey PRIMARY KEY (gid), " +
    "CONSTRAINT "+table_name+"_enforce_dims_geom CHECK (st_ndims(the_geom) = 2), " +
    "CONSTRAINT "+table_name+"_enforce_geotype_geom CHECK (geometrytype(the_geom) = 'POINT'::text OR the_geom IS NULL), " +
    "CONSTRAINT "+table_name+"_enforce_srid_geom CHECK (st_srid(the_geom) = 4326), " +
    "UNIQUE (place_name, time_from, time_to)" +
    ") WITH ( OIDS=FALSE );";
  console.info('Creating table '+table_name);
  pg(query, add_spatial_index);
}

function add_spatial_index(err, rows, result) {
  if(err) {
    return console.error(error_response, err);
  }
  var table_name = 'odpad';
  console.info('Creating spatial index on table ODPAD');
  pg("CREATE INDEX "+table_name+"_geom_gist ON "+table_name+" USING gist (the_geom);", add_known_places);
}

function add_known_places(err, rows, result) {
  if(err) {
    return console.error(error_response, err);
  }
  var table_name = 'known_places';
  var query = "CREATE TABLE "+table_name+" ( " +
    "place_name character varying(240), " +
    "the_geom geometry, " +
    "CONSTRAINT "+table_name+"_pkey PRIMARY KEY (place_name), " +
    "CONSTRAINT "+table_name+"_enforce_dims_geom CHECK (st_ndims(the_geom) = 2), " +
    "CONSTRAINT "+table_name+"_enforce_geotype_geom CHECK (geometrytype(the_geom) = 'POINT'::text OR the_geom IS NULL), " +
    "CONSTRAINT "+table_name+"_enforce_srid_geom CHECK (st_srid(the_geom) = 4326) " +
    ") WITH ( OIDS=FALSE );";
  console.info('Creating table '+table_name);
  pg(query, function(err, rows, result) {
    if(err) {
      return console.error(error_response, err);
    }
    return 'Database initialized!';
  });
}

function import_containers(containers) {
  console.info('Importing containers to DB')
  var stmt = 'INSERT INTO odpad (place_name, time_from, time_to) VALUES ($1::text, $2::timestamp, $3::timestamp);';
  for (var i = 0; i < containers.length; i++) {
    pg(stmt, containers[i], function(err, rows, result) {
      if(err) {
        return console.error('Cannot insert container to DB!', err);
      }
    });
  }
  // update geo location to containers
  console.info('Updating location of containers')
  stmt = 'UPDATE odpad SET the_geom = (SELECT the_geom FROM known_places p WHERE p.place_name = place_name);';
  pg (stmt, function(err, rows, result) {
    if (err) {
      return console.error('Cannot update container locations!', err);
    }

    // update list of places
    console.info('Updating list of places')
    stmt = 'INSERT INTO known_places (place_name) SELECT DISTINCT o.place_name AS place_name FROM odpad o WHERE o.the_geom IS NULL AND NOT EXISTS (SELECT kp.place_name FROM known_places kp WHERE kp.place_name = o.place_name);';
    pg (stmt, function(err, rows, result) {
      if (err) {
        return console.error('Cannot update list of places!', err);
      }
    });
  });
}

function init_db(){
  pg('CREATE EXTENSION postgis;', create_db_schema);
}

function select_all(req, res, next){
  console.log('Selecting all containers');
  pg('SELECT gid, place_name, ST_X(the_geom) AS lon, ST_Y(the_geom) AS lat FROM odpad WHERE time_to > NOW() AND the_geom IS NOT NULL;', function(err, rows, result) {
    console.log(config);
    if(err) {
      res.json(500, {http_status:500,error_msg: err})
      return console.error('error running query', err);
    }
    res.json(rows);
    return next();
  });
}

function unknown_places(req, res, next){
  console.log('Selecting known places');
  pg('SELECT place_name FROM known_places WHERE the_geom IS NULL;', function(err, rows, result) {
    console.log(config);
    if(err) {
      res.json(500, {http_status:500,error_msg: err})
      return console.error('error running query', err);
    }
    res.json(rows);
    return next();
  });
}

function add_place(place_name, lat, lng, callback) {
  console.info('Adding place to DB');
  var stmt = "INSERT INTO known_places (place_name, the_geom) VALUES ($1::text, ST_GeomFromText('POINT($2::text, $3::text)', 4326));";
  pg(stmt, [place_name, lat, lng], function(err, rows, result) {
    if(err) {
      console.error('Cannot add place to DB!', err);
      callback(err);
      return;
    }
    // update location of related containers
    console.info('Updating related containers')
    stmt = 'UPDATE odpad SET the_geom = (SELECT the_geom FROM known_places WHERE place_name = $1::text) WHERE place_name = $2::text;';
    pg(stmt, [place_name, place_name], function(err, rows, result) {
      if (err) {
        console.error('Cannot update location of related containers!', err);
        callback(err);
      }
      callback();
    });
  });
}

module.exports = exports = {
  selectAll:         select_all,
  initDB:            init_db,
  importContainers:  import_containers,
  unknownPlaces:     unknown_places,
  addPlace:          add_place
};
<commit_msg>Fixed insert statement with place location<commit_after>var config      = require('config'),
    pg          = require('pg-query')

var pg_config   = config.pg_config,
    schema_name = config.schema_name;
pg.connectionParameters = pg_config + '/' + schema_name;

var error_response = "Schema already exists - bypassing db initialization step\n";

function create_db_schema(err, rows, result) {
  if(err && err.code == "ECONNREFUSED"){
    return console.error("DB connection unavailable, see README notes for setup assistance\n", err);
  }
  // drop tables first
  // errors in this part are ignored - tables may and may not be present so DROP can fail
  console.info('Dropping table ODPAD');
  pg('DROP TABLE odpad;', function(err, rows, result){
    console.info('Dropping table KNOWN_PLACES');
    pg('DROP TABLE known_places;', create_odpad_table);
  });
}

function create_odpad_table(err, rows, result) {
  var table_name = 'odpad';
  var query = "CREATE TABLE "+table_name+" ( " +
    "gid serial NOT NULL," +
    "place_name character varying(240), " +
    "time_from TIMESTAMP NOT NULL, " +
    "time_to TIMESTAMP NOT NULL, " +
    "the_geom geometry, " +
    "CONSTRAINT "+table_name+ "_pkey PRIMARY KEY (gid), " +
    "CONSTRAINT "+table_name+"_enforce_dims_geom CHECK (st_ndims(the_geom) = 2), " +
    "CONSTRAINT "+table_name+"_enforce_geotype_geom CHECK (geometrytype(the_geom) = 'POINT'::text OR the_geom IS NULL), " +
    "CONSTRAINT "+table_name+"_enforce_srid_geom CHECK (st_srid(the_geom) = 4326), " +
    "UNIQUE (place_name, time_from, time_to)" +
    ") WITH ( OIDS=FALSE );";
  console.info('Creating table '+table_name);
  pg(query, add_spatial_index);
}

function add_spatial_index(err, rows, result) {
  if(err) {
    return console.error(error_response, err);
  }
  var table_name = 'odpad';
  console.info('Creating spatial index on table ODPAD');
  pg("CREATE INDEX "+table_name+"_geom_gist ON "+table_name+" USING gist (the_geom);", add_known_places);
}

function add_known_places(err, rows, result) {
  if(err) {
    return console.error(error_response, err);
  }
  var table_name = 'known_places';
  var query = "CREATE TABLE "+table_name+" ( " +
    "place_name character varying(240), " +
    "the_geom geometry, " +
    "CONSTRAINT "+table_name+"_pkey PRIMARY KEY (place_name), " +
    "CONSTRAINT "+table_name+"_enforce_dims_geom CHECK (st_ndims(the_geom) = 2), " +
    "CONSTRAINT "+table_name+"_enforce_geotype_geom CHECK (geometrytype(the_geom) = 'POINT'::text OR the_geom IS NULL), " +
    "CONSTRAINT "+table_name+"_enforce_srid_geom CHECK (st_srid(the_geom) = 4326) " +
    ") WITH ( OIDS=FALSE );";
  console.info('Creating table '+table_name);
  pg(query, function(err, rows, result) {
    if(err) {
      return console.error(error_response, err);
    }
    return 'Database initialized!';
  });
}

function import_containers(containers) {
  console.info('Importing containers to DB')
  var stmt = 'INSERT INTO odpad (place_name, time_from, time_to) VALUES ($1::text, $2::timestamp, $3::timestamp);';
  for (var i = 0; i < containers.length; i++) {
    pg(stmt, containers[i], function(err, rows, result) {
      if(err) {
        return console.error('Cannot insert container to DB!', err);
      }
    });
  }
  // update geo location to containers
  console.info('Updating location of containers')
  stmt = 'UPDATE odpad SET the_geom = (SELECT the_geom FROM known_places p WHERE p.place_name = place_name);';
  pg (stmt, function(err, rows, result) {
    if (err) {
      return console.error('Cannot update container locations!', err);
    }

    // update list of places
    console.info('Updating list of places')
    stmt = 'INSERT INTO known_places (place_name) SELECT DISTINCT o.place_name AS place_name FROM odpad o WHERE o.the_geom IS NULL AND NOT EXISTS (SELECT kp.place_name FROM known_places kp WHERE kp.place_name = o.place_name);';
    pg (stmt, function(err, rows, result) {
      if (err) {
        return console.error('Cannot update list of places!', err);
      }
    });
  });
}

function init_db(){
  pg('CREATE EXTENSION postgis;', create_db_schema);
}

function select_all(req, res, next){
  console.log('Selecting all containers');
  pg('SELECT gid, place_name, ST_X(the_geom) AS lon, ST_Y(the_geom) AS lat FROM odpad WHERE time_to > NOW() AND the_geom IS NOT NULL;', function(err, rows, result) {
    console.log(config);
    if(err) {
      res.json(500, {http_status:500,error_msg: err})
      return console.error('error running query', err);
    }
    res.json(rows);
    return next();
  });
}

function unknown_places(req, res, next){
  console.log('Selecting known places');
  pg('SELECT place_name FROM known_places WHERE the_geom IS NULL;', function(err, rows, result) {
    console.log(config);
    if(err) {
      res.json(500, {http_status:500,error_msg: err})
      return console.error('error running query', err);
    }
    res.json(rows);
    return next();
  });
}

function add_place(place_name, lat, lng, callback) {
  console.info('Adding place to DB');
  var stmt = "INSERT INTO known_places (place_name, the_geom) VALUES ($1::text, ST_SetSRID(ST_MakePoint($2::float, $3::float), 4326));";
  pg(stmt, [place_name, lat, lng], function(err, rows, result) {
    if(err) {
      console.error('Cannot add place to DB!', err);
      callback(err);
      return;
    }
    // update location of related containers
    console.info('Updating related containers')
    stmt = 'UPDATE odpad SET the_geom = (SELECT the_geom FROM known_places WHERE place_name = $1::text) WHERE place_name = $2::text;';
    pg(stmt, [place_name, place_name], function(err, rows, result) {
      if (err) {
        console.error('Cannot update location of related containers!', err);
        callback(err);
      }
      callback();
    });
  });
}

module.exports = exports = {
  selectAll:         select_all,
  initDB:            init_db,
  importContainers:  import_containers,
  unknownPlaces:     unknown_places,
  addPlace:          add_place
};
<|endoftext|>


<commit_before>(function(NS){

})(window.controller = window.controller || {});<commit_msg>deleted misplaced copy of controller.js<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

let origDir = process.cwd()
process.chdir(__dirname + "/..")

// NOTE: Don't require anything from node_modules here, since the
// install script has to be able to run _before_ that exists.
let child = require("child_process"), fs = require("fs"), path = require("path")

let main = ["model", "transform", "state", "view",
            "keymap", "inputrules", "history", "collab", "commands", "gapcursor",
            "schema-basic", "schema-list"]
let mods = main.concat(["menu", "example-setup", "markdown", "dropcursor", "test-builder", "changeset"])
let modsAndWebsite = mods.concat("website")

function start() {
  let command = process.argv[2]
  if (command && !["install", "--help"].includes(command)) assertInstalled()
  let args = process.argv.slice(3)
  let cmdFn = {
    "status": status,
    "lint": lint,
    "commit": commit,
    "install": install,
    "build": build,
    "test": test,
    "push": push,
    "grep": grep,
    "run": runCmd,
    "watch": watch,
    "changes": changes,
    "modules": listModules,
    "release": release,
    "dev-start": devStart,
    "dev-stop": devStop,
    "mass-change": massChange,
    "--help": showHelp
  }[command]
  if (!cmdFn || cmdFn.length > args.length) help(1)
  cmdFn.apply(null, args)
}

function showHelp() {
  help(0)
}

function help(status) {
  console.log(`Usage:
  pm install [--ssh]      Clone and symlink the packages, install dependencies, build
  pm build                Build all modules
  pm status               Print out the git status of packages
  pm commit <args>        Run git commit in all packages that have changes
  pm push                 Run git push in packages that have new commits
  pm test                 Run the tests from all packages
  pm lint                 Run the linter over all packages
  pm watch                Set up a process that rebuilds the packages on change
  pm grep <pattern>       Grep through the source code for all packages
  pm run <command>        Run the given command in each of the package dirs
  pm changes              Show commits since the last release for all packages
  pm mass-change <files> <pattern> <replacement>
                          Run a regexp-replace on the matching files in each package
  pm release <module>     Generate a new release for the given module.
  pm modules [--core]     Emit a list of all package names
  pm dev-start            Start development server
  pm dev-stop             Stop development server, if running
  pm --help`)
  process.exit(status)
}

function assertInstalled() {
  modsAndWebsite.forEach(repo => {
    if (!fs.existsSync(repo)) {
      console.error("module `%s` is missing. Did you forget to run `pm install`?", repo)
      process.exit(1)
    }
  })
}

function run(cmd, args, wd) {
  return child.execFileSync(cmd, args, {cwd: wd, encoding: "utf8", stdio: ["ignore", "pipe", process.stderr]})
}

function status() {
  modsAndWebsite.forEach(repo => {
    let output = run("git", ["status", "-sb"], repo)
    if (output != "## master...origin/master\n")
      console.log(repo + ":\n" + run("git", ["status"], repo))
  })
}

function lintOptions(browser) {
  return {
    browser,
    ecmaVersion: 6,
    semicolons: false,
    namedFunctions: true,
    trailingCommas: true
  }
}

function lint() {
  let blint = require("blint")
  mods.forEach(repo => {
    let options = lintOptions(["view", "menu", "example-setup", "dropcursor", "gapcursor"].indexOf(repo) > -1)
    blint.checkDir(repo + "/src/", options)
    if (fs.existsSync(repo + "/test")) {
      options.allowedGlobals = ["it", "describe"]
      blint.checkDir(repo + "/test/", options)
    }
  })
  let websiteOptions = Object.assign(lintOptions(true), {
    allowedGlobals: ["__dirname", "process"],
    console: true
  })
  blint.checkDir("website/src/", websiteOptions)
  require("glob").sync("website/pages/examples/*/example.js").forEach(file => blint.checkFile(file, websiteOptions))
}

function commit(...args) {
  modsAndWebsite.forEach(repo => {
    if (run("git", ["diff"], repo) || run("git", ["diff", "--cached"], repo))
      console.log(repo + ":\n" + run("git", ["commit"].concat(args), repo))
  })
}

function install(arg = null) {
  let base = "https://github.com/prosemirror/"
  if (arg == "--ssh") { base = "git@github.com:ProseMirror/" }
  else if (arg != null) help(1)

  modsAndWebsite.forEach(repo => {
    if (fs.existsSync(repo)) {
      console.warn("Skipping cloning of " + repo + " (directory exists)")
      return
    }
    let origin = base + (repo == "website" ? "" : "prosemirror-") + repo + ".git"
    run("git", ["clone", origin, repo])
  })

  console.log("Running yarn install")
  run("yarn", ["install"])
  console.log("Building modules")
  build()
}

function build() {
  mods.forEach(repo => {
    console.log(repo + "...")
    run("npm", ["run", "build"], repo)
  })
}

function test() {
  let mocha = new (require("mocha"))
  mods.forEach(repo => {
    if (repo == "view" || !fs.existsSync(repo + "/test")) return
    fs.readdirSync(repo + "/test").forEach(file => {
      if (/^test-/.test(file)) mocha.addFile(repo + "/test/" + file)
    })
  })
  mocha.run(failures => process.exit(failures))
}

function push() {
  modsAndWebsite.forEach(repo => {
    if (/\bahead\b/.test(run("git", ["status", "-sb"], repo)))
      run("git", ["push"], repo)
  })
}

function grep(pattern) {
  let files = []
  let glob = require("glob")
  mods.forEach(repo => {
    files = files.concat(glob.sync(repo + "/src/*.js")).concat(glob.sync(repo + "/test/*.js"))
  })
  files = files.concat(glob.sync("website/src/**/*.js")).concat(glob.sync("website/pages/examples/*/*.js"))
  try {
    console.log(run("grep", ["--color", "-nH", "-e", pattern].concat(files.map(f => path.relative(origDir, f))), origDir))
  } catch(e) {
    process.exit(1)
  }
}

function runCmd(cmd, ...args) {
  mods.forEach(repo => {
    console.log(repo + ":")
    try {
      console.log(run(cmd, args, repo))
    } catch (e) {
      console.log(e.toString())
      process.exit(1)
    }
  })
}

function changes() {
  mods.forEach(repo => {
    let lastTag = run("git", ["describe", "master", "--tags", "--abbrev=0"], repo).trim()
    if (!lastTag) return console.log("No previous tag for " + repo + "\n")
    let history = run("git", ["log", lastTag + "..master"], repo).trim()
    if (history) console.log(repo + ":\n" + "=".repeat(repo.length + 1) + "\n\n" + history + "\n")
  })
}

function release(mod) {
  let currentVersion = require("../" + mod + "/package.json").version
  let changes = changelog(mod, currentVersion)
  let newVersion = bumpVersion(currentVersion, changes)
  console.log(`Creating prosemirror-${mod} ${newVersion}`)

  let notes = releaseNotes(mod, changes, newVersion)

  setModuleVersion(mod, newVersion)
  if (changes.breaking.length) setDepVersion(mod, newVersion)
  fs.writeFileSync(mod + "/CHANGELOG.md", notes.head + notes.body + fs.readFileSync(mod + "/CHANGELOG.md", "utf8"))
  run("git", ["add", "package.json"], mod)
  run("git", ["add", "CHANGELOG.md"], mod)
  run("git", ["commit", "-m", `Mark version ${newVersion}`], mod)
  run("git", ["tag", newVersion, "-m", `Version ${newVersion}\n\n${notes.body}`, "--cleanup=verbatim"], mod)
}

function changelog(repo, since) {
  let commits = run("git", ["log", "--format=%B", "--reverse", since + "..master"], repo)
  let result = {fix: [], feature: [], breaking: []}
  let re = /\n\r?\n(BREAKING|FIX|FEATURE):\s*([^]*?)(?=\r?\n\r?\n|\r?\n?$)/g, match
  while (match = re.exec(commits)) result[match[1].toLowerCase()].push(match[2].replace(/\r?\n/g, " "))
  return result
}

function bumpVersion(version, changes) {
  let [major, minor, patch] = version.split(".")
  if (changes.breaking.length) return `${Number(major) + 1}.0.0`
  if (changes.feature.length) return `${major}.${Number(minor) + 1}.0`
  if (changes.fix.length) return `${major}.${minor}.${Number(patch) + 1}`
  throw new Error("No new release notes!")
}

function releaseNotes(mod, changes, version) {
  let pad = n => n < 10 ? "0" + n : n
  let d = new Date, date = d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate())

  let types = {breaking: "Breaking changes", fix: "Bug fixes", feature: "New features"}

  let refTarget = "https://prosemirror.net/docs/ref/"
  let head = `## ${version} (${date})\n\n`, body = ""
  for (let type in types) {
    let messages = changes[type]
    if (messages.length) body += `### ${types[type]}\n\n`
    messages.forEach(message => body += message.replace(/\]\(##/g, "](" + refTarget + "#") + "\n\n")
  }
  return {head, body}
}

function setModuleVersion(mod, version) {
  let file = mod + "/package.json"
  fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace(/"version":\s*".*?"/, `"version": "${version}"`))
}

function setDepVersion(mod, version) {
  modsAndWebsite.forEach(repo => {
    if (repo == mod) return
    let file = repo + "/package.json", text = fs.readFileSync(file, "utf8")
    let result = text.replace(/"prosemirror-(.*?)":\s*".*?"/g, (match, dep) => {
      return dep == mod ? `"prosemirror-${mod}": "^${version}"` : match
    })
    if (result != text) {
      fs.writeFileSync(file, result)
      run("git", ["add", "package.json"], repo)
      run("git", ["commit", "-m", `Upgrade prosemirror-${mod} dependency`], repo)
    }
  })
}

function listModules() {
  console.log((process.argv.includes("--core") ? main : mods).join("\n"))
}

function watch() {
  const {watch} = require("rollup")
  let configs = mods.map(repo => {
    let conf = require("../" + repo + "/rollup.config")
    conf.input = path.resolve(repo, conf.input)
    conf.output.file = path.resolve(repo, conf.output.file)
    conf.watch = {exclude: ['node_modules/**']}
    return conf
  })
  let watcher = watch(configs), cwd = process.cwd()
  function name(input) { return input.slice(cwd.length + 1).match(/[^\/]*/)[0] }
  watcher.on("event", event => {
    if (event.code == "FATAL") {
      console.log(event.error + "")
      process.exit(1)
    } else if (event.code == "ERROR") {
      console.log(event.error + "")
    } else if (event.code == "BUNDLE_START") {
      console.log("Bundling " + name(event.input))
    } else if (event.code == "BUNDLE_END") {
      console.log("Finished bundling " + name(event.input))
    }
  })
  process.on("exit", () => watcher.close())
}

const pidFile = __dirname + "/.pm-dev.pid"
function devPID() {
  try { return JSON.parse(fs.readFileSync(pidFile, "utf8")) }
  catch(_) { return null }
}

function devStart() {
  let pid = devPID()
  if (pid != null) {
    try { run("ps", ["-p", String(pid)]) }
    catch (_) { pid = null }
  }
  if (pid != null) {
    console.log("Dev server already running at pid " + pid)
    return
  }

  fs.writeFileSync(pidFile, process.pid + "\n")
  function del() { fs.unlink(pidFile, () => {}); console.log("Stop") }
  function delAndExit() { del(); process.exit() }
  process.on("exit", del)
  process.on("SIGINT", delAndExit)
  process.on("SIGTERM", delAndExit)

  let root = path.resolve(__dirname, "../demo")
  let ecstatic = require("ecstatic")({root})
  let moduleserver = new (require("moduleserve/moduleserver"))({root})

  require("http").createServer(function(req, resp) {
    moduleserver.handleRequest(req, resp) || ecstatic(req, resp)
  }).listen(8080, process.argv.includes("--open") ? undefined : "127.0.0.1")
  console.log("Dev server listening on 8080")

  watch()
}

function devStop() {
  let pid = devPID()
  if (pid == null) {
    console.log("Dev server not running")
  } else {
    process.kill(pid, "SIGTERM")
    console.log("Killed dev server with pid " + pid)
  }
}

function massChange(file, pattern, replacement = "") {
  let re = new RegExp(pattern, "g")
  modsAndWebsite.forEach(repo => {
    let glob = require("glob")
    glob.sync(repo + "/" + file).forEach(file => {
      let content = fs.readFileSync(file, "utf8"), changed = content.replace(re, replacement)
      if (changed != content) {
        console.log("Updated " + file)
        fs.writeFileSync(file, changed)
      }
    })
  })
}

start()
<commit_msg>Allow browser variables in inputrules during linting<commit_after>#!/usr/bin/env node

let origDir = process.cwd()
process.chdir(__dirname + "/..")

// NOTE: Don't require anything from node_modules here, since the
// install script has to be able to run _before_ that exists.
let child = require("child_process"), fs = require("fs"), path = require("path")

let main = ["model", "transform", "state", "view",
            "keymap", "inputrules", "history", "collab", "commands", "gapcursor",
            "schema-basic", "schema-list"]
let mods = main.concat(["menu", "example-setup", "markdown", "dropcursor", "test-builder", "changeset"])
let modsAndWebsite = mods.concat("website")

function start() {
  let command = process.argv[2]
  if (command && !["install", "--help"].includes(command)) assertInstalled()
  let args = process.argv.slice(3)
  let cmdFn = {
    "status": status,
    "lint": lint,
    "commit": commit,
    "install": install,
    "build": build,
    "test": test,
    "push": push,
    "grep": grep,
    "run": runCmd,
    "watch": watch,
    "changes": changes,
    "modules": listModules,
    "release": release,
    "dev-start": devStart,
    "dev-stop": devStop,
    "mass-change": massChange,
    "--help": showHelp
  }[command]
  if (!cmdFn || cmdFn.length > args.length) help(1)
  cmdFn.apply(null, args)
}

function showHelp() {
  help(0)
}

function help(status) {
  console.log(`Usage:
  pm install [--ssh]      Clone and symlink the packages, install dependencies, build
  pm build                Build all modules
  pm status               Print out the git status of packages
  pm commit <args>        Run git commit in all packages that have changes
  pm push                 Run git push in packages that have new commits
  pm test                 Run the tests from all packages
  pm lint                 Run the linter over all packages
  pm watch                Set up a process that rebuilds the packages on change
  pm grep <pattern>       Grep through the source code for all packages
  pm run <command>        Run the given command in each of the package dirs
  pm changes              Show commits since the last release for all packages
  pm mass-change <files> <pattern> <replacement>
                          Run a regexp-replace on the matching files in each package
  pm release <module>     Generate a new release for the given module.
  pm modules [--core]     Emit a list of all package names
  pm dev-start            Start development server
  pm dev-stop             Stop development server, if running
  pm --help`)
  process.exit(status)
}

function assertInstalled() {
  modsAndWebsite.forEach(repo => {
    if (!fs.existsSync(repo)) {
      console.error("module `%s` is missing. Did you forget to run `pm install`?", repo)
      process.exit(1)
    }
  })
}

function run(cmd, args, wd) {
  return child.execFileSync(cmd, args, {cwd: wd, encoding: "utf8", stdio: ["ignore", "pipe", process.stderr]})
}

function status() {
  modsAndWebsite.forEach(repo => {
    let output = run("git", ["status", "-sb"], repo)
    if (output != "## master...origin/master\n")
      console.log(repo + ":\n" + run("git", ["status"], repo))
  })
}

function lintOptions(browser) {
  return {
    browser,
    ecmaVersion: 6,
    semicolons: false,
    namedFunctions: true,
    trailingCommas: true
  }
}

function lint() {
  let blint = require("blint")
  mods.forEach(repo => {
    let options = lintOptions(["view", "menu", "example-setup", "dropcursor", "gapcursor", "inputrules"].indexOf(repo) > -1)
    blint.checkDir(repo + "/src/", options)
    if (fs.existsSync(repo + "/test")) {
      options.allowedGlobals = ["it", "describe"]
      blint.checkDir(repo + "/test/", options)
    }
  })
  let websiteOptions = Object.assign(lintOptions(true), {
    allowedGlobals: ["__dirname", "process"],
    console: true
  })
  blint.checkDir("website/src/", websiteOptions)
  require("glob").sync("website/pages/examples/*/example.js").forEach(file => blint.checkFile(file, websiteOptions))
}

function commit(...args) {
  modsAndWebsite.forEach(repo => {
    if (run("git", ["diff"], repo) || run("git", ["diff", "--cached"], repo))
      console.log(repo + ":\n" + run("git", ["commit"].concat(args), repo))
  })
}

function install(arg = null) {
  let base = "https://github.com/prosemirror/"
  if (arg == "--ssh") { base = "git@github.com:ProseMirror/" }
  else if (arg != null) help(1)

  modsAndWebsite.forEach(repo => {
    if (fs.existsSync(repo)) {
      console.warn("Skipping cloning of " + repo + " (directory exists)")
      return
    }
    let origin = base + (repo == "website" ? "" : "prosemirror-") + repo + ".git"
    run("git", ["clone", origin, repo])
  })

  console.log("Running yarn install")
  run("yarn", ["install"])
  console.log("Building modules")
  build()
}

function build() {
  mods.forEach(repo => {
    console.log(repo + "...")
    run("npm", ["run", "build"], repo)
  })
}

function test() {
  let mocha = new (require("mocha"))
  mods.forEach(repo => {
    if (repo == "view" || !fs.existsSync(repo + "/test")) return
    fs.readdirSync(repo + "/test").forEach(file => {
      if (/^test-/.test(file)) mocha.addFile(repo + "/test/" + file)
    })
  })
  mocha.run(failures => process.exit(failures))
}

function push() {
  modsAndWebsite.forEach(repo => {
    if (/\bahead\b/.test(run("git", ["status", "-sb"], repo)))
      run("git", ["push"], repo)
  })
}

function grep(pattern) {
  let files = []
  let glob = require("glob")
  mods.forEach(repo => {
    files = files.concat(glob.sync(repo + "/src/*.js")).concat(glob.sync(repo + "/test/*.js"))
  })
  files = files.concat(glob.sync("website/src/**/*.js")).concat(glob.sync("website/pages/examples/*/*.js"))
  try {
    console.log(run("grep", ["--color", "-nH", "-e", pattern].concat(files.map(f => path.relative(origDir, f))), origDir))
  } catch(e) {
    process.exit(1)
  }
}

function runCmd(cmd, ...args) {
  mods.forEach(repo => {
    console.log(repo + ":")
    try {
      console.log(run(cmd, args, repo))
    } catch (e) {
      console.log(e.toString())
      process.exit(1)
    }
  })
}

function changes() {
  mods.forEach(repo => {
    let lastTag = run("git", ["describe", "master", "--tags", "--abbrev=0"], repo).trim()
    if (!lastTag) return console.log("No previous tag for " + repo + "\n")
    let history = run("git", ["log", lastTag + "..master"], repo).trim()
    if (history) console.log(repo + ":\n" + "=".repeat(repo.length + 1) + "\n\n" + history + "\n")
  })
}

function release(mod) {
  let currentVersion = require("../" + mod + "/package.json").version
  let changes = changelog(mod, currentVersion)
  let newVersion = bumpVersion(currentVersion, changes)
  console.log(`Creating prosemirror-${mod} ${newVersion}`)

  let notes = releaseNotes(mod, changes, newVersion)

  setModuleVersion(mod, newVersion)
  if (changes.breaking.length) setDepVersion(mod, newVersion)
  fs.writeFileSync(mod + "/CHANGELOG.md", notes.head + notes.body + fs.readFileSync(mod + "/CHANGELOG.md", "utf8"))
  run("git", ["add", "package.json"], mod)
  run("git", ["add", "CHANGELOG.md"], mod)
  run("git", ["commit", "-m", `Mark version ${newVersion}`], mod)
  run("git", ["tag", newVersion, "-m", `Version ${newVersion}\n\n${notes.body}`, "--cleanup=verbatim"], mod)
}

function changelog(repo, since) {
  let commits = run("git", ["log", "--format=%B", "--reverse", since + "..master"], repo)
  let result = {fix: [], feature: [], breaking: []}
  let re = /\n\r?\n(BREAKING|FIX|FEATURE):\s*([^]*?)(?=\r?\n\r?\n|\r?\n?$)/g, match
  while (match = re.exec(commits)) result[match[1].toLowerCase()].push(match[2].replace(/\r?\n/g, " "))
  return result
}

function bumpVersion(version, changes) {
  let [major, minor, patch] = version.split(".")
  if (changes.breaking.length) return `${Number(major) + 1}.0.0`
  if (changes.feature.length) return `${major}.${Number(minor) + 1}.0`
  if (changes.fix.length) return `${major}.${minor}.${Number(patch) + 1}`
  throw new Error("No new release notes!")
}

function releaseNotes(mod, changes, version) {
  let pad = n => n < 10 ? "0" + n : n
  let d = new Date, date = d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate())

  let types = {breaking: "Breaking changes", fix: "Bug fixes", feature: "New features"}

  let refTarget = "https://prosemirror.net/docs/ref/"
  let head = `## ${version} (${date})\n\n`, body = ""
  for (let type in types) {
    let messages = changes[type]
    if (messages.length) body += `### ${types[type]}\n\n`
    messages.forEach(message => body += message.replace(/\]\(##/g, "](" + refTarget + "#") + "\n\n")
  }
  return {head, body}
}

function setModuleVersion(mod, version) {
  let file = mod + "/package.json"
  fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace(/"version":\s*".*?"/, `"version": "${version}"`))
}

function setDepVersion(mod, version) {
  modsAndWebsite.forEach(repo => {
    if (repo == mod) return
    let file = repo + "/package.json", text = fs.readFileSync(file, "utf8")
    let result = text.replace(/"prosemirror-(.*?)":\s*".*?"/g, (match, dep) => {
      return dep == mod ? `"prosemirror-${mod}": "^${version}"` : match
    })
    if (result != text) {
      fs.writeFileSync(file, result)
      run("git", ["add", "package.json"], repo)
      run("git", ["commit", "-m", `Upgrade prosemirror-${mod} dependency`], repo)
    }
  })
}

function listModules() {
  console.log((process.argv.includes("--core") ? main : mods).join("\n"))
}

function watch() {
  const {watch} = require("rollup")
  let configs = mods.map(repo => {
    let conf = require("../" + repo + "/rollup.config")
    conf.input = path.resolve(repo, conf.input)
    conf.output.file = path.resolve(repo, conf.output.file)
    conf.watch = {exclude: ['node_modules/**']}
    return conf
  })
  let watcher = watch(configs), cwd = process.cwd()
  function name(input) { return input.slice(cwd.length + 1).match(/[^\/]*/)[0] }
  watcher.on("event", event => {
    if (event.code == "FATAL") {
      console.log(event.error + "")
      process.exit(1)
    } else if (event.code == "ERROR") {
      console.log(event.error + "")
    } else if (event.code == "BUNDLE_START") {
      console.log("Bundling " + name(event.input))
    } else if (event.code == "BUNDLE_END") {
      console.log("Finished bundling " + name(event.input))
    }
  })
  process.on("exit", () => watcher.close())
}

const pidFile = __dirname + "/.pm-dev.pid"
function devPID() {
  try { return JSON.parse(fs.readFileSync(pidFile, "utf8")) }
  catch(_) { return null }
}

function devStart() {
  let pid = devPID()
  if (pid != null) {
    try { run("ps", ["-p", String(pid)]) }
    catch (_) { pid = null }
  }
  if (pid != null) {
    console.log("Dev server already running at pid " + pid)
    return
  }

  fs.writeFileSync(pidFile, process.pid + "\n")
  function del() { fs.unlink(pidFile, () => {}); console.log("Stop") }
  function delAndExit() { del(); process.exit() }
  process.on("exit", del)
  process.on("SIGINT", delAndExit)
  process.on("SIGTERM", delAndExit)

  let root = path.resolve(__dirname, "../demo")
  let ecstatic = require("ecstatic")({root})
  let moduleserver = new (require("moduleserve/moduleserver"))({root})

  require("http").createServer(function(req, resp) {
    moduleserver.handleRequest(req, resp) || ecstatic(req, resp)
  }).listen(8080, process.argv.includes("--open") ? undefined : "127.0.0.1")
  console.log("Dev server listening on 8080")

  watch()
}

function devStop() {
  let pid = devPID()
  if (pid == null) {
    console.log("Dev server not running")
  } else {
    process.kill(pid, "SIGTERM")
    console.log("Killed dev server with pid " + pid)
  }
}

function massChange(file, pattern, replacement = "") {
  let re = new RegExp(pattern, "g")
  modsAndWebsite.forEach(repo => {
    let glob = require("glob")
    glob.sync(repo + "/" + file).forEach(file => {
      let content = fs.readFileSync(file, "utf8"), changed = content.replace(re, replacement)
      if (changed != content) {
        console.log("Updated " + file)
        fs.writeFileSync(file, changed)
      }
    })
  })
}

start()
<|endoftext|>


<commit_before>query = "";
page = 1;
$(document).ready(function(){
 url = location.search;

 function Display_Load() {
  $(".spinner").fadeIn(900,0);
  $(".spinner").html("");
 };

 function Hide_Load() {
  $(".spinner").fadeOut('slow');
 };

 function Next_Results(){
  Display_Load(); //Show spinner
  var pageNum = this.id; //Set page number
  if (!(query == "")) {
   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=" + pageNum + query, function () { Build_Pagination() }); //Load data to page then rebuild Build_Pagination function
  } else {
   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=" + pageNum + "&filter[terms][0][attr]=MonitorName&filter[terms][0][op]==&filter[terms][0][val]=" + monitorName, function () { Build_Pagination() }); //Load data to page then rebuild Build_Pagination function
  }
 };

$("#btnPlay").click(function(){
 start = setInterval(function(){changeClass()}, 200);
 $("#btnPause").css("border", "1px solid #C5DBEC");
 $(this).css('border', "1px solid red");
});

function changeClass() {
 if (z<x){
  $("#img_" + (z-1)).attr("class", "eventImageHide");
  $("#img_" + z).attr("class", "eventImage");
  z++;
 }
};

 function Build_Pagination() {
  Hide_Load();  //Hide spinner
  var monitorName = $("#inptMonitorName").attr("value"); // Get the currently selected monitor.  This is only needed for the first page load, before any filters are set.

 // Auto-check the default monitor filter box
 $("#sidebarHistory input").each(function() {
  if ((this.id) == $("#inptMonitorName").attr("value")) {
   $(this).attr("checked", true);
  }
 });

  var galleries = $('.ad-gallery').adGallery({
   slideshow: {enable: false},
   callbacks: {
    afterImageVisible: function() {
     z = 0;
    if (!$("#btnPlay").attr('disabled')) {
     $("#btnPlay").attr('disabled', 'disabled');
     $("#btnPlay").addClass('ui-button-disabled ui-state-disabled');
    }
var context = this;
var src = $('#img_0').attr('src');
var width = $('#img_0').css('width');
var height = $('#img_0').css('height');
var style = 'style="width:' + width + '; height:' + height + ';"';
var pos = src.lastIndexOf('/');
path = src.substr(0,pos+1); // This is the path to the event image directory
var imgs = new Array();

$.post("skins/new/includes/getFiles.php?path=" + path, function(data){ // Get the list of files
 imgs = data.split(" "); // Push the list into the array
 x = imgs.length -1; // Number of images
 y = 1; // Loaded image counter
 for (var i=1;i<x;i++){
  $.preLoadImages(imgs[i], function(){ // Preload the image, then,
   y++;
   var percent = (y / x);
   var result = Math.round(percent*100);
   $("#progress").html("Loading... " + result + "%");
   if (x == y){ // All images are loaded; enable btnPlay
    $("#btnPlay").removeAttr('disabled');
    $("#btnPlay").removeClass('ui-button-disabled ui-state-disabled');
   };
  });
  $(".ad-image").append('');
 };

 $("#btnStills").colorbox({iframe:true, width:'75%', height:'75%', href:'skins/new/views/stills.php?path='+path});

$('.ad-forward').click(function(){
 var divwidth = $('.ad-thumbs').width(); // The width of the continer (how many px are shown at once)
 var width = $('.ad-thumb-list').width(); // Width of

 var left = $('.ad-thumbs').scrollLeft(); // How far Left I am
 if (width == (divwidth + left)){
  page = page + 1;
  $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=" + page + query, function(data){
   $(".ad-thumb-list").append(data);
   Build_Pagination()
  });
 };
});

});

    }
   }
  });
 };

 $("#btnSubmit").click(function() {
  Display_Load();
  Build_Query();
  Hide_Load();
 });

 Display_Load(); //First thing that happens - display spinner
 $(".ad-thumb-list").load("skins/new/views/pagination_data.php" + url, function(){ //Second, load data into .ad-thumb-list then build Build_Pagination function
   Build_Pagination();
 });

 $('#sidebarHistory li input').change(function() { //When a checkbox is checked
  monitorName = this.id;
  Display_Load();
  Build_Query();
  Hide_Load();
 });

 function Build_Query() {
  var aryMonitors = [];

  $("#sidebarHistory input:checked").each(function() { // For each checked monitor
   aryMonitors.push(this.id); // Push its name into the array
  });
  var x = aryMonitors.length; // Number of checked monitors

  var Dfrom = $("#inptDateFrom").val();
  var Dto = $("#inptDateTo").val();
  var Tfrom = $("#inptTimeFrom").val();
  var Tto = $("#inptTimeTo").val();
  var eid = $("#inptEventID").val();

  // First filters are Monitor Names, lets do those!
  for (var i=0;i<x;i++) {
   if (x==1) { // Only filter, no ( or )
    query = "&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=0";
   } else if (i == 0){ // First filter, open the (
    query = "&filter[terms][" + i + "][obr]=1&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=0";
   } else if ( !(i==0) && (i<(x-1)) ) { // Any filter that is not the first or last, no ( or )
    query += "&filter[terms][" + i + "][cnj]=or&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=0";
   } else { // Last filter, close the )
    query += "&filter[terms][" + i + "][cnj]=or&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=1";
   }
  };

  // Next filters are dates, if filled in
  if ((Dfrom != "") && (Dto != "")) {
   query +=  "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Date&filter[terms][" + i + "][op]=%3E%3D&filter[terms][" + i + "][val]=" + Dfrom + "&filter[terms][" + i + "][cbr]=0";
   i++;
   query += "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Date&filter[terms][" + i + "][op]=%3C%3D&filter[terms][" + i + "][val]=" + Dto + "&filter[terms][" + i + "][cbr]=0";
  }

  // Next filters are times, if filed in
  if ((Tfrom != "") && (Tto != "")) {
   i++;
   query +=  "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Time&filter[terms][" + i + "][op]=%3E&filter[terms][" + i + "][val]=" + Tfrom + "&filter[terms][" + i + "][cbr]=0";
   i++;
   query += "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Time&filter[terms][" + i + "][op]=%3C&filter[terms][" + i + "][val]=" + Tto + "&filter[terms][" + i + "][cbr]=0";
  }

  // Last filter is a specific event ID.  If filled in, filter on only that.
  if (eid >= 1) {
   i = 0;
   query =  "&filter[terms][" + i + "][attr]=Id&filter[terms][" + i + "][op]=%3D&filter[terms][" + i + "][val]=" + eid;
  }

   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=1" + query, function() { Build_Pagination()}); // Load data into .ad-thumb-list

 };
});
<commit_msg>Moved code that does filter posting out of Build_Query(), so that it can be used for generic query building.<commit_after>query = "";
page = 1;
$(document).ready(function(){
 url = location.search;

 function Display_Load() {
  $(".spinner").fadeIn(900,0);
  $(".spinner").html("");
 };

 function Hide_Load() {
  $(".spinner").fadeOut('slow');
 };

 function Next_Results(){
  Display_Load(); //Show spinner
  var pageNum = this.id; //Set page number
  if (!(query == "")) {
   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=" + pageNum + query, function () { Build_Pagination() }); //Load data to page then rebuild Build_Pagination function
  } else {
   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=" + pageNum + "&filter[terms][0][attr]=MonitorName&filter[terms][0][op]==&filter[terms][0][val]=" + monitorName, function () { Build_Pagination() }); //Load data to page then rebuild Build_Pagination function
  }
 };

$("#btnPlay").click(function(){
 start = setInterval(function(){changeClass()}, 200);
 $("#btnPause").css("border", "1px solid #C5DBEC");
 $(this).css('border', "1px solid red");
});

function changeClass() {
 if (z<x){
  $("#img_" + (z-1)).attr("class", "eventImageHide");
  $("#img_" + z).attr("class", "eventImage");
  z++;
 }
};

 function Build_Pagination() {
  Hide_Load();  //Hide spinner
  var monitorName = $("#inptMonitorName").attr("value"); // Get the currently selected monitor.  This is only needed for the first page load, before any filters are set.

 // Auto-check the default monitor filter box
 $("#sidebarHistory input").each(function() {
  if ((this.id) == $("#inptMonitorName").attr("value")) {
   $(this).attr("checked", true);
  }
 });

  var galleries = $('.ad-gallery').adGallery({
   slideshow: {enable: false},
   callbacks: {
    afterImageVisible: function() {
     z = 0;
    if (!$("#btnPlay").attr('disabled')) {
     $("#btnPlay").attr('disabled', 'disabled');
     $("#btnPlay").addClass('ui-button-disabled ui-state-disabled');
    }
var context = this;
var src = $('#img_0').attr('src');
var width = $('#img_0').css('width');
var height = $('#img_0').css('height');
var style = 'style="width:' + width + '; height:' + height + ';"';
var pos = src.lastIndexOf('/');
path = src.substr(0,pos+1); // This is the path to the event image directory
var imgs = new Array();

$.post("skins/new/includes/getFiles.php?path=" + path, function(data){ // Get the list of files
 imgs = data.split(" "); // Push the list into the array
 x = imgs.length -1; // Number of images
 y = 1; // Loaded image counter
 for (var i=1;i<x;i++){
  $.preLoadImages(imgs[i], function(){ // Preload the image, then,
   y++;
   var percent = (y / x);
   var result = Math.round(percent*100);
   $("#progress").html("Loading... " + result + "%");
   if (x == y){ // All images are loaded; enable btnPlay
    $("#btnPlay").removeAttr('disabled');
    $("#btnPlay").removeClass('ui-button-disabled ui-state-disabled');
   };
  });
  $(".ad-image").append('');
 };

 $("#btnStills").colorbox({iframe:true, width:'75%', height:'75%', href:'skins/new/views/stills.php?path='+path});

$('.ad-forward').click(function(){
 var divwidth = $('.ad-thumbs').width(); // The width of the continer (how many px are shown at once)
 var width = $('.ad-thumb-list').width(); // Width of

 var left = $('.ad-thumbs').scrollLeft(); // How far Left I am
 if (width == (divwidth + left)){
  page = page + 1;
  $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=" + page + query, function(data){
   $(".ad-thumb-list").append(data);
   Build_Pagination()
  });
 };
});

});

    }
   }
  });
 };

 $("#btnSubmit").click(function() {
  Display_Load();
  Build_Query();
   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=1" + query, function() { Build_Pagination()}); // Load data into .ad-thumb-list
  Hide_Load();
 });

 Display_Load(); //First thing that happens - display spinner
 $(".ad-thumb-list").load("skins/new/views/pagination_data.php" + url, function(){ //Second, load data into .ad-thumb-list then build Build_Pagination function
   Build_Pagination();
 });

 $('#sidebarHistory li input').change(function() { //When a checkbox is checked
  monitorName = this.id;
  Display_Load();
  Build_Query();
   $(".ad-thumb-list").load("skins/new/views/pagination_data.php?page=1" + query, function() { Build_Pagination()}); // Load data into .ad-thumb-list
  Hide_Load();
 });

 function Build_Query() {
  var aryMonitors = [];

  $("#sidebarHistory input:checked").each(function() { // For each checked monitor
   aryMonitors.push(this.id); // Push its name into the array
  });
  var x = aryMonitors.length; // Number of checked monitors

  var Dfrom = $("#inptDateFrom").val();
  var Dto = $("#inptDateTo").val();
  var Tfrom = $("#inptTimeFrom").val();
  var Tto = $("#inptTimeTo").val();
  var eid = $("#inptEventID").val();

  // First filters are Monitor Names, lets do those!
  for (var i=0;i<x;i++) {
   if (x==1) { // Only filter, no ( or )
    query = "&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=0";
   } else if (i == 0){ // First filter, open the (
    query = "&filter[terms][" + i + "][obr]=1&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=0";
   } else if ( !(i==0) && (i<(x-1)) ) { // Any filter that is not the first or last, no ( or )
    query += "&filter[terms][" + i + "][cnj]=or&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=0";
   } else { // Last filter, close the )
    query += "&filter[terms][" + i + "][cnj]=or&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=MonitorName&filter[terms][" + i + "][op]==&filter[terms][" + i + "][val]=" + aryMonitors[i] + "&filter[terms][" + i + "][cbr]=1";
   }
  };

  // Next filters are dates, if filled in
  if ((Dfrom != "") && (Dto != "")) {
   query +=  "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Date&filter[terms][" + i + "][op]=%3E%3D&filter[terms][" + i + "][val]=" + Dfrom + "&filter[terms][" + i + "][cbr]=0";
   i++;
   query += "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Date&filter[terms][" + i + "][op]=%3C%3D&filter[terms][" + i + "][val]=" + Dto + "&filter[terms][" + i + "][cbr]=0";
  }

  // Next filters are times, if filed in
  if ((Tfrom != "") && (Tto != "")) {
   i++;
   query +=  "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Time&filter[terms][" + i + "][op]=%3E&filter[terms][" + i + "][val]=" + Tfrom + "&filter[terms][" + i + "][cbr]=0";
   i++;
   query += "&filter[terms][" + i + "][cnj]=and&filter[terms][" + i + "][obr]=0&filter[terms][" + i + "][attr]=Time&filter[terms][" + i + "][op]=%3C&filter[terms][" + i + "][val]=" + Tto + "&filter[terms][" + i + "][cbr]=0";
  }

  // Last filter is a specific event ID.  If filled in, filter on only that.
  if (eid >= 1) {
   i = 0;
   query =  "&filter[terms][" + i + "][attr]=Id&filter[terms][" + i + "][op]=%3D&filter[terms][" + i + "][val]=" + eid;
  }

  return(query);

 };
});
<|endoftext|>