<commit_before>Openure = {
    allViews: [],
    currentView: "",
    listener: "",
    trackedViewsIDs: [],

    findViewsInRegion: function(region) {
        this.findViewsInView(region.currentView);
    },

    findViewsInView: function(view) {
        if (view.cid && _.lastIndexOf(this.trackedViewsIDs, view.cid) == -1) {
            this.trackedViewsIDs.push(view.cid);
            for(var prop in view) {
                this.findViewsAndRegionsInObject(view[prop]);
            }
            this.allViews.push(view);
        }
    },

    findViewsAndRegionsInObject: function(obj) {
        for(var prop in obj) {
            if (obj[prop] instanceof Backbone.ChildViewContainer) {
                obj[prop].each(function(subview) {
                    this.findViewsInView(subview);
                }, this);
            }
            else if (obj[prop] instanceof Marionette.Region) {
                this.findViewsInRegion(obj[prop]);
            }
            else if (obj[prop] instanceof Marionette.View) {
                this.findViewsInView(obj[prop]);
            }
            else if (obj[prop] instanceof Marionette.Application) {
                this.findViewsAndRegionsInObject(obj[prop]);
            }
        }
    },

    applySelectedView: function() {
        console.log("rock the view - " + Openure.currentView.cid);

        var jqconsole = document.createElement('div');

        jqconsole.style.cssText = 'position:absolute;width:400px;height:500px;background-color:black';
        jqconsole.id = "console";

        this.currentView.el.appendChild(jqconsole);

// Creating the console.
        var header = 'Welcome to JQConsole!\n' +
            'Use jqconsole.Write() to write and ' +
            'jqconsole.Input() to read.\n';
        this.jqconsole = $('#console').jqconsole(header, 'JS> ');

// Abort prompt on Ctrl+Z.
        this.jqconsole.RegisterShortcut('Z', function() {
            this.jqconsole.AbortPrompt();
            handler();
        });

// Move to line start Ctrl+A.
        this.jqconsole.RegisterShortcut('A', function() {
            this.jqconsole.MoveToStart();
            handler();
        });

// Move to line end Ctrl+E.
        this.jqconsole.RegisterShortcut('E', function() {
            this.jqconsole.MoveToEnd();
            handler();
        });

        this.jqconsole.RegisterMatching('{', '}', 'brace');
        this.jqconsole.RegisterMatching('(', ')', 'paran');
        this.jqconsole.RegisterMatching('[', ']', 'bracket');
// Handle a command.
        var handler = _.bind(function(command) {
            if (command) {
                try {
                    this.jqconsole.Write(window.eval(command));
                    this.jqconsole.Write('\n');
                } catch (e) {
                    this.jqconsole.Write('ERROR: ' + e.message + '\n');
                }
            }
            this.jqconsole.Prompt(true, handler, function(command) {
                // Continue line if can't compile the command.
                try {
                    Function(command);
                } catch (e) {
                    if (/[\[\{\(]$/.test(command)) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
                return false;
            });
        }, this);

// Initiate the first prompt.
        handler();

        model = this.currentView.model;
        view = this.currentView;
        collection = this.currentView.collection;
        clearInterval(this.listener);
    },

    go: function() {
        this.findViewsAndRegionsInObject(window);

        _.each(this.allViews, function(view) {
            view.$el[0].addEventListener('click', _.bind(function(e) {
                if(e.metaKey && e.shiftKey) {
                    var ownIt = _.bind(this.applySelectedView, this);

                    clearInterval(this.listener);
                    this.listener = setInterval(ownIt, 100);

                    e.preventDefault();
                    this.currentView = view;
                }
            }, this), true);
        }, this);
    }
};

$(function () {
    Openure.go();
});
<commit_msg>print json objects better<commit_after>Openure = {
    allViews: [],
    currentView: "",
    listener: "",
    trackedViewsIDs: [],

    findViewsInRegion: function(region) {
        this.findViewsInView(region.currentView);
    },

    findViewsInView: function(view) {
        if (view.cid && _.lastIndexOf(this.trackedViewsIDs, view.cid) == -1) {
            this.trackedViewsIDs.push(view.cid);
            for(var prop in view) {
                this.findViewsAndRegionsInObject(view[prop]);
            }
            this.allViews.push(view);
        }
    },

    findViewsAndRegionsInObject: function(obj) {
        for(var prop in obj) {
            if (obj[prop] instanceof Backbone.ChildViewContainer) {
                obj[prop].each(function(subview) {
                    this.findViewsInView(subview);
                }, this);
            }
            else if (obj[prop] instanceof Marionette.Region) {
                this.findViewsInRegion(obj[prop]);
            }
            else if (obj[prop] instanceof Marionette.View) {
                this.findViewsInView(obj[prop]);
            }
            else if (obj[prop] instanceof Marionette.Application) {
                this.findViewsAndRegionsInObject(obj[prop]);
            }
        }
    },

    applySelectedView: function() {
        console.log("rock the view - " + Openure.currentView.cid);

        var jqconsole = document.createElement('div');

        jqconsole.style.cssText = 'position:absolute;width:400px;height:500px;background-color:black';
        jqconsole.id = "console";

        this.currentView.el.appendChild(jqconsole);

// Creating the console.
        var header = 'Welcome to JQConsole!\n' +
            'Use jqconsole.Write() to write and ' +
            'jqconsole.Input() to read.\n';
        this.jqconsole = $('#console').jqconsole(header, 'JS> ');

// Abort prompt on Ctrl+Z.
        this.jqconsole.RegisterShortcut('Z', function() {
            this.jqconsole.AbortPrompt();
            handler();
        });

// Move to line start Ctrl+A.
        this.jqconsole.RegisterShortcut('A', function() {
            this.jqconsole.MoveToStart();
            handler();
        });

// Move to line end Ctrl+E.
        this.jqconsole.RegisterShortcut('E', function() {
            this.jqconsole.MoveToEnd();
            handler();
        });

        this.jqconsole.RegisterMatching('{', '}', 'brace');
        this.jqconsole.RegisterMatching('(', ')', 'paran');
        this.jqconsole.RegisterMatching('[', ']', 'bracket');

        isObject = function(obj) {
            return obj === Object(obj);
        };

// Handle a command.
        var handler = _.bind(function(command) {
            if (command) {
                try {
                    var result = window.eval(command);
                } catch (e) {
                    this.jqconsole.Write('ERROR: ' + e.message + '\n');
                }
                try {
                    if(isObject(result)) {
                        result = JSON.stringify(result, undefined, 2);
                    }
                } catch (e) {
                    if (e.message === 'Converting circular structure to JSON') {
                        this.jqconsole.Write('ERROR: ' + e.message + '\n');
                        this.jqconsole.Write('Please try the same command in the chrome console.\n');
                    }
                    else {
                        this.jqconsole.Write('ERROR: ' + e.message + '\n');
                    }
                }

                this.jqconsole.Write(result);
                this.jqconsole.Write('\n');
            }
            this.jqconsole.Prompt(true, handler, function(command) {
                // Continue line if can't compile the command.
                try {
                    Function(command);
                } catch (e) {
                    if (/[\[\{\(]$/.test(command)) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
                return false;
            });
        }, this);

// Initiate the first prompt.
        handler();

        model = this.currentView.model;
        view = this.currentView;
        collection = this.currentView.collection;
        clearInterval(this.listener);
    },

    go: function() {
        this.findViewsAndRegionsInObject(window);

        _.each(this.allViews, function(view) {
            view.$el[0].addEventListener('click', _.bind(function(e) {
                if(e.metaKey && e.shiftKey) {
                    var ownIt = _.bind(this.applySelectedView, this);

                    clearInterval(this.listener);
                    this.listener = setInterval(ownIt, 100);

                    e.preventDefault();
                    this.currentView = view;
                }
            }, this), true);
        }, this);
    }
};

$(function () {
    Openure.go();
});
<|endoftext|>


<commit_before>function JSEvalKruecke(){}

JSEvalKruecke.prototype = {

    callEval: function (code)
    {
        return opener.eval(code);
    },

    QueryInterface: function (iid) {
        if (!iid.equals(Components.interfaces.IJSEvalKruecke)
            && !iid.equals(Components.interfaces.nsISupports))
        {
            throw Components.results.NS_ERROR_NO_INTERFACE;
        }
        return this;
    }
}

var Module = {
    firstTime: true,

    registerSelf: function (compMgr, fileSpec, location, type) {
        if (this.firstTime) {
            this.firstTime = false;
            throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
        }
        compMgr =
            compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        compMgr.registerFactoryLocation(this.myCID,
                                        "JSEvalKruecke",
                                        this.myProgID,
                                        fileSpec,
                                        location,
                                        type);
    },

    getClassObject : function (compMgr, cid, iid) {
        if (!cid.equals(this.myCID))
            throw Components.results.NS_ERROR_NO_INTERFACE
        if (!iid.equals(Components.interfaces.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
        return this.myFactory;
    },

    myCID: Components.ID("{4ec47a4f-ef4a-4609-907b-7656d4208957}"),
    myProgID: "@c-base.org/jsevalkruecke;1",

    myFactory: {
        createInstance: function (outer, iid) {
            if (outer != null)
                throw Components.results.NS_ERROR_NO_AGGREGATION;
            return (new JSEvalKruecke()).QueryInterface(iid);
        }
    },

    canUnload: function(compMgr) {
        return true;
    }
};

function NSGetModule(compMgr, fileSpec) { return Module; }

<commit_msg>*** empty log message ***<commit_after><|endoftext|>


<commit_before>(function () {
    $.widget("execut.GridView", {
        _create: function () {
            var t = this;
            t._initElements();
            t._initEvents();
        },
        _initElements: function () {
            var t = this,
                el = t.element;
            if (typeof t.options.updateUrl !== 'undefined') {
                el.find('tr[data-key]').click(function (e) {
                    var trEl = $(this),
                        targetEl = $(e.target);
                    if (!(targetEl.parents('a').length || targetEl.is('a'))) {
                        var id = trEl.attr('data-id'),
                            url = t.options.updateUrl,
                            delimiter = null;
                        if (url.search('\\?') !== 0) {
                            delimiter = '&';
                        } else {
                            delimiter = '?';
                        }

                        location.href = url + delimiter + 'id=' + id;
                    }
                });
            }
        },
        _initEvents: function () {
            var t = this;
        }
    })
})();<commit_msg>Fixed bug with urls with ?<commit_after>(function () {
    $.widget("execut.GridView", {
        _create: function () {
            var t = this;
            t._initElements();
            t._initEvents();
        },
        _initElements: function () {
            var t = this,
                el = t.element;
            if (typeof t.options.updateUrl !== 'undefined') {
                el.find('tr[data-key]').click(function (e) {
                    var trEl = $(this),
                        targetEl = $(e.target);
                    if (!(targetEl.parents('a').length || targetEl.is('a'))) {
                        var id = trEl.attr('data-id'),
                            url = t.options.updateUrl,
                            delimiter = null;
                        if (url.search('\\?') !== -1) {
                            delimiter = '&';
                        } else {
                            delimiter = '?';
                        }

                        location.href = url + delimiter + 'id=' + id;
                    }
                });
            }
        },
        _initEvents: function () {
            var t = this;
        }
    })
})();<|endoftext|>


<commit_before>var benchmarks = {
    "gold_per_min": function(m, p)
    {
        return p.gold_per_min;
    },
    "xp_per_min": function(m, p)
    {
        return p.xp_per_min;
    },
    "kills_per_min": function(m, p)
    {
        return (p.kills / m.duration * 60);
    },
    "last_hits_per_min": function(m, p)
    {
        return (p.last_hits / m.duration * 60);
    },
    "hero_damage_per_min": function(m, p)
    {
        return (p.hero_damage / m.duration * 60);
    },
    "hero_healing_per_min": function(m, p)
    {
        return (p.hero_healing / m.duration * 60);
    },
    "tower_damage_per_min": function(m, p)
    {
        return (p.tower_damage / m.duration * 60);
    },
};
module.exports = benchmarks;
<commit_msg>Update benchmarks.js<commit_after>var benchmarks = {
    "gold_per_min": function(m, p)
    {
        return p.gold_per_min;
    },
    "xp_per_min": function(m, p)
    {
        return p.xp_per_min;
    },
    "kills_per_min": function(m, p)
    {
        return (p.kills / m.duration * 60);
    },
    "last_hits_per_min": function(m, p)
    {
        return (p.last_hits / m.duration * 60);
    },
    "hero_damage_per_min": function(m, p)
    {
        return (p.hero_damage / m.duration * 60);
    },
    "hero_healing_per_min": function(m, p)
    {
        return (p.hero_healing / m.duration * 60);
    },
    "tower_damage": function(m, p)
    {
        return (p.tower_damage);
    },
};
module.exports = benchmarks;
<|endoftext|>


<commit_before>function byTime (a, b) {
  const earlier = (new Date(a.EventEnqueuedUtcTime.toString())).getTime() > (new Date(b.EventEnqueuedUtcTime.toString())).getTime();
  if (earlier) {
    return -1;
  }
  if (!earlier) {
    return 1;
  }
  return 0;
}

module.exports.getLastNRows = function(azure, tableService, columns, n, callback) {
  const query = new azure.TableQuery()
  .select(columns)
  .top(n)

  tableService.queryEntities(process.env.TABLE_NAME, query, null, function(error, result, response) {
    console.log(error);
    if (error) return callback(error, []);

      // each prop in the results comes back with a nested prop of `_`,
      // so this flattens the props and filters out metadata prop also
      const rows = result.entries.map(e => {
        return Object.keys(e)
          .filter(k => k !== '.metadata')
          .reduce((a, b) => {
            const flatProp = { [b]: e[b]._ };
            return Object.assign(a, flatProp);
          }, {});
      });

      rows.sort(byTime);

      return callback(null, rows);
  });
}<commit_msg>use switch case for sorting<commit_after>function byTime (a, b) {
  const earlier = (new Date(a.EventEnqueuedUtcTime.toString())).getTime() > (new Date(b.EventEnqueuedUtcTime.toString())).getTime();

  switch (earlier) {
    case true:
      return -1;
      break;

    case false:
      return 1;
      break;

    default:
      return 0;
  }
}

module.exports.getLastNRows = function(azure, tableService, columns, n, callback) {
  const query = new azure.TableQuery()
  .select(columns)
  .top(n)

  tableService.queryEntities(process.env.TABLE_NAME, query, null, function(error, result, response) {
    console.log(error);
    if (error) return callback(error, []);

      // each prop in the results comes back with a nested prop of `_`,
      // so this flattens the props and filters out metadata prop also
      const rows = result.entries.map(e => {
        return Object.keys(e)
          .filter(k => k !== '.metadata')
          .reduce((a, b) => {
            const flatProp = { [b]: e[b]._ };
            return Object.assign(a, flatProp);
          }, {});
      });

      rows.sort(byTime);

      return callback(null, rows);
  });
}<|endoftext|>


<commit_before>

function OperationData(){
	self = this;

	self.init = function(){
			$(document).ready(function () {
				$('#copy').click(function () {
					self.copy();
			      });

				$('#import').click(function () {
					self.import();
			      });
			});

			self.readConfig();
	};

	self.readConfig = function(){
		result = "{" + self.generate("Theme",localStorage['Theme']) + "," +
		self.generate("UserTheme",localStorage['UserTheme']) + "," +
		self.generate("ColorValue",localStorage['localStorage']) + "," +
		self.generate("UserFont",localStorage['UserFont']) + "," +
		self.generate("UserCSS",localStorage['UserCSS']) + "}"
		;
		document.getElementById("Config").value = result;
		var btn = document.getElementById('copy');
	    var clipboard = new Clipboard(btn);

	    clipboard.on('success', function(e) {
	        alert("复制成功!");
	        delete clipboard;
	    });

	    clipboard.on('error', function(e) {
	        alert("复制失败! Chrome 版本 内核不支持!");
	        delete clipboard;
	    });
	}

	self.copy = function(){

	};

	self.import = function(){
		result = document.getElementById("Config").value;
		obj = JSON.parse(result);
		localStorage['Theme'] = obj.Theme;
		localStorage['UserTheme'] = obj.UserTheme;
		localStorage['ColorValue'] = obj.ColorValue;
		localStorage['UserFont'] = obj.UserFont;
		localStorage['UserCSS'] = obj.UserCSS;
		//console.log(obj);
		alert("导入成功!");
	};

	self.generate = function(key,value){
		if(value == 'null' || value == undefined){
			value = '';
		}
		result =  "\"";
		result += key;
		result += "\":";
		result += "\"";
		result += value;
		result += "\"";
		return result;
	}

	return self;
};

OperationData().init();
<commit_msg>updateset<commit_after>

function OperationData(){
	self = this;

	self.init = function(){
			$(document).ready(function () {
				$('#copy').click(function () {
					self.copy();
			      });

				$('#import').click(function () {
					self.import();
			      });
			});

			self.readConfig();
	};

	self.readConfig = function(){
		result = "{" + self.generate("Theme",localStorage['Theme']) + "," +
		self.generate("UserTheme",localStorage['UserTheme']) + "," +
		self.generate("ColorValue",localStorage['localStorage']) + "," +
		self.generate("UserFont",localStorage['UserFont']) + "," +
		self.generate("UserCSS",localStorage['UserCSS']) + "," +
		self.generate("enable",localStorage['enable']) + "}"
		;
		document.getElementById("Config").value = result;
		var btn = document.getElementById('copy');
	    var clipboard = new Clipboard(btn);

	    clipboard.on('success', function(e) {
	        alert("复制成功!");
	        delete clipboard;
	    });

	    clipboard.on('error', function(e) {
	        alert("复制失败! Chrome 版本 内核不支持!");
	        delete clipboard;
	    });
	}

	self.copy = function(){

	};

	self.import = function(){
		result = document.getElementById("Config").value;
		obj = JSON.parse(result);
		localStorage['Theme'] = obj.Theme;
		localStorage['UserTheme'] = obj.UserTheme;
		localStorage['ColorValue'] = obj.ColorValue;
		localStorage['UserFont'] = obj.UserFont;
		localStorage['UserCSS'] = obj.UserCSS;
		localStorage['enable'] = obj.enable;
		//console.log(obj);
		alert("导入成功!");
	};

	self.generate = function(key,value){
		if(value == 'null' || value == undefined){
			value = '';
		}
		result =  "\"";
		result += key;
		result += "\":";
		result += "\"";
		result += value;
		result += "\"";
		return result;
	}

	return self;
};

OperationData().init();
<|endoftext|>


<commit_before>'use strict'
const vec3 = require('pex-math/vec3')
const mat4 = require('pex-math/mat4')
const ray = require('pex-geom/ray')
const clamp = require('pex-math/utils').clamp
const raf = require('raf')
const interpolateAngle = require('interpolate-angle')
const lerp = require('pex-math/utils').lerp
const toRadians = require('pex-math/utils').toRadians
const toDegrees = require('pex-math/utils').toDegrees
const latLonToXyz = require('latlon-to-xyz')
const xyzToLatLon = require('xyz-to-latlon')

function Orbiter (opts) {
  // TODO: split into internal state and public state
  const initialState = {
    camera: opts.camera,
    invViewMatrix: mat4.create(),
    dragging: false,
    lat: 0, // Y
    lon: 0, // XZ
    currentLat: 0,
    currentLon: 0,
    easing: 1,
    element: opts.element || window,
    width: 0,
    height: 0,
    clickPosWindow: [0, 0],
    dragPos: [0, 0, 0],
    dragPosWindow: [0, 0],
    distance: 1,
    currentDistance: 1,
    minDistance: 1,
    maxDistance: 1,
    zoomSlowdown: 400,
    zoom: true,
    pan: true,
    drag: true,
    dragSlowdown: 4,
    clickTarget: [0, 0, 0],
    clickPosPlane: [0, 0, 0],
    dragPosPlane: [0, 0, 0],
    clickPosWorld: [0, 0, 0],
    dragPosWorld: [0, 0, 0],
    panPlane: null
  }

  this.set(initialState)
  this.set(opts)
  this.setup()
}

Orbiter.prototype.set = function (opts) {
  if (opts.lat !== undefined) {

  }

  if (opts.camera) {
    const distance = vec3.distance(opts.camera.position, opts.camera.target)
    const latLon = xyzToLatLon(vec3.normalize(vec3.sub(vec3.copy(opts.camera.position), opts.camera.target)))
    this.lat = latLon[0]
    this.lon = latLon[1]
    this.currentLat = this.lat
    this.currentLon = this.lon
    this.distance = distance
    this.currentDistance = this.distance
    this.minDistance = opts.minDistance || distance / 10
    this.maxDistance = opts.maxDistance || distance * 10
  }

  Object.assign(this, opts)
}

Orbiter.prototype.updateWindowSize = function () {
  const width = this.element.clientWidth || this.element.innerWidth
  const height = this.element.clientHeight || this.element.innerHeight
  if (width !== this.width) {
    this.width = width
    this.height = height
    this.radius = Math.min(this.width / 2, this.height / 2)
  }
}

Orbiter.prototype.updateCamera = function () {
  // instad of rotating the object we want to move camera around it
  // state.currRot[3] *= -1

  const position = this.camera.position
  const target = this.camera.target

  this.lat = clamp(this.lat, -89.5, 89.5)
  this.lon = this.lon % (360)

  this.currentLat = toDegrees(
    interpolateAngle(
      (toRadians(this.currentLat) + 2 * Math.PI) % (2 * Math.PI),
      (toRadians(this.lat) + 2 * Math.PI) % (2 * Math.PI),
      this.easing
    )
  )
  this.currentLon = toDegrees(
    interpolateAngle(
      (toRadians(this.currentLon) + 2 * Math.PI) % (2 * Math.PI),
      (toRadians(this.lon) + 2 * Math.PI) % (2 * Math.PI),
      this.easing
    )
  )
  this.currentDistance = lerp(this.currentDistance, this.distance, this.easing)

  // set new camera position according to the current
  // rotation at distance relative to target
  latLonToXyz(this.currentLat, this.currentLon, position)
  vec3.scale(position, this.distance)
  vec3.add(position, target)

  this.camera.set({
    position: position
  })
}

Orbiter.prototype.setup = function () {
  var orbiter = this

  function down (x, y, shift) {
    orbiter.dragging = true
    orbiter.dragPos[0] = x
    orbiter.dragPos[1] = y
    if (shift && orbiter.pan) {
      orbiter.clickPosWindow[0] = x
      orbiter.clickPosWindow[1] = y
      vec3.set(orbiter.clickTarget, orbiter.camera.target)
      const targetInViewSpace = vec3.multMat4(vec3.copy(orbiter.clickTarget), orbiter.camera.viewMatrix)
      orbiter.panPlane = [targetInViewSpace, [0, 0, 1]]
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
    } else {
      orbiter.panPlane = null
    }
  }

  function move (x, y, shift) {
    if (!orbiter.dragging) {
      return
    }
    if (shift && orbiter.panPlane) {
      orbiter.dragPosWindow[0] = x
      orbiter.dragPosWindow[1] = y
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
      mat4.set(orbiter.invViewMatrix, orbiter.camera.viewMatrix)
      mat4.invert(orbiter.invViewMatrix)
      vec3.multMat4(vec3.set(orbiter.clickPosWorld, orbiter.clickPosPlane), orbiter.invViewMatrix)
      vec3.multMat4(vec3.set(orbiter.dragPosWorld, orbiter.dragPosPlane), orbiter.invViewMatrix)
      const diffWorld = vec3.sub(vec3.copy(orbiter.dragPosWorld), orbiter.clickPosWorld)
      const target = vec3.sub(vec3.copy(orbiter.clickTarget), diffWorld)
      orbiter.camera.set({ target: target })
      orbiter.updateCamera()
    } else if (orbiter.drag) {
      const dx = x - orbiter.dragPos[0]
      const dy = y - orbiter.dragPos[1]
      orbiter.dragPos[0] = x
      orbiter.dragPos[1] = y

      orbiter.lat += dy / orbiter.dragSlowdown
      orbiter.lon -= dx / orbiter.dragSlowdown

      // TODO: how to have resolution independed scaling? will this code behave differently with retina/pixelRatio=2?
      orbiter.updateCamera()
    }
  }

  function up () {
    orbiter.dragging = false
    orbiter.panPlane = null
  }

  function scroll (dy) {
    if (!orbiter.zoom) {
      return
    }
    orbiter.distance *= 1 + dy / orbiter.zoomSlowdown
    orbiter.distance = clamp(orbiter.distance, orbiter.minDistance, orbiter.maxDistance)
    orbiter.updateCamera()
  }

  function onMouseDown (e) {
    orbiter.updateWindowSize()
    down(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseMove (e) {
    move(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseUp (e) {
    up()
  }

  function onWheel (e) {
    scroll(e.deltaY)
    e.preventDefault()
  }

  this.element.addEventListener('mousedown', onMouseDown)
  this.element.addEventListener('touchstart', (e) => {
    e.preventDefault()
    onMouseDown(e)
  })
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('touchmove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
  window.addEventListener('touchend', onMouseUp)
  this.element.addEventListener('wheel', onWheel)

  this.updateCamera()

  raf(function tick () {
    orbiter.updateCamera()
    raf(tick)
  })
}

module.exports = function createOrbiter (opts) {
  return new Orbiter(opts)
}
<commit_msg>Remove dead code<commit_after>'use strict'
const vec3 = require('pex-math/vec3')
const mat4 = require('pex-math/mat4')
const ray = require('pex-geom/ray')
const clamp = require('pex-math/utils').clamp
const raf = require('raf')
const interpolateAngle = require('interpolate-angle')
const lerp = require('pex-math/utils').lerp
const toRadians = require('pex-math/utils').toRadians
const toDegrees = require('pex-math/utils').toDegrees
const latLonToXyz = require('latlon-to-xyz')
const xyzToLatLon = require('xyz-to-latlon')

function Orbiter (opts) {
  // TODO: split into internal state and public state
  const initialState = {
    camera: opts.camera,
    invViewMatrix: mat4.create(),
    dragging: false,
    lat: 0, // Y
    lon: 0, // XZ
    currentLat: 0,
    currentLon: 0,
    easing: 1,
    element: opts.element || window,
    width: 0,
    height: 0,
    clickPosWindow: [0, 0],
    dragPos: [0, 0, 0],
    dragPosWindow: [0, 0],
    distance: 1,
    currentDistance: 1,
    minDistance: 1,
    maxDistance: 1,
    zoomSlowdown: 400,
    zoom: true,
    pan: true,
    drag: true,
    dragSlowdown: 4,
    clickTarget: [0, 0, 0],
    clickPosPlane: [0, 0, 0],
    dragPosPlane: [0, 0, 0],
    clickPosWorld: [0, 0, 0],
    dragPosWorld: [0, 0, 0],
    panPlane: null
  }

  this.set(initialState)
  this.set(opts)
  this.setup()
}

Orbiter.prototype.set = function (opts) {
  if (opts.camera) {
    const distance = vec3.distance(opts.camera.position, opts.camera.target)
    const latLon = xyzToLatLon(vec3.normalize(vec3.sub(vec3.copy(opts.camera.position), opts.camera.target)))
    this.lat = latLon[0]
    this.lon = latLon[1]
    this.currentLat = this.lat
    this.currentLon = this.lon
    this.distance = distance
    this.currentDistance = this.distance
    this.minDistance = opts.minDistance || distance / 10
    this.maxDistance = opts.maxDistance || distance * 10
  }

  Object.assign(this, opts)
}

Orbiter.prototype.updateWindowSize = function () {
  const width = this.element.clientWidth || this.element.innerWidth
  const height = this.element.clientHeight || this.element.innerHeight
  if (width !== this.width) {
    this.width = width
    this.height = height
    this.radius = Math.min(this.width / 2, this.height / 2)
  }
}

Orbiter.prototype.updateCamera = function () {
  // instad of rotating the object we want to move camera around it
  // state.currRot[3] *= -1

  const position = this.camera.position
  const target = this.camera.target

  this.lat = clamp(this.lat, -89.5, 89.5)
  this.lon = this.lon % (360)

  this.currentLat = toDegrees(
    interpolateAngle(
      (toRadians(this.currentLat) + 2 * Math.PI) % (2 * Math.PI),
      (toRadians(this.lat) + 2 * Math.PI) % (2 * Math.PI),
      this.easing
    )
  )
  this.currentLon = toDegrees(
    interpolateAngle(
      (toRadians(this.currentLon) + 2 * Math.PI) % (2 * Math.PI),
      (toRadians(this.lon) + 2 * Math.PI) % (2 * Math.PI),
      this.easing
    )
  )
  this.currentDistance = lerp(this.currentDistance, this.distance, this.easing)

  // set new camera position according to the current
  // rotation at distance relative to target
  latLonToXyz(this.currentLat, this.currentLon, position)
  vec3.scale(position, this.distance)
  vec3.add(position, target)

  this.camera.set({
    position: position
  })
}

Orbiter.prototype.setup = function () {
  var orbiter = this

  function down (x, y, shift) {
    orbiter.dragging = true
    orbiter.dragPos[0] = x
    orbiter.dragPos[1] = y
    if (shift && orbiter.pan) {
      orbiter.clickPosWindow[0] = x
      orbiter.clickPosWindow[1] = y
      vec3.set(orbiter.clickTarget, orbiter.camera.target)
      const targetInViewSpace = vec3.multMat4(vec3.copy(orbiter.clickTarget), orbiter.camera.viewMatrix)
      orbiter.panPlane = [targetInViewSpace, [0, 0, 1]]
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
    } else {
      orbiter.panPlane = null
    }
  }

  function move (x, y, shift) {
    if (!orbiter.dragging) {
      return
    }
    if (shift && orbiter.panPlane) {
      orbiter.dragPosWindow[0] = x
      orbiter.dragPosWindow[1] = y
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.clickPosWindow[0], orbiter.clickPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.clickPosPlane
      )
      ray.hitTestPlane(
        orbiter.camera.getViewRay(orbiter.dragPosWindow[0], orbiter.dragPosWindow[1], orbiter.width, orbiter.height),
        orbiter.panPlane[0],
        orbiter.panPlane[1],
        orbiter.dragPosPlane
      )
      mat4.set(orbiter.invViewMatrix, orbiter.camera.viewMatrix)
      mat4.invert(orbiter.invViewMatrix)
      vec3.multMat4(vec3.set(orbiter.clickPosWorld, orbiter.clickPosPlane), orbiter.invViewMatrix)
      vec3.multMat4(vec3.set(orbiter.dragPosWorld, orbiter.dragPosPlane), orbiter.invViewMatrix)
      const diffWorld = vec3.sub(vec3.copy(orbiter.dragPosWorld), orbiter.clickPosWorld)
      const target = vec3.sub(vec3.copy(orbiter.clickTarget), diffWorld)
      orbiter.camera.set({ target: target })
      orbiter.updateCamera()
    } else if (orbiter.drag) {
      const dx = x - orbiter.dragPos[0]
      const dy = y - orbiter.dragPos[1]
      orbiter.dragPos[0] = x
      orbiter.dragPos[1] = y

      orbiter.lat += dy / orbiter.dragSlowdown
      orbiter.lon -= dx / orbiter.dragSlowdown

      // TODO: how to have resolution independed scaling? will this code behave differently with retina/pixelRatio=2?
      orbiter.updateCamera()
    }
  }

  function up () {
    orbiter.dragging = false
    orbiter.panPlane = null
  }

  function scroll (dy) {
    if (!orbiter.zoom) {
      return
    }
    orbiter.distance *= 1 + dy / orbiter.zoomSlowdown
    orbiter.distance = clamp(orbiter.distance, orbiter.minDistance, orbiter.maxDistance)
    orbiter.updateCamera()
  }

  function onMouseDown (e) {
    orbiter.updateWindowSize()
    down(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseMove (e) {
    move(
      e.offsetX || e.clientX || (e.touches ? e.touches[0].clientX : 0),
      e.offsetY || e.clientY || (e.touches ? e.touches[0].clientY : 0),
      e.shiftKey || (e.touches && e.touches.length === 2)
    )
  }

  function onMouseUp (e) {
    up()
  }

  function onWheel (e) {
    scroll(e.deltaY)
    e.preventDefault()
  }

  this.element.addEventListener('mousedown', onMouseDown)
  this.element.addEventListener('touchstart', (e) => {
    e.preventDefault()
    onMouseDown(e)
  })
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('touchmove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
  window.addEventListener('touchend', onMouseUp)
  this.element.addEventListener('wheel', onWheel)

  this.updateCamera()

  raf(function tick () {
    orbiter.updateCamera()
    raf(tick)
  })
}

module.exports = function createOrbiter (opts) {
  return new Orbiter(opts)
}
<|endoftext|>


<commit_before>/**
 * Manages links
 * @param collectionId
 * @param data
 * @param field - JSON data key
 * @param idField - HTML id for the template
 */

function editExtLink (collectionId, data, field, idField) {
  var list = data[field];
  var dataTemplate = {list: list, idField: idField};
  var html = templates.editorLinks(dataTemplate);
  $('#'+ idField).replaceWith(html);

  // Load
  $(data[field]).each(function(index){

    $('#' + idField +'-edit_'+index).click(function() {
      var editedSectionValue = {
        "title": data[field][index].uri,
        "markdown": data[field][index].title
      };

      var saveContent = function(updatedContent) {
        data[field][index].title = updatedContent;                         //markdown
        data[field][index].uri = $('#' + idField +'-uri_' + index).val();
        saveLink (collectionId, data.uri, data, field, idField);
        refreshPreview(data.uri);
      };

      loadMarkdownEditor(editedSectionValue, saveContent, data);
    });

    // Delete
    $('#' + idField + '-delete_'+index).click(function() {
      swal ({
        title: "Warning",
        text: "Are you sure you want to delete?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Delete",
        cancelButtonText: "Cancel",
        closeOnConfirm: false
      }, function(result) {
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position + 300;
          $(this).parent().remove();
          data[field].splice(index, 1);
          saveLink(collectionId, data.uri, data, field, idField);
          refreshPreview(data.uri);
          swal({
            title: "Deleted",
            text: "This link has been deleted",
            type: "success",
            timer: 2000
          });
        }
      });
    });
  });

  //Add
  $('#add-' + idField).click(function () {
    var position = $(".workspace-edit").scrollTop();
    Florence.globalVars.pagePos = position + 300;

    if (!data[field]) {
      data[field] = [];
    }
    var modal = templates.linkExternalModal;
    var uri, title;
    $('.workspace-menu').append(modal);
    $('#uri-input').change(function () {
      uri = $('#uri-input').val();
    });
    $('#uri-title').change(function () {
      title = $('#uri-title').val();
    });
    $('.btn-uri-get').off().click(function () {
      if (!title) {
        sweetAlert('You need to enter a title to continue');
      }
      else {
        data[field].push({uri: uri, title: title});
        saveLink(collectionId, data.uri, data, field, idField);
        $('.modal').remove();
      }
    });
    $('.btn-uri-cancel').off().click(function () {
      //createWorkspace(data.uri, collectionId, 'edit');
      $('.modal').remove();
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable({
      stop: function(){
        $('#' + idField + ' .edit-section__sortable-item--counter').each(function(index) {
          $(this).empty().append(index + 1);
        });
      }
    });
  }
  sortable();
}

function saveLink (collectionId, path, data, field, idField) {
  putContent(collectionId, path, JSON.stringify(data),
      success = function (response) {
        Florence.Editor.isDirty = false;
        editExtLink (collectionId, data, field, idField);
        refreshPreview(data.uri);
      },
      error = function (response) {
        if (response.status === 400) {
          sweetAlert("Cannot edit this page", "It is already part of another collection.");
        }
        else {
          handleApiError(response);
        }
      }
  );
}<commit_msg>Check the link does not contain spaces.<commit_after>/**
 * Manages links
 * @param collectionId
 * @param data
 * @param field - JSON data key
 * @param idField - HTML id for the template
 */

function editExtLink (collectionId, data, field, idField) {
  var list = data[field];
  var dataTemplate = {list: list, idField: idField};
  var html = templates.editorLinks(dataTemplate);
  $('#'+ idField).replaceWith(html);

  // Load
  $(data[field]).each(function(index){

    $('#' + idField +'-edit_'+index).click(function() {
      var editedSectionValue = {
        "title": data[field][index].uri,
        "markdown": data[field][index].title
      };

      var saveContent = function(updatedContent) {
        data[field][index].title = updatedContent;                         //markdown
        data[field][index].uri = $('#' + idField +'-uri_' + index).val();
        saveLink (collectionId, data.uri, data, field, idField);
        refreshPreview(data.uri);
      };

      loadMarkdownEditor(editedSectionValue, saveContent, data);
    });

    // Delete
    $('#' + idField + '-delete_'+index).click(function() {
      swal ({
        title: "Warning",
        text: "Are you sure you want to delete?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Delete",
        cancelButtonText: "Cancel",
        closeOnConfirm: false
      }, function(result) {
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position + 300;
          $(this).parent().remove();
          data[field].splice(index, 1);
          saveLink(collectionId, data.uri, data, field, idField);
          refreshPreview(data.uri);
          swal({
            title: "Deleted",
            text: "This link has been deleted",
            type: "success",
            timer: 2000
          });
        }
      });
    });
  });

  //Add
  $('#add-' + idField).click(function () {
    var position = $(".workspace-edit").scrollTop();
    Florence.globalVars.pagePos = position + 300;

    if (!data[field]) {
      data[field] = [];
    }
    var modal = templates.linkExternalModal;
    var uri, title;
    $('.workspace-menu').append(modal);
    $('#uri-input').change(function () {
      uri = $('#uri-input').val();
    });
    $('#uri-title').change(function () {
      title = $('#uri-title').val();
    });
    $('.btn-uri-get').off().click(function () {
      if (!title) {
        sweetAlert('You need to enter a title to continue');
      } else if (uri.match(/\s/g)){
        sweetAlert('Your link cannot contain spaces');
      } else {
        data[field].push({uri: uri, title: title});
        saveLink(collectionId, data.uri, data, field, idField);
        $('.modal').remove();
      }
    });
    $('.btn-uri-cancel').off().click(function () {
      //createWorkspace(data.uri, collectionId, 'edit');
      $('.modal').remove();
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable({
      stop: function(){
        $('#' + idField + ' .edit-section__sortable-item--counter').each(function(index) {
          $(this).empty().append(index + 1);
        });
      }
    });
  }
  sortable();
}

function saveLink (collectionId, path, data, field, idField) {
  putContent(collectionId, path, JSON.stringify(data),
      success = function (response) {
        Florence.Editor.isDirty = false;
        editExtLink (collectionId, data, field, idField);
        refreshPreview(data.uri);
      },
      error = function (response) {
        if (response.status === 400) {
          sweetAlert("Cannot edit this page", "It is already part of another collection.");
        }
        else {
          handleApiError(response);
        }
      }
  );
}<|endoftext|>


<commit_before>define([ "jquery", "rajo.pubsub", "jquery.blockUI" ], function($, PubSub) {
	"use strict";

	PubSub.subscribe("mailslurper.block", function(msg) {
		$.blockUI({ message: "<h3>" + msg + "</h3>" });
	});

	PubSub.subscribe("mailslurper.unblock", function(fn) {
		$.unblockUI();
		if (fn !== undefined && typeof fn === Function) {
			fn();
		}
	});

	return {
		log: function(msg) {
			if (window.hasOwnProperty("console")) {
				console.log(msg);
			}
		}
	}
});
<commit_msg>Removed unused MailSlurper.js refs #11<commit_after><|endoftext|>


<commit_before>
function Gallery(id) {
		var gallery = this;

		//string with id of the gallery node
		this.galleryId = id;
		//array of jquery IMG nodes
		this.imgList = new Array();
		//jquery reference to main container
		this.$holder = null;
		//jquery reference to the container encapsulating images
		this.wrapper = null;
		//index in the img array for the current image
		this.currentImgIdx = 0;
		//# of images loaded
		this.imagesLoaded = 0;
		//navigation elements
		this.arrowLeft = null;
		this.arrowRight = null;

		//opacity value for inactive arrows
		this.inactiveOpacity = 0.3;

		/*** Gallery functions ***/

		this.scrollLeft = function(event) {
			if(gallery.currentImgIdx >= gallery.imgList.length-1)
				return;

			var scrollWidth = gallery.imgList[gallery.currentImgIdx].parent().outerWidth(true)/2
							+ gallery.imgList[gallery.currentImgIdx+1].parent().outerWidth(true)/2;

			//remove onclick handler for the image that is being scrolled away
			gallery.imgList[gallery.currentImgIdx].off('click')
				   .css("cursor", "default");

			gallery.wrapper.animate({
				left: "-=" + scrollWidth + "px"
			});

			gallery.currentImgIdx += 1;

			//add onclick handler for new centered image
			gallery.imgList[gallery.currentImgIdx].on("click", function() {
					gallery.showLightbox(gallery.imgList[gallery.currentImgIdx]);
				}).css("cursor", "pointer");

		};

		this.scrollRight = function(event) {
			if(gallery.currentImgIdx <= 0) return;

			var scrollWidth = gallery.imgList[gallery.currentImgIdx].parent().outerWidth(true)/2
			+ gallery.imgList[gallery.currentImgIdx-1].parent().outerWidth(true)/2;

			//remove onclick handler for the image that is being scrolled away
			gallery.imgList[gallery.currentImgIdx].off('click');

			gallery.wrapper.animate({
				left: '+=' + scrollWidth + "px"
			});

			gallery.currentImgIdx -= 1;
			//add onclick handler for new centered image
			gallery.imgList[gallery.currentImgIdx].on("click", function() {
					gallery.showLightbox(gallery.imgList[gallery.currentImgIdx]);
				}).css("cursor", "pointer");

		};

		this.showLightbox = function(img) {
			console.log("Lightboxing " + img.attr('src'));

			$lbImg = $(document.createElement("img")).attr('src', img.attr('src'));

            $lightboxWrapper = $("

");
			$lbImg.on("load", function() {
                $lightboxClose = $("

");

                $lightboxWrapper.append($lightboxClose);
                $lightboxWrapper.append($lbImg);

                $lightboxClose.offset({top: 5, left: this.width - $lightboxClose.width() -20});

                $lightboxWrapper.lightbox_me({
                    centered: true,
                    destroyOnClose: true
                });
			});
		};

		this.arrowHoverIn = function(event) {
			$(this).fadeTo('normal', 1);
		};

		this.arrowHoverOut = function(event) {
			$(this).fadeTo('normal', gallery.inactiveOpacity);
		};

		/*** Gallery functions end ***/

		//initialize holder element
		this.$holder = $(this.galleryId);
		this.$holder.css("overflow","hidden")
					.css("position", "relative");

		//store images in imgList
		_list = $(this.galleryId + ' > img' );
		_list.each(function() {
			gallery.imgList.push($(this));
		});
		//remove images from original DOM
		_list.detach();

		//set up navigation buttons
		this.$arrowLeft = $("
")
			.addClass("galleryArrowLeft");
		this.$holder.append(this.$arrowLeft);

		this.$arrowLeft.css({
			top: this.$holder.height()/2 - this.$arrowLeft.height()/2,
			left: 5,
			opacity: this.inactiveOpacity
		});

		this.$arrowRight = $("
")
		.addClass("galleryArrowRight");
		this.$holder.append(this.$arrowRight);

		this.$arrowRight.css({
			top: this.$holder.height()/2 - this.$arrowRight.outerHeight(true)/2,
			left: this.$holder.width()-this.$arrowRight.outerWidth(true),
			opacity: this.inactiveOpacity
		});

		this.$arrowLeft.hover(this.arrowHoverIn, this.arrowHoverOut);
		this.$arrowRight.hover(this.arrowHoverIn, this.arrowHoverOut);

		//add wrapper element
		this.wrapper = $(document.createElement("div"));
		this.wrapper.css({
			position: "relative",
			padding: 0,
			margin: 0
		});
		this.$holder.append(this.wrapper);

		this.$holder.on("load", function() {
			console.log("Holder loaded!");
		});

		if(this.$holder[0].complete) {
			console.log("Holder completed!");
			this.$holder.load();
		}

		$.each(this.imgList, function(i, img){
			//construct placeholder for every image
			d = document.createElement("div");
			$(d).addClass("imgHolder")
				.height(gallery.$holder.innerHeight());
			gallery.wrapper.append(d);

			$(d).append(img);
			img.height(gallery.$holder.innerHeight());

			img.on("load", function() {
				//as soon as the first img is loaded, we will set up leading space:
				if(i==0) {
					_offset = gallery.$holder.width() /2 -
					$(this).parent().outerWidth(true)/2;
					gallery.wrapper.css({left: _offset + "px"});
					//set onclick handler for first image
					img.on("click", function(){gallery.showLightbox(img);});
					img.css("cursor", "pointer");
				};
			});

		});

		//set up click handlers for scroll buttons, but only after all images in wrapper element load
		//(so we know their widths for scrolling)

		//onLoad doesn't work for wrapper, only for $(window)
		//$(window).on("load", function (){
			gallery.$arrowLeft.click(gallery.scrollRight);
			gallery.$arrowRight.click(gallery.scrollLeft);
		//});
};

<commit_msg>Fixed clearing elements after lightboxing<commit_after>
function Gallery(id) {
		var gallery = this;

		//string with id of the gallery node
		this.galleryId = id;
		//array of jquery IMG nodes
		this.imgList = new Array();
		//jquery reference to main container
		this.$holder = null;
		//jquery reference to the container encapsulating images
		this.wrapper = null;
		//index in the img array for the current image
		this.currentImgIdx = 0;
		//# of images loaded
		this.imagesLoaded = 0;
		//navigation elements
		this.arrowLeft = null;
		this.arrowRight = null;

		//opacity value for inactive arrows
		this.inactiveOpacity = 0.3;

		/*** Gallery functions ***/

		this.scrollLeft = function(event) {
			if(gallery.currentImgIdx >= gallery.imgList.length-1)
				return;

			var scrollWidth = gallery.imgList[gallery.currentImgIdx].parent().outerWidth(true)/2
							+ gallery.imgList[gallery.currentImgIdx+1].parent().outerWidth(true)/2;

			//remove onclick handler for the image that is being scrolled away
			gallery.imgList[gallery.currentImgIdx].off('click')
				   .css("cursor", "default");

			gallery.wrapper.animate({
				left: "-=" + scrollWidth + "px"
			});

			gallery.currentImgIdx += 1;

			//add onclick handler for new centered image
			gallery.imgList[gallery.currentImgIdx].on("click", function() {
					gallery.showLightbox(gallery.imgList[gallery.currentImgIdx]);
				}).css("cursor", "pointer");

		};

		this.scrollRight = function(event) {
			if(gallery.currentImgIdx <= 0) return;

			var scrollWidth = gallery.imgList[gallery.currentImgIdx].parent().outerWidth(true)/2
			+ gallery.imgList[gallery.currentImgIdx-1].parent().outerWidth(true)/2;

			//remove onclick handler for the image that is being scrolled away
			gallery.imgList[gallery.currentImgIdx].off('click');

			gallery.wrapper.animate({
				left: '+=' + scrollWidth + "px"
			});

			gallery.currentImgIdx -= 1;
			//add onclick handler for new centered image
			gallery.imgList[gallery.currentImgIdx].on("click", function() {
					gallery.showLightbox(gallery.imgList[gallery.currentImgIdx]);
				}).css("cursor", "pointer");

		};

		this.showLightbox = function(img) {
			console.log("Lightboxing " + img.attr('src'));

			$lbImg = $(document.createElement("img")).attr('src', img.attr('src'));

            $lightboxWrapper = $("

");
			$lbImg.on("load", function() {
                $lightboxClose = $("

");

                $lightboxWrapper.append($lightboxClose);
                $lightboxWrapper.append($lbImg);

                $lightboxClose.offset({top: 5, left: this.width - $lightboxClose.width() -20});

                $lightboxWrapper.lightbox_me({
                    centered: true,
                    destroyOnClose: true
                });
			});
		};

		this.arrowHoverIn = function(event) {
			$(this).fadeTo('normal', 1);
		};

		this.arrowHoverOut = function(event) {
			$(this).fadeTo('normal', gallery.inactiveOpacity);
		};

		/*** Gallery functions end ***/

		//initialize holder element
		this.$holder = $(this.galleryId);
		this.$holder.css("overflow","hidden")
					.css("position", "relative");

		//store images in imgList
		_list = $(this.galleryId + ' > img' );
		_list.each(function() {
			gallery.imgList.push($(this));
		});
		//remove images from original DOM
		_list.detach();

		//set up navigation buttons
		this.$arrowLeft = $("
")
			.addClass("galleryArrowLeft");
		this.$holder.append(this.$arrowLeft);

		this.$arrowLeft.css({
			top: this.$holder.height()/2 - this.$arrowLeft.height()/2,
			left: 5,
			opacity: this.inactiveOpacity
		});

		this.$arrowRight = $("
")
		.addClass("galleryArrowRight");
		this.$holder.append(this.$arrowRight);

		this.$arrowRight.css({
			top: this.$holder.height()/2 - this.$arrowRight.outerHeight(true)/2,
			left: this.$holder.width()-this.$arrowRight.outerWidth(true),
			opacity: this.inactiveOpacity
		});

		this.$arrowLeft.hover(this.arrowHoverIn, this.arrowHoverOut);
		this.$arrowRight.hover(this.arrowHoverIn, this.arrowHoverOut);

		//add wrapper element
		this.wrapper = $(document.createElement("div"));
		this.wrapper.css({
			position: "relative",
			padding: 0,
			margin: 0
		});
		this.$holder.append(this.wrapper);

		this.$holder.on("load", function() {
			console.log("Holder loaded!");
		});

		if(this.$holder[0].complete) {
			console.log("Holder completed!");
			this.$holder.load();
		}

		$.each(this.imgList, function(i, img){
			//construct placeholder for every image
			d = document.createElement("div");
			$(d).addClass("imgHolder")
				.height(gallery.$holder.innerHeight());
			gallery.wrapper.append(d);

			$(d).append(img);
			img.height(gallery.$holder.innerHeight());

			img.on("load", function() {
				//as soon as the first img is loaded, we will set up leading space:
				if(i==0) {
					_offset = gallery.$holder.width() /2 -
					$(this).parent().outerWidth(true)/2;
					gallery.wrapper.css({left: _offset + "px"});
					//set onclick handler for first image
					img.on("click", function(){gallery.showLightbox(img);});
					img.css("cursor", "pointer");
				};
			});

		});

		//set up click handlers for scroll buttons, but only after all images in wrapper element load
		//(so we know their widths for scrolling)

		//onLoad doesn't work for wrapper, only for $(window)
		//$(window).on("load", function (){
			gallery.$arrowLeft.click(gallery.scrollRight);
			gallery.$arrowRight.click(gallery.scrollLeft);
		//});
};

<|endoftext|>


<commit_before>        var pageSize = DEFAULT_PAGE_SIZE;
        var currPageNumber = 0;
        var sortDirection = false;
        var orderBy = DEFAULT_SORT_FIELD;

        $(document).ready(function() {
            $('#startDate, #endDate, #create_tender_enddate').datepicker({
                format: 'yyyy/mm/dd',
                startDate: '-5y'
            });

            initializeDateFilter();

            $("#category_filter").select2({
                placeholder: "All categories"
            });

            $("#item_dropdown").select2({
                placeholder: "All items"
            });

            $("#location_filter").select2({
                placeholder: "All locations"
            });

            $("#status_filter").select2({
                placeholder: "All active statuses"
            });

            $("#location_filter, #item_dropdown, #status_filter, #price_from, #price_to, #date_from, #date_to").change(function() {
                enableFilterButtons();
            });

            $("#pagination_itemsnum").on('change', function() {
                pageSize = this.value;
                currPageNumber = 0;
                showPage(currPageNumber);
            });

            $("#tender_title").click(function(){
                sortTenders("title","tender_title");
            });

            $("#tender_author").click(function(){
                sortTenders("author.firstName","tender_author");
            });

            $("#tender_suitable_price").click(function(){
                sortTenders("suitablePrice","tender_suitable_price");
            });

            $("#tender_status").click(function(){
                sortTenders("status.name","tender_status");
            });

            $("#tender_proposals").click(function(){
                sortTenders("proposals.size","tender_proposals");
            });

            $("#category_filter").change(function() {
                enableFilterButtons();
                $("#item_dropdown").select2('val', 'All');
                var str='';
                var categories=new Array();
                categories=$('#category_filter').val();
                if (categories!=null){
                    str += "categories="+categories;
                }
                $.ajax({
                    url: "/tenders/items",
                    type: "GET",
                    data:  str,
                    dataType:'json',

                    success: function(data) {
                        var html = '';
                        var len = data.length;
                        for (var i = 0; i < len; i++) {
                            html += '<option value="' + data[i].id + '">'
                                + data[i].name + '</option>';
                        }

                        $('#item_dropdown').html(html);
                    },
                    error:function(){
                        alert("ERROR");
                    }
                });
            });

            $.getJSON('/tenders/statuses', {
                  ajax : 'true'
                }, function(data){
                  var html;
                  var len = data.length;
                  for (var i = 0; i < len; i++) {
                      html += '<option value="' + data[i].id + '">'
                               + data[i].name + '</option>';
                  }
                  $('#status_filter').html(html);
            });

            $.getJSON('/tenders/locations', {
                ajax : 'true'
            }, function(loc){
                var html = ' ';
                var len = loc.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + loc[i].id + '">'
                            +loc[i].name + '</option>';
                }

                $('#location_filter').html(html);
            });

            $.getJSON('/tenders/categories', function(data){
                var html = ' ';
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + data[i].id + '">'
                            + data[i].name + '</option>';
                }

                $('#category_filter').html(html);
            });

            populateItemDropdown();
            showTenders();

            $('#search_input').keydown(function(event) {
                if (event.keyCode == 13) {
                    //search query

                    return false;
                }
            });
        });

        function populateItemDropdown() {
            $.getJSON('/tenders/items', function (data) {
                var html = '';
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + data[i].id + '">'
                            + data[i].name + '</option>';
                }

                $('#item_dropdown').html(html);
            });
        }

        function showTenders() {
            showPagination("");
            var queryParams = "pageSize=" + pageSize + "&pageNumber=" + currPageNumber + "&sortDirection=" +
                ((sortDirection)?"desc":"asc") + "&orderBy=" + orderBy;

            $.ajax({
                url: TENDERS_URL,
                type: "GET",
                data:  queryParams,
                dataType:'json',

                success: function(data) {
                    var html = '';
                    var dataSize = data.length;

                    if(dataSize > 0) {
                        for (var i = 0; i < dataSize; i++) {
                            html += '
' + data[i].title + '	' +
                                '' + data[i].authorName + '	' +
                                '' + data[i].categories + '	';
                                if (data[i].locations.toString().split(',').length>2){
                                    html += '' + data[i].locations.toString().split(',')[0] +','+data[i].locations.toString().split(',')[1] + '...'+'	';
                                }else{
                                    html += '' + data[i].locations + '	';
                                }

                            html += '' + data[i].suitablePrice + '	' +
                                '' + data[i].status + '	' +
                                '' + data[i].proposals + '	' +
                                '' +
                                '
' +
                                '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Action</button>' +
                                '
'+
                                '
View
';
                            if (data[i].roles.toString().search('CUSTOMER')!=-1){
                                if (data[i].userId.toString()==data[i].authorId.toString()){
                                html += '
Close
';
                            }
                            }
                            if (data[i].roles.toString().search('SELLER')!=-1){
                                html += '
Create proposal
';
                            }
                            html +='
' +
                                '
' +
                                '
';
                        }

                        $('#user_message').html('');
                        $('#tender_items').show();
                        $('#tenders').html(html);
                    } else {
                        $('#user_message').html('
Your filter parameters did not match any tender
');
                        $('#tender_items').hide();
                    }
                },
                error:function(){
                    alert("ERROR");
                }
            });
        }

        function clearFilters() {
            disableFilterButtons();
            $("#price_from").val("");
            $("#price_to").val("");
            $("#date_from").val("");
            $("#date_to").val("");
            $("#location_filter").select2('val', 'All');
            $("#category_filter").select2('val', 'All');
            $("#item_dropdown").select2('val', 'All');
            $("#status_filter").select2('val', 'All');
            initializeDateFilter();

            showTenders();
        }

        function enableFilterButtons() {
            $("#filter_button").removeAttr("disabled");
            $("#clear_button").removeAttr("disabled");
        }

        function disableFilterButtons() {
            $("#filter_button").attr("disabled", "disabled");
            $("#clear_button").attr("disabled", "disabled");
        }

        function applyFilters() {
            disableFilterButtons();
            var str='';
            if($("#price_from").val()!=""){
                str+="minPrice="+$("#price_from").val();
            }
            if($("#price_to").val()!=""){
                str += (str.length==0)?"maxPrice="+$("#price_to").val():"&maxPrice="+$("#price_to").val();
            }
            var items=new Array();
            items=$('#item_dropdown').val();
            if (items!=null){
                str += (str.length==0)?"items="+items:"&items="+items;
            }

            var categories = new Array();
            categories = $('#category_filter').val();

            if (categories != null){
                $.ajax({
                    dataType: "json",
                    url: '/tenders/categories',
                    async: false,
                    success: function(data){
                        for(var z=0;z<categories.length;z++) {
                            var subCats = getSubCategories(categories[z],data,categories);
                            categories = categories.concat(subCats);
                        }
                    }
                });
                str += (str.length == 0)?"categories="+categories:"&categories="+categories;
            }

            var locations=new Array();
            locations=$('#location_filter').val();
            if (locations!=null){
                str += (str.length==0)?"locations="+locations:"&locations="+locations;
            }
            var statuses=new Array();
            statuses=$('#status_filter').val();
            if (statuses!=null){
                str += (str.length==0)?"statuses="+statuses:"&statuses="+statuses;
            }
            if($("#date_from").val()!=""){
                str += (str.length==0)?"minDate="+$("#date_from").val():"&minDate="+$("#date_from").val();
            }
            if($("#date_to").val()!=""){
                str += (str.length==0)?"maxDate="+$("#date_to").val():"&maxDate="+$("#date_to").val();
            }

            showPagination(str);
            str += (str.length==0)?"pageSize="+pageSize:"&pageSize="+pageSize;
            str += "&pageNumber="+currPageNumber + "&sortDirection=" + ((sortDirection)?"desc":"asc") + "&orderBy=" + orderBy;

            $.ajax({
                url: TENDERS_URL,
                type: "GET",
                data:  str,
                dataType:'json',

                success: function(data) {
                    var html = '';
                    var dataSize = data.length;

                    if(dataSize > 0) {
                        for (var i = 0; i < dataSize; i++) {
                            html += '
' + data[i].title + '	' +
                                '' + data[i].authorName + '	' +
                                '' + data[i].categories + '	';
                            if (data[i].locations.toString().split(',').length>2){
                                html += '' + data[i].locations.toString().split(',')[0] +','+data[i].locations.toString().split(',')[1] + '...'+'	';
                            }else{
                                html += '' + data[i].locations + '	';
                            }

                            html += '' + data[i].suitablePrice + '	' +
                                '' + data[i].status + '	' +
                                '' + data[i].proposals + '	' +
                                '' +
                                '
' +
                                '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Action</button>' +
                                '
'+
                                '
View
';
                            if (data[i].roles.toString().search('CUSTOMER')!=-1){
                                html += '
Close
';
                            }
                            if (data[i].roles.toString().search('SELLER')!=-1){
                                html += '
Create proposal
';
                            }
                            html +='
' +
                                '
' +
                                '
';
                        }

                        $('#user_message').html('');
                        $('#tender_items').show();
                        $('#tenders').html(html);
                    } else {
                        $('#user_message').html('
Your filter parameters did not match any tender
');
                        $('#tender_items').hide();
                    }
                },
                error:function(){
                    alert("ERROR");
                }
            });

            $("#clear_button").removeAttr("disabled");
        }

        function closeTender() {
            var str = '';
            str += "statusName=" + CLOSE_TENDER_STATUS_NAME;
            $.ajax({
                url: TENDERS_URL + "/" + $('#close_tender_id').val() + "?"  + str,
                type: "PUT",

                success: function(data){
                    closeModalWindow('close_tender_mod_wind');
                    showTenders()},
                error: function(){
                    alert("Something wrong")
                }
            })
        }

        function writeCloseTenderId(id) {
            document.getElementById('close_tender_id').value = id;
        }

        function closeModalWindow(id) {
            $('#' + id).modal('hide');
        }

        function initializeDateFilter() {
            var currentDate = getCurrentDate();
            var nextMonthDate = getNextMonthDate();

            $('#startDate').data({date: currentDate});
            $('#startDate').datepicker('update');
            $('#startDate').datepicker().children('input').val(currentDate);

            $('#endDate').data({date: nextMonthDate});
            $('#endDate').datepicker('update');
            $('#endDate').datepicker().children('input').val(nextMonthDate);
        }

        function getSubCategories(id,data,categories) {
            var dataSize = data.length;
            var subCats = new Array();

            for(var z=0;z<dataSize;z++) {
                if(id == data[z].parentId)
                {
                    if($.inArray(data[z].id, categories) != 0) {
                        subCats.push(data[z].id);
                    }
                }
            }

            return subCats;
        }

        function getCurrentDate() {
            var today = new Date();
            var day = today.getDate();
            var month = today.getMonth()+1;
            var year = today.getFullYear();

            if(day < 10) day = '0' + day;
            if(month < 10) month = '0' + month;

            return year + '/' + month + '/' + day;
        }

        function getNextMonthDate() {
            var today = new Date();
            var day = today.getDate();
            var month = today.getMonth()+2;
            var year = today.getFullYear();

            if(day < 10) day = '0' + day;
            if(month < 10) month = '0' + month;

            return year + '/' + month + '/' + day;
        }

        function goToRegistrationPage() {
            window.location.href = REGISTRATION_PAGE_URL;
        }

        function goToMyDealsPage() {
            window.location.href = MYDEALS_PAGE_URL;
        }

        function showPagination(queryParams) {
            $.ajax({
                url: TENDERS_NUMBER,
                async: false,
                type: "GET",
                data:  queryParams,
                dataType:'json',

                success: function(data) {
                    var dataSize = data.tendersNumber;
                    var pageNumber = Math.ceil(dataSize / pageSize);

                    if(dataSize > 0 && pageSize < dataSize) {
                         var html = '';
                         html += '
«
';
                         for(var z=1;z<=pageNumber;z++) {
                              html += '
'+z+'
';
                         }
                         html += '
»
';

                         $('.page_pagination').html(html).show();
                         $('#pagination').show();

                        if(currPageNumber != 0) {
                            document.getElementById('prev_page').setAttribute("onclick", "showPage("+(currPageNumber-1)+");");
                        }

                        if(currPageNumber != pageNumber-1) {
                            document.getElementById('next_page').setAttribute("onclick", "showPage("+(currPageNumber+1)+");");
                        }
                    } else {
                         $('.page_pagination').hide();
                    }
                },
                error:function(){
                    $('#pagination').hide();
                }
            });
        }

        function showPage(pageNumber) {
            currPageNumber = pageNumber;
            applyFilters();
        }

        function sortTenders(orderByField, elementId) {
            sortDirection = (orderBy == orderByField) ? !sortDirection : false;
            orderBy = orderByField;

            $('#tender_items .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
            if(sortDirection == false) {
                $('#'+elementId+' .sortable').addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
            } else {
                $('#'+elementId+' .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
            }

            applyFilters();
        }
<commit_msg>fix some bug<commit_after>        var pageSize = DEFAULT_PAGE_SIZE;
        var currPageNumber = 0;
        var sortDirection = false;
        var orderBy = DEFAULT_SORT_FIELD;

        $(document).ready(function() {
            $('#startDate, #endDate, #create_tender_enddate').datepicker({
                format: 'yyyy/mm/dd',
                startDate: '-5y'
            });

            initializeDateFilter();

            $("#category_filter").select2({
                placeholder: "All categories"
            });

            $("#item_dropdown").select2({
                placeholder: "All items"
            });

            $("#location_filter").select2({
                placeholder: "All locations"
            });

            $("#status_filter").select2({
                placeholder: "All active statuses"
            });

            $("#location_filter, #item_dropdown, #status_filter, #price_from, #price_to, #date_from, #date_to").change(function() {
                enableFilterButtons();
            });

            $("#pagination_itemsnum").on('change', function() {
                pageSize = this.value;
                currPageNumber = 0;
                showPage(currPageNumber);
            });

            $("#tender_title").click(function(){
                sortTenders("title","tender_title");
            });

            $("#tender_author").click(function(){
                sortTenders("author.firstName","tender_author");
            });

            $("#tender_suitable_price").click(function(){
                sortTenders("suitablePrice","tender_suitable_price");
            });

            $("#tender_status").click(function(){
                sortTenders("status.name","tender_status");
            });

            $("#tender_proposals").click(function(){
                sortTenders("proposals.size","tender_proposals");
            });

            $("#category_filter").change(function() {
                enableFilterButtons();
                $("#item_dropdown").select2('val', 'All');
                var str='';
                var categories=new Array();
                categories=$('#category_filter').val();
                if (categories!=null){
                    str += "categories="+categories;
                }
                $.ajax({
                    url: "/tenders/items",
                    type: "GET",
                    data:  str,
                    dataType:'json',

                    success: function(data) {
                        var html = '';
                        var len = data.length;
                        for (var i = 0; i < len; i++) {
                            html += '<option value="' + data[i].id + '">'
                                + data[i].name + '</option>';
                        }

                        $('#item_dropdown').html(html);
                    },
                    error:function(){
                        alert("ERROR");
                    }
                });
            });

            $.getJSON('/tenders/statuses', {
                  ajax : 'true'
                }, function(data){
                  var html;
                  var len = data.length;
                  for (var i = 0; i < len; i++) {
                      html += '<option value="' + data[i].id + '">'
                               + data[i].name + '</option>';
                  }
                  $('#status_filter').html(html);
            });

            $.getJSON('/tenders/locations', {
                ajax : 'true'
            }, function(loc){
                var html = ' ';
                var len = loc.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + loc[i].id + '">'
                            +loc[i].name + '</option>';
                }

                $('#location_filter').html(html);
            });

            $.getJSON('/tenders/categories', function(data){
                var html = ' ';
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + data[i].id + '">'
                            + data[i].name + '</option>';
                }

                $('#category_filter').html(html);
            });

            populateItemDropdown();
            showTenders();

            $('#search_input').keydown(function(event) {
                if (event.keyCode == 13) {
                    //search query

                    return false;
                }
            });
        });

        function populateItemDropdown() {
            $.getJSON('/tenders/items', function (data) {
                var html = '';
                var len = data.length;
                for (var i = 0; i < len; i++) {
                    html += '<option value="' + data[i].id + '">'
                            + data[i].name + '</option>';
                }

                $('#item_dropdown').html(html);
            });
        }

        function showTenders() {
            showPagination("");
            var queryParams = "pageSize=" + pageSize + "&pageNumber=" + currPageNumber + "&sortDirection=" +
                ((sortDirection)?"desc":"asc") + "&orderBy=" + orderBy;

            $.ajax({
                url: TENDERS_URL,
                type: "GET",
                data:  queryParams,
                dataType:'json',

                success: function(data) {
                    var html = '';
                    var dataSize = data.length;

                    if(dataSize > 0) {
                        for (var i = 0; i < dataSize; i++) {
                            html += '
' + data[i].title + '	' +
                                '' + data[i].authorName + '	' +
                                '' + data[i].categories + '	';
                                if (data[i].locations.toString().split(',').length>2){
                                    html += '' + data[i].locations.toString().split(',')[0] +','+data[i].locations.toString().split(',')[1] + '...'+'	';
                                }else{
                                    html += '' + data[i].locations + '	';
                                }

                            html += '' + data[i].suitablePrice + '	' +
                                '' + data[i].status + '	' +
                                '' + data[i].proposals + '	' +
                                '' +
                                '
' +
                                '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Action</button>' +
                                '
'+
                                '
View
';
                            if (data[i].roles.toString().search('CUSTOMER')!=-1){
                                if (data[i].userId.toString()==data[i].authorId.toString()){
                                    html += '
Close
';
                                }
                            }
                            if (data[i].roles.toString().search('SELLER')!=-1){
                                html += '
Create proposal
';
                            }
                            html +='
' +
                                '
' +
                                '
';
                        }

                        $('#user_message').html('');
                        $('#tender_items').show();
                        $('#tenders').html(html);
                    } else {
                        $('#user_message').html('
Your filter parameters did not match any tender
');
                        $('#tender_items').hide();
                    }
                },
                error:function(){
                    alert("ERROR");
                }
            });
        }

        function clearFilters() {
            disableFilterButtons();
            $("#price_from").val("");
            $("#price_to").val("");
            $("#date_from").val("");
            $("#date_to").val("");
            $("#location_filter").select2('val', 'All');
            $("#category_filter").select2('val', 'All');
            $("#item_dropdown").select2('val', 'All');
            $("#status_filter").select2('val', 'All');
            initializeDateFilter();

            showTenders();
        }

        function enableFilterButtons() {
            $("#filter_button").removeAttr("disabled");
            $("#clear_button").removeAttr("disabled");
        }

        function disableFilterButtons() {
            $("#filter_button").attr("disabled", "disabled");
            $("#clear_button").attr("disabled", "disabled");
        }

        function applyFilters() {
            disableFilterButtons();
            var str='';
            if($("#price_from").val()!=""){
                str+="minPrice="+$("#price_from").val();
            }
            if($("#price_to").val()!=""){
                str += (str.length==0)?"maxPrice="+$("#price_to").val():"&maxPrice="+$("#price_to").val();
            }
            var items=new Array();
            items=$('#item_dropdown').val();
            if (items!=null){
                str += (str.length==0)?"items="+items:"&items="+items;
            }

            var categories = new Array();
            categories = $('#category_filter').val();

            if (categories != null){
                $.ajax({
                    dataType: "json",
                    url: '/tenders/categories',
                    async: false,
                    success: function(data){
                        for(var z=0;z<categories.length;z++) {
                            var subCats = getSubCategories(categories[z],data,categories);
                            categories = categories.concat(subCats);
                        }
                    }
                });
                str += (str.length == 0)?"categories="+categories:"&categories="+categories;
            }

            var locations=new Array();
            locations=$('#location_filter').val();
            if (locations!=null){
                str += (str.length==0)?"locations="+locations:"&locations="+locations;
            }
            var statuses=new Array();
            statuses=$('#status_filter').val();
            if (statuses!=null){
                str += (str.length==0)?"statuses="+statuses:"&statuses="+statuses;
            }
            if($("#date_from").val()!=""){
                str += (str.length==0)?"minDate="+$("#date_from").val():"&minDate="+$("#date_from").val();
            }
            if($("#date_to").val()!=""){
                str += (str.length==0)?"maxDate="+$("#date_to").val():"&maxDate="+$("#date_to").val();
            }

            showPagination(str);
            str += (str.length==0)?"pageSize="+pageSize:"&pageSize="+pageSize;
            str += "&pageNumber="+currPageNumber + "&sortDirection=" + ((sortDirection)?"desc":"asc") + "&orderBy=" + orderBy;

            $.ajax({
                url: TENDERS_URL,
                type: "GET",
                data:  str,
                dataType:'json',

                success: function(data) {
                    var html = '';
                    var dataSize = data.length;

                    if(dataSize > 0) {
                        for (var i = 0; i < dataSize; i++) {
                            html += '
' + data[i].title + '	' +
                                '' + data[i].authorName + '	' +
                                '' + data[i].categories + '	';
                            if (data[i].locations.toString().split(',').length>2){
                                html += '' + data[i].locations.toString().split(',')[0] +','+data[i].locations.toString().split(',')[1] + '...'+'	';
                            }else{
                                html += '' + data[i].locations + '	';
                            }

                            html += '' + data[i].suitablePrice + '	' +
                                '' + data[i].status + '	' +
                                '' + data[i].proposals + '	' +
                                '' +
                                '
' +
                                '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Action</button>' +
                                '
'+
                                '
View
';
                            if (data[i].roles.toString().search('CUSTOMER')!=-1){
                                html += '
Close
';
                            }
                            if (data[i].roles.toString().search('SELLER')!=-1){
                                html += '
Create proposal
';
                            }
                            html +='
' +
                                '
' +
                                '
';
                        }

                        $('#user_message').html('');
                        $('#tender_items').show();
                        $('#tenders').html(html);
                    } else {
                        $('#user_message').html('
Your filter parameters did not match any tender
');
                        $('#tender_items').hide();
                    }
                },
                error:function(){
                    alert("ERROR");
                }
            });

            $("#clear_button").removeAttr("disabled");
        }

        function closeTender() {
            var str = '';
            str += "statusName=" + CLOSE_TENDER_STATUS_NAME;
            $.ajax({
                url: TENDERS_URL + "/" + $('#close_tender_id').val() + "?"  + str,
                type: "PUT",

                success: function(data){
                    closeModalWindow('close_tender_mod_wind');
                    showTenders()},
                error: function(){
                    alert("Something wrong")
                }
            })
        }

        function writeCloseTenderId(id) {
            document.getElementById('close_tender_id').value = id;
        }

        function closeModalWindow(id) {
            $('#' + id).modal('hide');
        }

        function initializeDateFilter() {
            var currentDate = getCurrentDate();
            var nextMonthDate = getNextMonthDate();

            $('#startDate').data({date: currentDate});
            $('#startDate').datepicker('update');
            $('#startDate').datepicker().children('input').val(currentDate);

            $('#endDate').data({date: nextMonthDate});
            $('#endDate').datepicker('update');
            $('#endDate').datepicker().children('input').val(nextMonthDate);
        }

        function getSubCategories(id,data,categories) {
            var dataSize = data.length;
            var subCats = new Array();

            for(var z=0;z<dataSize;z++) {
                if(id == data[z].parentId)
                {
                    if($.inArray(data[z].id, categories) != 0) {
                        subCats.push(data[z].id);
                    }
                }
            }

            return subCats;
        }

        function getCurrentDate() {
            var today = new Date();
            var day = today.getDate();
            var month = today.getMonth()+1;
            var year = today.getFullYear();

            if(day < 10) day = '0' + day;
            if(month < 10) month = '0' + month;

            return year + '/' + month + '/' + day;
        }

        function getNextMonthDate() {
            var today = new Date();
            var day = today.getDate();
            var month = today.getMonth()+2;
            var year = today.getFullYear();

            if(day < 10) day = '0' + day;
            if(month < 10) month = '0' + month;

            return year + '/' + month + '/' + day;
        }

        function goToRegistrationPage() {
            window.location.href = REGISTRATION_PAGE_URL;
        }

        function goToMyDealsPage() {
            window.location.href = MYDEALS_PAGE_URL;
        }

        function showPagination(queryParams) {
            $.ajax({
                url: TENDERS_NUMBER,
                async: false,
                type: "GET",
                data:  queryParams,
                dataType:'json',

                success: function(data) {
                    var dataSize = data.tendersNumber;
                    var pageNumber = Math.ceil(dataSize / pageSize);

                    if(dataSize > 0 && pageSize < dataSize) {
                         var html = '';
                         html += '
«
';
                         for(var z=1;z<=pageNumber;z++) {
                              html += '
'+z+'
';
                         }
                         html += '
»
';

                         $('.page_pagination').html(html).show();
                         $('#pagination').show();

                        if(currPageNumber != 0) {
                            document.getElementById('prev_page').setAttribute("onclick", "showPage("+(currPageNumber-1)+");");
                        }

                        if(currPageNumber != pageNumber-1) {
                            document.getElementById('next_page').setAttribute("onclick", "showPage("+(currPageNumber+1)+");");
                        }
                    } else {
                         $('.page_pagination').hide();
                    }
                },
                error:function(){
                    $('#pagination').hide();
                }
            });
        }

        function showPage(pageNumber) {
            currPageNumber = pageNumber;
            applyFilters();
        }

        function sortTenders(orderByField, elementId) {
            sortDirection = (orderBy == orderByField) ? !sortDirection : false;
            orderBy = orderByField;

            $('#tender_items .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
            if(sortDirection == false) {
                $('#'+elementId+' .sortable').addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
            } else {
                $('#'+elementId+' .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
            }

            applyFilters();
        }
<|endoftext|>