<commit_before>var global = require('../../global');

module.exports = function (purchaseRequest) {

    var items = [].concat.apply([], purchaseRequest.items);

    var iso = "FM-6.00-06-004/R1";
    var number = purchaseRequest.no;

    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var header = [{
        columns: [{
            columns: [{
                width: '*',
                stack: [{
                    text: 'PT DAN LIRIS',
                    style: ['size15'],
                    alignment: "center"
                }, {
                        text: 'BANARAN, GROGOL, SUKOHARJO 57193',
                        style: ['size09'],
                        alignment: "center"
                    },
                    {
                        text: 'No. Telp : (0271) 716888   Fax : (0271) 717818',
                        style: ['size09'],
                        alignment: "center"
                    }]
            }]

        }]
    }];

    var line = [{
        canvas: [{
    	       type: 'line',
            x1: 0,
            y1: 5,
            x2: 378,
            y2: 5,
            lineWidth: 0.5
        }
        ]
    }, '\n'];

    var subheader = [{
        columns: [{
            columns: [{
                width: '*',
                stack: [{
                    text: iso,
                    style: ['size09', 'bold'],
                    alignment: "right"
                },
                    {
                        text: 'ORDER PEMESANAN',
                        style: ['size09', 'bold'],
                        alignment: "center",
                        decoration: 'underline'
                    }]
            }]

        }]
    }];

    var subheader2 = [{
        columns: [
            {
                width: '40%',
                columns: [{
                    width: '35%',
                    stack: ['BAGIAN', 'Nomor']
                }, {
                        width: '5%',
                        stack: [':', ':']
                    }, {
                        width: '*',
                        stack: [purchaseRequest.unit.subDivision, purchaseRequest.no]
                    }],
                style: ['size08']

            },
            {
                width: '30%',
                text: ''
            },
            {
                width: '30%',
                columns: [{
                    width: '*',
                    stack: [`Solo, ${moment(purchaseRequest.date).format(locale.date.format)} `],
                    alignment: "right",
                }],
                style: ['size08']
            }
        ]
    }];

    var opening = {
        text: [
            '\n', {
                text: 'MOHON DIBELIKAN/DIUSAHAKAN BARANG TERSEBUT DIBAWAH INI : '
            },
            '\n\n'
        ],
        style: ['size09']
    };

    var thead = [{
        text: 'NO',
        style: 'tableHeader'
    }, {
            text: 'KODE',
            style: 'tableHeader'
        }, {
            text: 'BARANG',
            style: 'tableHeader'
        }, {
            text: 'JUMLAH',
            style: 'tableHeader'
        }, {
            text: 'HARGA',
            style: 'tableHeader'
        }];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size07', 'center']
        }, {
                text: item.product.code,
                style: ['size07', 'left']
            }, {
                text: item.product.name,
                style: ['size07', 'center']
            }, {
                text: parseFloat(item.quantity).toLocaleString(locale, locale.decimal) + " " + item.uom.unit,
                style: ['size07', 'center']
            }, {
                text: '',
                style: ['size07', 'left']
            }];
    });

    var tfoot = [[{
        text: " ",
        style: ['size08', 'center']
    }, "", "", "", ""]];

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 5
        }, "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '20%', '40%', '10%', '25%'],
            headerRows: 1,
            body: [].concat([thead], tbody, tfoot)
        }
    }];

    var footer = [
        '\n', {
            stack: [{
                columns: [{
                    width: '60%',
                    columns: [{
                        width: '50%',
                        stack: ['KATEGORI', 'DIMINTA DATANG', 'KETERANGAN']
                    }, {
                            width: '3%',
                            stack: [':', ':', ':']
                        }, {
                            width: '*',
                            stack: [purchaseRequest.category.name, `${moment(purchaseRequest.expectedDeliveryDate).format(locale.date.format)}`, purchaseRequest.remark]
                        },]
                }]
            }
            ],
            style: ['size08']
        }, '\n'
    ];

    var thead2 = [{
        text: 'BAGIAN ANGGARAN',
        style: 'tableHeader'
    }, {
            text: 'ACC MENGETAHUI',
            style: 'tableHeader'
        }, {
            text: 'BAGIAN PEMBELIAN',
            style: 'tableHeader'
        }, {
            text: 'KABAG PRODUKSI',
            style: 'tableHeader'
        }, {
            text: 'YANG MEMERLUKAN',
            style: 'tableHeader'
        }];

    var tbody2 = [[{
        text: " ",
        style: ['size30', 'center']
    }, "", "", "", ""]];

    var table2 = [{
        table: {
            widths: ['20%', '20%', '20%', '20%', '20%'],
            headerRows: 1,
            body: [].concat([thead2], tbody2)
        }
    }];

    var pr = {
        pageSize: 'A5',
        pageOrientation: 'portrait',
        pageMargins: 20,
        content: [].concat(header, line, subheader, subheader2, opening, table, footer, table2),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            size30: {
                fontSize: 30
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    };

    return pr;
}<commit_msg>fixing invalid date in print pdf PR<commit_after>var global = require('../../global');

module.exports = function (purchaseRequest) {

    var items = [].concat.apply([], purchaseRequest.items);

    var iso = "FM-6.00-06-004/R1";
    var number = purchaseRequest.no;

    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var header = [{
        columns: [{
            columns: [{
                width: '*',
                stack: [{
                    text: 'PT DAN LIRIS',
                    style: ['size15'],
                    alignment: "center"
                }, {
                        text: 'BANARAN, GROGOL, SUKOHARJO 57193',
                        style: ['size09'],
                        alignment: "center"
                    },
                    {
                        text: 'No. Telp : (0271) 716888   Fax : (0271) 717818',
                        style: ['size09'],
                        alignment: "center"
                    }]
            }]

        }]
    }];

    var line = [{
        canvas: [{
    	       type: 'line',
            x1: 0,
            y1: 5,
            x2: 378,
            y2: 5,
            lineWidth: 0.5
        }
        ]
    }, '\n'];

    var subheader = [{
        columns: [{
            columns: [{
                width: '*',
                stack: [{
                    text: iso,
                    style: ['size09', 'bold'],
                    alignment: "right"
                },
                    {
                        text: 'ORDER PEMESANAN',
                        style: ['size09', 'bold'],
                        alignment: "center",
                        decoration: 'underline'
                    }]
            }]

        }]
    }];

    var subheader2 = [{
        columns: [
            {
                width: '40%',
                columns: [{
                    width: '35%',
                    stack: ['BAGIAN', 'Nomor']
                }, {
                        width: '5%',
                        stack: [':', ':']
                    }, {
                        width: '*',
                        stack: [purchaseRequest.unit.subDivision, purchaseRequest.no]
                    }],
                style: ['size08']

            },
            {
                width: '30%',
                text: ''
            },
            {
                width: '30%',
                columns: [{
                    width: '*',
                    stack: [`Solo, ${moment(purchaseRequest.date).format(locale.date.format)} `],
                    alignment: "right",
                }],
                style: ['size08']
            }
        ]
    }];

    var opening = {
        text: [
            '\n', {
                text: 'MOHON DIBELIKAN/DIUSAHAKAN BARANG TERSEBUT DIBAWAH INI : '
            },
            '\n\n'
        ],
        style: ['size09']
    };

    var thead = [{
        text: 'NO',
        style: 'tableHeader'
    }, {
            text: 'KODE',
            style: 'tableHeader'
        }, {
            text: 'BARANG',
            style: 'tableHeader'
        }, {
            text: 'JUMLAH',
            style: 'tableHeader'
        }, {
            text: 'HARGA',
            style: 'tableHeader'
        }];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size07', 'center']
        }, {
                text: item.product.code,
                style: ['size07', 'left']
            }, {
                text: item.product.name,
                style: ['size07', 'center']
            }, {
                text: parseFloat(item.quantity).toLocaleString(locale, locale.decimal) + " " + item.uom.unit,
                style: ['size07', 'center']
            }, {
                text: '',
                style: ['size07', 'left']
            }];
    });

    var tfoot = [[{
        text: " ",
        style: ['size08', 'center']
    }, "", "", "", ""]];

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 5
        }, "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '20%', '40%', '10%', '25%'],
            headerRows: 1,
            body: [].concat([thead], tbody, tfoot)
        }
    }];

    var getDateexpected= purchaseRequest.expectedDeliveryDate && purchaseRequest.expectedDeliveryDate.toString().trim() != '' ?  moment(purchaseRequest.expectedDeliveryDate).format(locale.date.format) : '-';

    var footer = [
        '\n', {
            stack: [{
                columns: [{
                    width: '60%',
                    columns: [{
                        width: '50%',
                        stack: ['KATEGORI', 'DIMINTA DATANG', 'KETERANGAN']
                    }, {
                            width: '3%',
                            stack: [':', ':', ':']
                        }, {
                            width: '*',
                            stack: [purchaseRequest.category.name, `${getDateexpected}`, purchaseRequest.remark]
                        },]
                }]
            }
            ],
            style: ['size08']
        }, '\n'
    ];

    var thead2 = [{
        text: 'BAGIAN ANGGARAN',
        style: 'tableHeader'
    }, {
            text: 'ACC MENGETAHUI',
            style: 'tableHeader'
        }, {
            text: 'BAGIAN PEMBELIAN',
            style: 'tableHeader'
        }, {
            text: 'KABAG PRODUKSI',
            style: 'tableHeader'
        }, {
            text: 'YANG MEMERLUKAN',
            style: 'tableHeader'
        }];

    var tbody2 = [[{
        text: " ",
        style: ['size30', 'center']
    }, "", "", "", ""]];

    var table2 = [{
        table: {
            widths: ['20%', '20%', '20%', '20%', '20%'],
            headerRows: 1,
            body: [].concat([thead2], tbody2)
        }
    }];

    var pr = {
        pageSize: 'A5',
        pageOrientation: 'portrait',
        pageMargins: 20,
        content: [].concat(header, line, subheader, subheader2, opening, table, footer, table2),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            size30: {
                fontSize: 30
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    };

    return pr;
}<|endoftext|>


<commit_before>import OpenTracing from 'opentracing';

class InstrumentPageLoad {

    constructor() {
        this._inited = false;
        this._span = null;
    }

    name() {
        return 'instrument_page_load';
    }

    start(tracerImp) {
        if (this._inited) {
            return;
        }
        this._inited = true;

        if (typeof window !== 'object' || typeof document !== 'object') {
            return;
        }
        if (typeof window.Tracer !== 'object') {
            return;
        }

        this._ensureSpanStarted(tracerImp);
        document.addEventListener('readystatechange', this._handleReadyStateChange.bind(this));
    }

    stop() {
    }

    // NOTE: the plug-in initialization could be more elegant here. The core
    // problem here is that a common usage pattern the below:
    //
    //      initGlobalTracer(LightStep.tracer({ ... }))
    //
    // The plug-ins are initialized during the tracer() call, *but* the OpenTracing
    // Tracer is not set until the tracer() call *finishes*; thus, the global
    // tracer is not yet set for the plug-in initialization and it needs to
    // create a temporary handle.
    _ensureSpanStarted(tracerImp) {
        if (!this._span) {
            let tracer = OpenTracing.initNewTracer(tracerImp);
            this._span = tracer.startSpan('document/load');
            tracerImp.addActiveRootSpan(this._span.imp());
        }
    }

    _handleReadyStateChange() {
        if (!this._span) {
            return;
        }

        let span = this._span;
        let state = document.readyState;
        let payload = undefined;
        if (state === 'complete') {
            payload = {};
            if (window.performance && performance.timing) {
                this._addTimingSpans(span, performance.timing);
                payload['window.performance.timing'] = performance.timing;
            }
        }

        span.logEvent(`document.readystatechange ${state}`, payload);

        if (state === 'complete') {
            OpenTracing.imp().removeActiveRootSpan(span.imp());
            span.finish();
        }
    }

    _copyNavigatorProperties(nav) {
        let dst = {};
        for (let key in nav) {
            try {
                let value = nav[key];
                switch (key) {

                case 'plugins': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            name        : item.name,
                            description : item.description,
                        });
                    }
                    dst[key] = p;
                } break;

                case 'mimeTypes': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            type        : item.type,
                            description : item.description,
                            suffixes    : item.suffixes,
                        });
                    }
                    dst[key] = p;
                } break;

                default:
                    dst[key] = value;
                    break;
                }
            } catch (e) {
                // Skip, just in case
            }
        }
        return dst;
    }

    // Retroactively create the appropriate spans and logs
    _addTimingSpans(parent, timing) {
        // NOTE: this currently relies on LightStep-specific APIs
        let parentImp = parent.imp();
        if (!parentImp) {
            return;
        }

        parent.setTag('user_agent', navigator.userAgent);

        for (let key in timing) {
            let value = timing[key];

            // e.g. secureConnectionStart is not always set
            if (typeof value !== 'number' || value === 0) {
                continue;
            }

            let micros = value * 1000.0;
            let payload = undefined;

            if (key === 'navigationStart' && typeof navigator === 'object') {
                payload = {
                    navigator : this._copyNavigatorProperties(navigator),
                };
            }
            parentImp.log({
                message          : `document ${key}`,
                timestamp_micros : micros,
                payload          : payload,
            });
        }

        if (window.chrome && window.chrome.loadTimes) {
            let chromeTimes = window.chrome.loadTimes();
            if (chromeTimes) {
                parentImp.log({
                    message          : 'window.chrome.loadTimes()',
                    timestamp_micros : timing.domComplete * 1000.0,
                    payload          : chromeTimes,
                });
            }
        }

        parentImp.modify({
            begin_micros : timing.navigationStart * 1000.0,
        });
        parent.tracer().startSpan('document/time_to_first_byte', { parent : parent }).imp().modify({
            begin_micros : timing.requestStart * 1000.0,
            end_micros   : timing.responseStart * 1000.0,
        }).finish();
        parent.tracer().startSpan('document/response_transfer', { parent : parent }).imp().modify({
            begin_micros : timing.responseStart * 1000.0,
            end_micros   : timing.responseEnd * 1000.0,
        }).finish();
        parent.tracer().startSpan('document/dom_load', { parent : parent }).imp().modify({
            begin_micros : timing.domLoading * 1000.0,
            end_micros   : timing.domInteractive * 1000.0,
        }).finish();
    }
}

module.exports = new InstrumentPageLoad();
<commit_msg>Temporary patch for document load regression<commit_after>import OpenTracing from 'opentracing';

class InstrumentPageLoad {

    constructor() {
        this._inited = false;
        this._span = null;
    }

    name() {
        return 'instrument_page_load';
    }

    start(tracerImp) {
        if (this._inited) {
            return;
        }
        this._inited = true;

        if (typeof window !== 'object' || typeof document !== 'object') {
            return;
        }
        if (typeof window.Tracer !== 'object') {
            return;
        }

        this._ensureSpanStarted(tracerImp);
        document.addEventListener('readystatechange', this._handleReadyStateChange.bind(this));
    }

    stop() {
    }

    // NOTE: the plug-in initialization could be more elegant here. The core
    // problem here is that a common usage pattern the below:
    //
    //      initGlobalTracer(LightStep.tracer({ ... }))
    //
    // The plug-ins are initialized during the tracer() call, *but* the OpenTracing
    // Tracer is not set until the tracer() call *finishes*; thus, the global
    // tracer is not yet set for the plug-in initialization and it needs to
    // create a temporary handle.
    _ensureSpanStarted(tracerImp) {
        if (!this._span) {
            let tracer = OpenTracing.initNewTracer(tracerImp);
            this._span = tracer.startSpan('document/load');
            tracerImp.addActiveRootSpan(this._span.imp());
        }
    }

    _handleReadyStateChange() {
        if (!this._span) {
            return;
        }

        let span = this._span;
        let state = document.readyState;
        let payload = undefined;
        if (state === 'complete') {
            payload = {};
            if (window.performance && performance.timing) {
                this._addTimingSpans(span, performance.timing);
                payload['window.performance.timing'] = performance.timing;
            }
        }

        span.logEvent(`document.readystatechange ${state}`, payload);

        if (state === 'complete') {
            let tracerImp = OpenTracing.imp();
            if (tracerImp) {
                tracerImp.removeActiveRootSpan(span.imp());
            }
            span.finish();
        }
    }

    _copyNavigatorProperties(nav) {
        let dst = {};
        for (let key in nav) {
            try {
                let value = nav[key];
                switch (key) {

                case 'plugins': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            name        : item.name,
                            description : item.description,
                        });
                    }
                    dst[key] = p;
                } break;

                case 'mimeTypes': {
                    let p = [];
                    for (let i = 0; i < value.length; i++) {
                        let item = value.item(i);
                        p.push({
                            type        : item.type,
                            description : item.description,
                            suffixes    : item.suffixes,
                        });
                    }
                    dst[key] = p;
                } break;

                default:
                    dst[key] = value;
                    break;
                }
            } catch (e) {
                // Skip, just in case
            }
        }
        return dst;
    }

    // Retroactively create the appropriate spans and logs
    _addTimingSpans(parent, timing) {
        // NOTE: this currently relies on LightStep-specific APIs
        let parentImp = parent.imp();
        if (!parentImp) {
            return;
        }

        parent.setTag('user_agent', navigator.userAgent);

        for (let key in timing) {
            let value = timing[key];

            // e.g. secureConnectionStart is not always set
            if (typeof value !== 'number' || value === 0) {
                continue;
            }

            let micros = value * 1000.0;
            let payload = undefined;

            if (key === 'navigationStart' && typeof navigator === 'object') {
                payload = {
                    navigator : this._copyNavigatorProperties(navigator),
                };
            }
            parentImp.log({
                message          : `document ${key}`,
                timestamp_micros : micros,
                payload          : payload,
            });
        }

        if (window.chrome && window.chrome.loadTimes) {
            let chromeTimes = window.chrome.loadTimes();
            if (chromeTimes) {
                parentImp.log({
                    message          : 'window.chrome.loadTimes()',
                    timestamp_micros : timing.domComplete * 1000.0,
                    payload          : chromeTimes,
                });
            }
        }

        parentImp.modify({
            begin_micros : timing.navigationStart * 1000.0,
        });
        parent.tracer().startSpan('document/time_to_first_byte', { parent : parent }).imp().modify({
            begin_micros : timing.requestStart * 1000.0,
            end_micros   : timing.responseStart * 1000.0,
        }).finish();
        parent.tracer().startSpan('document/response_transfer', { parent : parent }).imp().modify({
            begin_micros : timing.responseStart * 1000.0,
            end_micros   : timing.responseEnd * 1000.0,
        }).finish();
        parent.tracer().startSpan('document/dom_load', { parent : parent }).imp().modify({
            begin_micros : timing.domLoading * 1000.0,
            end_micros   : timing.domInteractive * 1000.0,
        }).finish();
    }
}

module.exports = new InstrumentPageLoad();
<|endoftext|>


<commit_before>Ui.VBox.extend('Ui.MonthCalendar',
/**@lends Ui.MonthCalendar#*/
{
	selectedDate: undefined,
	date: undefined,
	title: undefined,
	leftarrow: undefined,
	rightarrow: undefined,
	grid: undefined,
	dayFilter: undefined,
	dateFilter: undefined,

	/**
	* @constructs
	* @class The MonthCalendar is a small month calendar which allow
	* to select a day.
	* @extends Ui.VBox
	*/
	constructor: function(config) {
		this.addEvents('dayselect');

		if('date' in config) {
			this.date = new Date(config.date.getTime());
			delete(config.date);
		}
		else
			this.date = new Date();
		if('selectedDate' in config) {
			this.selectedDate = config.selectedDate;
			delete(config.selectedDate);
		}

		var hbox = new Ui.HBox();
		this.append(hbox);

		var button = new Ui.Pressable({ verticalAlign: 'center' });
		this.leftarrow = new Ui.Icon({ icon: 'arrowleft', width: 24, height: 24 });
		button.append(this.leftarrow);
		hbox.append(button);
		this.connect(button, 'press', this.onLeftButtonPress);

		this.title = new Ui.Label({ fontWeight: 'bold', fontSize: 18, margin: 5 });
		hbox.append(this.title, true);

		button = new Ui.Pressable({ verticalAlign: 'center' });
		this.rightarrow = new Ui.Icon({ icon: 'arrowright', width: 24, height: 24 });
		button.append(this.rightarrow);
		hbox.append(button);
		this.connect(button, 'press', this.onRightButtonPress);

		this.grid = new Ui.Grid({ cols: 'auto,auto,auto,auto,auto,auto,auto', rows: 'auto,auto,auto,auto,auto,auto,auto', horizontalAlign: 'center' });
		this.append(this.grid);

		this.updateDate();
	},

	/**
	 * @param {Number[]} Array of day to disable (from 0 to 6), 0 is sunday
	 */
	setDayFilter: function(dayFilter) {
		this.dayFilter = dayFilter;
		this.updateDate();
	},

	/**
	 * @param {String[]} Array of dates to disable. This dates must always be in yyyy/mm/dd format and will be converted to regex
	 * so you can do a lot of things
	 * @ example
	 * var calendar = new Ui.MonthCalendar();
	 * calendar.setDateFilter([ '2011/11/2[1-5]', '2011/12/*', '2012/0[2-3]/.[4]' ]);
	 */
	setDateFilter: function(dateFilter) {
		this.dateFilter = dateFilter;
		this.updateDate();
	},

	/**#@+
	* @private
	*/

	onLeftButtonPress: function() {
		this.date.setMonth(this.date.getMonth() - 1);
		this.updateDate();
	},

	onRightButtonPress: function() {
		this.date.setMonth(this.date.getMonth() + 1);
		this.updateDate();
	},

	onDaySelect: function(button) {
		this.fireEvent('dayselect', this, button.monthCalendarDate);
	},

	updateDate: function() {
		var dayPivot = [ 6, 0, 1, 2, 3, 4, 5 ];
		var dayNames = [ 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa', 'Di' ];
		var monthNames = [ 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ];

		this.title.setText(monthNames[this.date.getMonth()]+' '+this.date.getFullYear());

		while(this.grid.getFirstChild() != undefined)
			this.grid.detach(this.grid.getFirstChild());

		for(var i = 0; i < 7; i++)
			this.grid.attach(new Ui.Label({ text: dayNames[i], fontWeight: 'bold', margin: 5 }), i, 0);

		var month = this.date.getMonth();
		var current = new Date(this.date.getTime());
		current.setDate(1);
		var row = 1;
		var now = new Date();
		do {
			var day = new Ui.Pressable();
			day.monthCalendarDate = current;
			this.connect(day, 'press', this.onDaySelect);

			var bg;
			if((current.getFullYear() == now.getFullYear()) && (current.getMonth() == now.getMonth()) && (current.getDate() == now.getDate())) {
				day.monthCalendarCurrent = true;
				bg = new Ui.Rectangle({ radius: 2, fill: new Ui.Color({ r: 0.2, g: 0.4, b: 1, a: 0.4 }), margin: 1 });
				day.append(bg);
			}
			else {
				bg = new Ui.Rectangle({ radius: 2, fill: new Ui.Color({ r: 0.8, g: 0.8, b: 0.8, a: 0.4 }), margin: 1 });
				day.append(bg);
			}

			if((this.selectedDate != undefined) && (current.getFullYear() == this.selectedDate.getFullYear()) && (current.getMonth() == this.selectedDate.getMonth()) && (current.getDate() == this.selectedDate.getDate()))
				day.append(new Ui.Frame({ frameWidth: 3, fill: 'red', radius: 2 }));

			var disable = false;
			if(this.dayFilter != undefined) {
				var weekday = current.getDay();
				for(var i = 0; (i < this.dayFilter.length) && !disable; i++)
					if(weekday == this.dayFilter[i])
						disable = true;
			}
			if(this.dateFilter != undefined) {
				var daystr = current.getFullYear()+'/';
				if(current.getMonth() + 1 < 10)
					daystr += '0';
				daystr += (current.getMonth()+1)+'/';
				if(current.getDate() < 10)
					daystr += '0';
				daystr += current.getDate();
				for(var i = 0; (i < this.dateFilter.length) && !disable; i++) {
					var re = new RegExp(this.dateFilter[i]);
					if(re.test(daystr)) {
						disable = true;
					}
				}
			}

			if(disable) {
				day.disable();
				day.setOpacity(0.2);
			}

			day.append(new Ui.Label({ text: current.getDate(), margin: 5 }))

			this.grid.attach(day, dayPivot[current.getDay()], row);
			current = new Date(current.getTime() + 1000*60*60*24);
			if(dayPivot[current.getDay()] == 0)
				row++;
		} while(month == current.getMonth());
		this.onStyleChange();
	}
	/**#@-*/
},
/** @lends Ui.MonthCalendar# */
{
	onStyleChange: function() {
		var color = this.getStyleProperty('color');
		var dayColor = this.getStyleProperty('dayColor');
		var currentDayColor = this.getStyleProperty('currentDayColor');
		this.title.setColor(color);
		this.leftarrow.setFill(color);
		this.rightarrow.setFill(color);

		for(var i = 0; i < this.grid.getChildren().length; i++) {
			var child = this.grid.getChildren()[i];
			if(Ui.Label.hasInstance(child))
				child.setColor(color);
			else if(Ui.Pressable.hasInstance(child)) {
				for(var i2 = 0; i2 < child.getChildren().length; i2++) {
					var child2 = child.getChildren()[i2];
					if(Ui.Label.hasInstance(child2))
						child2.setColor(color);
					else if(Ui.Rectangle.hasInstance(child2)) {
						if(child.monthCalendarCurrent)
							child2.setFill(currentDayColor);
						else
							child2.setFill(dayColor);
					}
				}
			}
		}
	}
},
/** @lends Ui.MonthCalendar */
{
    /** @fieldOf*/
	style: {
		color: 'black',
		dayColor: new Ui.Color({ r: 0.81, g: 0.81, b: 0.81, a: 0.5 }),
		currentDayColor: new Ui.Color({ r: 1, g: 0.31, b: 0.66, a: 0.5 })
	}
});

<commit_msg>change to square design, provide getSelectedDate method and display the currently selected date<commit_after>Ui.VBox.extend('Ui.MonthCalendar',
/**@lends Ui.MonthCalendar#*/
{
	selectedDate: undefined,
	date: undefined,
	title: undefined,
	leftarrow: undefined,
	rightarrow: undefined,
	grid: undefined,
	dayFilter: undefined,
	dateFilter: undefined,

	/**
	* @constructs
	* @class The MonthCalendar is a small month calendar which allow
	* to select a day.
	* @extends Ui.VBox
	*/
	constructor: function(config) {
		this.addEvents('dayselect');

		if('date' in config) {
			this.date = new Date(config.date.getTime());
			delete(config.date);
		}
		else
			this.date = new Date();
		if('selectedDate' in config) {
			this.selectedDate = config.selectedDate;
			delete(config.selectedDate);
		}

		var hbox = new Ui.HBox();
		this.append(hbox);

		var button = new Ui.Pressable({ verticalAlign: 'center' });
		this.leftarrow = new Ui.Icon({ icon: 'arrowleft', width: 24, height: 24 });
		button.append(this.leftarrow);
		hbox.append(button);
		this.connect(button, 'press', this.onLeftButtonPress);

		this.title = new Ui.Label({ fontWeight: 'bold', fontSize: 18, margin: 5 });
		hbox.append(this.title, true);

		button = new Ui.Pressable({ verticalAlign: 'center' });
		this.rightarrow = new Ui.Icon({ icon: 'arrowright', width: 24, height: 24 });
		button.append(this.rightarrow);
		hbox.append(button);
		this.connect(button, 'press', this.onRightButtonPress);

		this.grid = new Ui.Grid({ cols: 'auto,auto,auto,auto,auto,auto,auto', rows: 'auto,auto,auto,auto,auto,auto,auto', horizontalAlign: 'center' });
		this.append(this.grid);

		this.updateDate();
	},

	/**
	 * @param {Number[]} Array of day to disable (from 0 to 6), 0 is sunday
	 */
	setDayFilter: function(dayFilter) {
		this.dayFilter = dayFilter;
		this.updateDate();
	},

	/**
	 * @param {String[]} Array of dates to disable. This dates must always be in yyyy/mm/dd format and will be converted to regex
	 * so you can do a lot of things
	 * @ example
	 * var calendar = new Ui.MonthCalendar();
	 * calendar.setDateFilter([ '2011/11/2[1-5]', '2011/12/*', '2012/0[2-3]/.[4]' ]);
	 */
	setDateFilter: function(dateFilter) {
		this.dateFilter = dateFilter;
		this.updateDate();
	},

	/**#@+
	* @private
	*/

	onLeftButtonPress: function() {
		this.date.setMonth(this.date.getMonth() - 1);
		this.updateDate();
	},

	onRightButtonPress: function() {
		this.date.setMonth(this.date.getMonth() + 1);
		this.updateDate();
	},

	getSelectedDate: function() {
		return this.selectedDate;
	},

	onDaySelect: function(button) {
		this.selectedDate = button.monthCalendarDate;
		this.updateDate();
		this.fireEvent('dayselect', this, this.selectedDate);
	},

	updateDate: function() {
		var dayPivot = [ 6, 0, 1, 2, 3, 4, 5 ];
		var dayNames = [ 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa', 'Di' ];
		var monthNames = [ 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ];

		this.title.setText(monthNames[this.date.getMonth()]+' '+this.date.getFullYear());

		while(this.grid.getFirstChild() != undefined)
			this.grid.detach(this.grid.getFirstChild());

		for(var i = 0; i < 7; i++)
			this.grid.attach(new Ui.Label({ text: dayNames[i], fontWeight: 'bold', margin: 5 }), i, 0);

		var month = this.date.getMonth();
		var current = new Date(this.date.getTime());
		current.setDate(1);
		var row = 1;
		var now = new Date();
		do {
			var day = new Ui.Pressable();
			day.monthCalendarDate = current;
			this.connect(day, 'press', this.onDaySelect);

			var bg;
			if((current.getFullYear() == now.getFullYear()) && (current.getMonth() == now.getMonth()) && (current.getDate() == now.getDate())) {
				day.monthCalendarCurrent = true;
				bg = new Ui.Rectangle({ fill: new Ui.Color({ r: 0.2, g: 0.4, b: 1, a: 0.4 }), margin: 1 });
				day.append(bg);
			}
			else {
				bg = new Ui.Rectangle({ fill: new Ui.Color({ r: 0.8, g: 0.8, b: 0.8, a: 0.4 }), margin: 1 });
				day.append(bg);
			}

			if((this.selectedDate != undefined) && (current.getFullYear() == this.selectedDate.getFullYear()) && (current.getMonth() == this.selectedDate.getMonth()) && (current.getDate() == this.selectedDate.getDate()))
				day.append(new Ui.Frame({ frameWidth: 3, fill: 'red', radius: 2 }));

			var disable = false;
			if(this.dayFilter != undefined) {
				var weekday = current.getDay();
				for(var i = 0; (i < this.dayFilter.length) && !disable; i++)
					if(weekday == this.dayFilter[i])
						disable = true;
			}
			if(this.dateFilter != undefined) {
				var daystr = current.getFullYear()+'/';
				if(current.getMonth() + 1 < 10)
					daystr += '0';
				daystr += (current.getMonth()+1)+'/';
				if(current.getDate() < 10)
					daystr += '0';
				daystr += current.getDate();
				for(var i = 0; (i < this.dateFilter.length) && !disable; i++) {
					var re = new RegExp(this.dateFilter[i]);
					if(re.test(daystr)) {
						disable = true;
					}
				}
			}

			if(disable) {
				day.disable();
				day.setOpacity(0.2);
			}

			day.append(new Ui.Label({ text: current.getDate(), margin: 5 }))

			this.grid.attach(day, dayPivot[current.getDay()], row);
			current = new Date(current.getTime() + 1000*60*60*24);
			if(dayPivot[current.getDay()] == 0)
				row++;
		} while(month == current.getMonth());
		this.onStyleChange();
	}
	/**#@-*/
},
/** @lends Ui.MonthCalendar# */
{
	onStyleChange: function() {
		var color = this.getStyleProperty('color');
		var dayColor = this.getStyleProperty('dayColor');
		var currentDayColor = this.getStyleProperty('currentDayColor');
		this.title.setColor(color);
		this.leftarrow.setFill(color);
		this.rightarrow.setFill(color);

		for(var i = 0; i < this.grid.getChildren().length; i++) {
			var child = this.grid.getChildren()[i];
			if(Ui.Label.hasInstance(child))
				child.setColor(color);
			else if(Ui.Pressable.hasInstance(child)) {
				for(var i2 = 0; i2 < child.getChildren().length; i2++) {
					var child2 = child.getChildren()[i2];
					if(Ui.Label.hasInstance(child2))
						child2.setColor(color);
					else if(Ui.Rectangle.hasInstance(child2)) {
						if(child.monthCalendarCurrent)
							child2.setFill(currentDayColor);
						else
							child2.setFill(dayColor);
					}
				}
			}
		}
	}
},
/** @lends Ui.MonthCalendar */
{
    /** @fieldOf*/
	style: {
		color: 'black',
		dayColor: new Ui.Color({ r: 0.81, g: 0.81, b: 0.81, a: 0.5 }),
		currentDayColor: new Ui.Color({ r: 1, g: 0.31, b: 0.66, a: 0.5 })
	}
});

<|endoftext|>


<commit_before>function renameGroupClickHandler(obj) {
    obj.click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        var groupname = $(this).parent().parent();
        var name = groupname.find('.group-link').text();
        groupname.find('.editform input[name="groupname"]').val(name);
        groupname.find('.group-link').toggle();
        groupname.find('.editform').toggle();
        groupname.find('.editform input[name="groupname"]').focus();
    });
}

function renameGroupFormHandler(obj) {
    obj.submit(function(e) {
        e.preventDefault();

        var $form = $(this),
            fname = $form.find('input[name="groupname"]').val(),
            url = $form.attr('action');

        var groupname = $form.parent();

        var editloader = $form.find('.editloader');
        editloader.show();

        $.post (url, {'groupname':fname })
            .done(function (data) {
                groupname.find('.group-link').text(data.newname);
                editloader.hide();
                groupname.find('.group-link').toggle();
                groupname.find('.editform').toggle();
            });
    });
}

function removeGroupHandler(obj) {
	obj.click(function(e) {
		e.preventDefault();
        e.stopPropagation();
        var obj = $(this);

        $.getJSON(obj.next().attr('href'), function(data) {
            var dialog;

            if(data.last) {
                dialog = $('#removeGroupLastDialog');
            }
            else {
                dialog = $('#removeGroupDialog');
            }

            handleDialog(dialog, function(pageUnblock) {
                $.get(obj.attr('href'), function(data) {
                    data = $(data);
                    obj.parent().parent().parent().hide('drop', function() {
                        $(this).remove();
                    });
                    flashmessages.show(data.find('#flash-messages'));
                    pageUnblock();
                });
            });

        });
    });
}

function expandGroupHandler(obj, newpadform, uploadGroupPicture) {
    obj.click(function(e) {
        e.preventDefault();

        var obj = $(this).find('.group-link');
        var parent = obj.parent();
        var group = obj.parent().parent();
        var group_content = group.find('.group-content');

        if (group_content.hasClass('expanded-new')) { // Group has been expanded before, but isn't open group
            group_content.slideUp();
            group_content.removeClass('expanded-new');
        }
        else if (!group_content.hasClass('expanded')) {  // Group isn't open group, but should be expanded

            // Close other new expanded groups
            $('.group-content.expanded-new').slideUp();
            $('.group-content.expanded-new').removeClass('expanded-new');

            // Prepare loading process
            parent.find('.loader').show();
            group_content.slideUp();

            // Get the pads
            $.get(obj.attr('href'), function(data) {
                data = $(data);

                // Add the pads in this page
                var padscontent = group.find('.pads .content');
                padscontent.empty();
                padscontent.append(data.find('#pads').html());

                // Add click handler for openPad
                openPadAndGroupHandler(padscontent, group, uploadGroupPicture);

                // Add click handler for removePad
                removePadHandler(padscontent);
                parent.find('.loader').hide();

                // Show pad actions on hover
                showActionsHandler(padscontent.children());

                // Hide Removepad icon
                padscontent.find('.actions').hide();

                // Add "new pad" form under the pads
                newpadform.empty().append(data.find('#newpad').html());

                // expand actual group
                group_content.slideDown();
                group_content.addClass('expanded-new');

                // If no pad is open yet, open first one
                if($('#pad-content').hasClass('empty')) {
                    padscontent.find('a:first').click();
                }

            });
        }
    });
}

function newPadFormSubmitHandler(newpadform, uploadGroupPicture) {
    newpadform.submit(function(e){
        e.preventDefault();
        var obj = $(this);
        var padsloader = obj.parent().find('.loader');
        padsloader.show();

        var $form = $(this),
            fname = $form.find('input[name="form[name]"]').val(),
            ftoken = $form.find('input[name="form[_token]"]').val(),
            url = $form.attr('action');

        // Clear the form
        $form.find('input[name="form[name]"]').val('');

        // post form via ajax
        var posting = $.post (url, {'form[name]':fname, 'form[_token]':ftoken })
            .done(function (data) {
                if(data.success) {
                    data = $(data.data);
                    var padscontent = obj.parent().parent().find('.content');
                    // Get the newpad; hide it and its actions
                    var newpad = data.find('.pad').hide();
                    newpad.find('.actions').hide();
                    var newName = newpad.find('.padname').text().toLowerCase();
                    var inserted = false;
                    padscontent.children().each(function(index, element) {
                        element = $(element);
                        var padname = element.find('.padname').text();
                        if(strnatcmp(newName, padname.toLowerCase()) <=0 ) {
                            newpad.insertBefore(element);
                            inserted = true;
                            return false;
                        }
                    });
                    if(!inserted) {
                        padscontent.append(newpad);
                    }
                    padsloader.hide();
                    newpad.show('drop');
                    //newpad.slideDown();
                    removePadHandler(padscontent);
                    openPadAndGroupHandler(padscontent, padscontent.closest('.group'), uploadGroupPicture);
                    showActionsHandler(newpad);
                }
                else {
                    data = $(data.data);
                    padsloader.hide();
                    flashmessages.show(data.find('#flash-messages'));
                }
            });
    });
}

function handleDialog(obj, yesFunction) {

	obj.show();

	var dialogs = $('#removeDialogs');
	var page = $('#page');
	page.block({
		message: dialogs,
		onUnblock: function() {
			hideDialogs();
			yes.off();
			no.off();
		}
	});

	var yes = dialogs.find('.yes');
	var no = dialogs.find('.no');

	yes.click(function() {
		yesFunction(function() {
			page.unblock();
		});
	});

	no.click(function() {
		page.unblock();
	});
}

function hideDialogs() {
	$('#removeDialogs').find('div').hide();
}

function removePadHandler(obj) {
	obj.find('.padremovelink').off();
	obj.find('.padremovelink').click(function(e) {
        e.preventDefault();
        e.stopPropagation();

        var dialog = $('#removePadDialog');
        var obj = $(this);
        var padloader = obj.parent().parent().find('.loader');

        handleDialog(dialog, function(pageUnblock) {
        	pageUnblock();

        	padloader.show();
            $.get(obj.attr('href'), function(data) {
        		padloader.hide();
        		obj.parent().parent().hide('drop', function() {
        		    $(this).remove();
            		});
        		});
            });

        });
}

function openPadAndGroupHandler(obj, group, uploadGroupPicture) {
	obj.find('.pad').off('click');
	obj.find('.pad').click(function(e) {
		e.preventDefault();

		// Collabse other groups and expand actual group
		if(!group.find('.group-content').hasClass('expanded')) {
            var otherOpenGroup = $('.group-content.expanded');
			otherOpenGroup.slideUp();
            showActionsHandler(otherOpenGroup.parent().children('.group-name'));
	        otherOpenGroup.removeClass('expanded');

	        var newgroup = $('.group-content.expanded-new');
	        newgroup.removeClass('expanded-new');
	        newgroup.addClass('expanded');

	        $('.group-link.selected').removeClass('selected');
	        group.find('.group-link').addClass('selected');

	        // Only show actions for selected group
			$('.actions').fadeOut();
	        group.find('.group-name .actions').fadeIn();
            group.find('.group-name').off('hover mouseleave');

	        // Change the paths for the group picture
	        uploadGroupPicture.changePaths({
	        	pathAdd: newgroup.find('input[name="pathAdd"]').val(),
	    		pathRemove: newgroup.find('input[name="pathRemove"]').val()
	            });
	        // Change the pic
	        uploadGroupPicture.changePic(newgroup.find('input[name="picUrl"]').val());

		}

		clickedPadHandler($(this).children('.padname'));
	});
}

function openPadHandler(obj) {
	obj.find('.padname').off();
	obj.find('.padname').click(function(e) {
		e.preventDefault();

		clickedPadHandler(this);
	});
}

function clickedPadHandler (obj) {
	var obj = $(obj);

    var otherOpenPad = $('.padname.selected');

	// only show actions for selected pad
	$('.pads .actions').not(obj.parent().find('.actions')).fadeOut();
    showActionsHandler(otherOpenPad.parent());
	obj.parent().find('.actions').fadeIn();
    obj.parent().off('hover mouseleave');

	// deselect other pads & select this
	otherOpenPad.removeClass('selected');
	obj.addClass('selected');

	var pad = $('#pad');
	pad.block({
		message: $('#loader-bar'),
		overlayCSS: { backgroundColor: 'lightgray' },
		css: {
			border: 'none',
			backgroundColor: 'none' },
		onBlock: function() {
			$.get(obj.attr('href'), function(data) {
			    data = $(data);
			    var content = data.find('.page-content').html();
			    var padcontent = $('#pad-content');
			    padcontent.empty().append(content);
			    padcontent.removeClass('empty');
			    pad.unblock();
				});
			},
		onUnblock: function() {
			initPad();
			}
		});
}

function usernamesHandler() {
	$('.usernames').hide();
	var userinfo = $('.userinfo');

	userinfo.click(function(e) {
	    e.preventDefault();
	    $(this).parent().find('.usernames').slideToggle();
	    $(this).find('img').toggle();
		});

	userinfo.show();
}

function newUserHandler() {
	$('.adduserform').submit(function(e) {
		e.preventDefault();

		var $this = $(this);

		var $form = $(this),
        fname = $form.find('input[name="username"]').val(),
        url = $form.attr('action');

		// Show loader

		// Clear the form and disable it
    	$form.find('input[name="username"]').val('');
    	$form.children().prop('disabled', true);

    	var groupID = $form.closest('.group').attr('id');

        var posting = $.post (url, {'username':fname })
        .done(function (data) {
            data = $(data);
            // Hide loader

            var newUserNames = data.find('#'+groupID+' .usernames div');

            $('#'+groupID+' .usernames div').empty().append(newUserNames.html());

            var newUserNo = data.find('#'+groupID+' .userinfo .usernumber');
            $('#'+groupID+' .userinfo .usernumber').empty().append(newUserNo.html());

            $form.children().prop('disabled', false);

            flashmessages.show(data.find('#flash-messages'));

        });

	});
}

function showActionsHandler(obj) {
    obj.hover(function(){
        $(this).children('.actions').show();
    });
    obj.mouseleave(function(){
        $(this).children('.actions').hide();
    });
}<commit_msg>seperate click handler from function in groups.js<commit_after>function renameGroupClickHandler(obj) {
    obj.click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        var groupname = $(this).parent().parent();
        var name = groupname.find('.group-link').text();
        groupname.find('.editform input[name="groupname"]').val(name);
        groupname.find('.group-link').toggle();
        groupname.find('.editform').toggle();
        groupname.find('.editform input[name="groupname"]').focus();
    });
}

function renameGroupFormHandler(obj) {
    obj.submit(function(e) {
        e.preventDefault();

        var $form = $(this),
            fname = $form.find('input[name="groupname"]').val(),
            url = $form.attr('action');

        var groupname = $form.parent();

        var editloader = $form.find('.editloader');
        editloader.show();

        $.post (url, {'groupname':fname })
            .done(function (data) {
                groupname.find('.group-link').text(data.newname);
                editloader.hide();
                groupname.find('.group-link').toggle();
                groupname.find('.editform').toggle();
            });
    });
}

function removeGroupHandler(obj) {
	obj.click(function(e) {
		e.preventDefault();
        e.stopPropagation();
        var obj = $(this);

        $.getJSON(obj.next().attr('href'), function(data) {
            var dialog;

            if(data.last) {
                dialog = $('#removeGroupLastDialog');
            }
            else {
                dialog = $('#removeGroupDialog');
            }

            handleDialog(dialog, function(pageUnblock) {
                $.get(obj.attr('href'), function(data) {
                    data = $(data);
                    obj.parent().parent().parent().hide('drop', function() {
                        $(this).remove();
                    });
                    flashmessages.show(data.find('#flash-messages'));
                    pageUnblock();
                });
            });

        });
    });
}

function expandGroupHandler(obj, newpadform, uploadGroupPicture) {
    obj.click(function(e) {
        e.preventDefault();
        expandGroup($(this), newpadform, uploadGroupPicture, function(padscontent) {
            // If no pad is open yet, open first one
            if($('#pad-content').hasClass('empty')) {
                padscontent.find('a:first').click();
            }
        });
    });
}

function expandGroup($this, newpadform, uploadGroupPicture, callback) {
    var obj = $this.find('.group-link');
    var parent = obj.parent();
    var group = obj.parent().parent();
    var group_content = group.find('.group-content');

    if (group_content.hasClass('expanded-new')) { // Group has been expanded before, but isn't open group
        group_content.slideUp();
        group_content.removeClass('expanded-new');
    }
    else if (!group_content.hasClass('expanded')) {  // Group isn't open group, but should be expanded

        // Close other new expanded groups
        $('.group-content.expanded-new').slideUp();
        $('.group-content.expanded-new').removeClass('expanded-new');

        // Prepare loading process
        parent.find('.loader').show();
        group_content.slideUp();

        // Get the pads
        $.get(obj.attr('href'), function(data) {
            data = $(data);

            // Add the pads in this page
            var padscontent = group.find('.pads .content');
            padscontent.empty();
            padscontent.append(data.find('#pads').html());

            // Add click handler for openPad
            openPadAndGroupHandler(padscontent, group, uploadGroupPicture);

            // Add click handler for removePad
            removePadHandler(padscontent);
            parent.find('.loader').hide();

            // Show pad actions on hover
            showActionsHandler(padscontent.children());

            // Hide Removepad icon
            padscontent.find('.actions').hide();

            // Add "new pad" form under the pads
            newpadform.empty().append(data.find('#newpad').html());

            // expand actual group
            group_content.slideDown();
            group_content.addClass('expanded-new');

            callback(padscontent);
        });
    }
    else { // Group is open
        callback(group.find('.pads .content'))
    }
}

function newPadFormSubmitHandler(newpadform, uploadGroupPicture) {
    newpadform.submit(function(e){
        e.preventDefault();
        var obj = $(this);
        var padsloader = obj.parent().find('.loader');
        padsloader.show();

        var $form = $(this),
            fname = $form.find('input[name="form[name]"]').val(),
            ftoken = $form.find('input[name="form[_token]"]').val(),
            url = $form.attr('action');

        // Clear the form
        $form.find('input[name="form[name]"]').val('');

        // post form via ajax
        var posting = $.post (url, {'form[name]':fname, 'form[_token]':ftoken })
            .done(function (data) {
                if(data.success) {
                    data = $(data.data);
                    var padscontent = obj.parent().parent().find('.content');
                    // Get the newpad; hide it and its actions
                    var newpad = data.find('.pad').hide();
                    newpad.find('.actions').hide();
                    var newName = newpad.find('.padname').text().toLowerCase();
                    var inserted = false;
                    padscontent.children().each(function(index, element) {
                        element = $(element);
                        var padname = element.find('.padname').text();
                        if(strnatcmp(newName, padname.toLowerCase()) <=0 ) {
                            newpad.insertBefore(element);
                            inserted = true;
                            return false;
                        }
                    });
                    if(!inserted) {
                        padscontent.append(newpad);
                    }
                    padsloader.hide();
                    newpad.show('drop');
                    //newpad.slideDown();
                    removePadHandler(padscontent);
                    openPadAndGroupHandler(padscontent, padscontent.closest('.group'), uploadGroupPicture);
                    showActionsHandler(newpad);
                }
                else {
                    data = $(data.data);
                    padsloader.hide();
                    flashmessages.show(data.find('#flash-messages'));
                }
            });
    });
}

function handleDialog(obj, yesFunction) {

	obj.show();

	var dialogs = $('#removeDialogs');
	var page = $('#page');
	page.block({
		message: dialogs,
		onUnblock: function() {
			hideDialogs();
			yes.off();
			no.off();
		}
	});

	var yes = dialogs.find('.yes');
	var no = dialogs.find('.no');

	yes.click(function() {
		yesFunction(function() {
			page.unblock();
		});
	});

	no.click(function() {
		page.unblock();
	});
}

function hideDialogs() {
	$('#removeDialogs').find('div').hide();
}

function removePadHandler(obj) {
	obj.find('.padremovelink').off();
	obj.find('.padremovelink').click(function(e) {
        e.preventDefault();
        e.stopPropagation();

        var dialog = $('#removePadDialog');
        var obj = $(this);
        var padloader = obj.parent().parent().find('.loader');

        handleDialog(dialog, function(pageUnblock) {
        	pageUnblock();

        	padloader.show();
            $.get(obj.attr('href'), function(data) {
        		padloader.hide();
        		obj.parent().parent().hide('drop', function() {
        		    $(this).remove();
            		});
        		});
            });

        });
}

function openPadAndGroupHandler(obj, group, uploadGroupPicture) {
	obj.find('.pad').off('click');
	obj.find('.pad').click(function(e) {
		e.preventDefault();
		openPadAndGroup($(this), group, uploadGroupPicture)
	});
}

function openPadAndGroup($this, group, uploadGroupPicture) {

    // Collabse other groups and expand actual group
    if(!group.find('.group-content').hasClass('expanded')) {
        var otherOpenGroup = $('.group-content.expanded');
        otherOpenGroup.slideUp();
        showActionsHandler(otherOpenGroup.parent().children('.group-name'));
        otherOpenGroup.removeClass('expanded');

        var newgroup = $('.group-content.expanded-new');
        newgroup.removeClass('expanded-new');
        newgroup.addClass('expanded');

        $('.group-link.selected').removeClass('selected');
        group.find('.group-link').addClass('selected');

        // Only show actions for selected group
        $('.actions').fadeOut();
        group.find('.group-name .actions').fadeIn();
        group.find('.group-name').off('hover mouseleave');

        // Change the paths for the group picture
        uploadGroupPicture.changePaths({
            pathAdd: newgroup.find('input[name="pathAdd"]').val(),
            pathRemove: newgroup.find('input[name="pathRemove"]').val()
        });
        // Change the pic
        uploadGroupPicture.changePic(newgroup.find('input[name="picUrl"]').val());

    }

    clickedPadHandler($this.children('.padname'));
}

function openPadHandler(obj) {
	obj.find('.padname').off();
	obj.find('.padname').click(function(e) {
		e.preventDefault();

		clickedPadHandler(this);
	});
}

function clickedPadHandler (obj) {
	var obj = $(obj);

    var otherOpenPad = $('.padname.selected');

	// only show actions for selected pad
	$('.pads .actions').not(obj.parent().find('.actions')).fadeOut();
    showActionsHandler(otherOpenPad.parent());
	obj.parent().find('.actions').fadeIn();
    obj.parent().off('hover mouseleave');

	// deselect other pads & select this
	otherOpenPad.removeClass('selected');
	obj.addClass('selected');

	var pad = $('#pad');
	pad.block({
		message: $('#loader-bar'),
		overlayCSS: { backgroundColor: 'lightgray' },
		css: {
			border: 'none',
			backgroundColor: 'none' },
		onBlock: function() {
			$.get(obj.attr('href'), function(data) {
			    data = $(data);
			    var content = data.find('.page-content').html();
			    var padcontent = $('#pad-content');
			    padcontent.empty().append(content);
			    padcontent.removeClass('empty');
			    pad.unblock();
				});
			},
		onUnblock: function() {
			initPad();
			}
		});
}

function usernamesHandler() {
	$('.usernames').hide();
	var userinfo = $('.userinfo');

	userinfo.click(function(e) {
	    e.preventDefault();
	    $(this).parent().find('.usernames').slideToggle();
	    $(this).find('img').toggle();
		});

	userinfo.show();
}

function newUserHandler() {
	$('.adduserform').submit(function(e) {
		e.preventDefault();

		var $this = $(this);

		var $form = $(this),
        fname = $form.find('input[name="username"]').val(),
        url = $form.attr('action');

		// Show loader

		// Clear the form and disable it
    	$form.find('input[name="username"]').val('');
    	$form.children().prop('disabled', true);

    	var groupID = $form.closest('.group').attr('id');

        var posting = $.post (url, {'username':fname })
        .done(function (data) {
            data = $(data);
            // Hide loader

            var newUserNames = data.find('#'+groupID+' .usernames div');

            $('#'+groupID+' .usernames div').empty().append(newUserNames.html());

            var newUserNo = data.find('#'+groupID+' .userinfo .usernumber');
            $('#'+groupID+' .userinfo .usernumber').empty().append(newUserNo.html());

            $form.children().prop('disabled', false);

            flashmessages.show(data.find('#flash-messages'));

        });

	});
}

function showActionsHandler(obj) {
    obj.hover(function(){
        $(this).children('.actions').show();
    });
    obj.mouseleave(function(){
        $(this).children('.actions').hide();
    });
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, nomen: true, regexp: true, maxerr: 50 */
/*global define, brackets, $, window */

define(function (require, exports, module) {
    "use strict";

    var InlineWidget         = brackets.getModule("editor/InlineWidget").InlineWidget,
        ColorEditor          = require("ColorEditor").ColorEditor,
        InlineEditorTemplate = require("text!InlineColorEditorTemplate.html");

    var MAX_USED_COLORS = 7;

    function InlineColorEditor(color, startBookmark, endBookmark) {
        this.color = color;
        this.startBookmark = startBookmark;
        this.endBookmark = endBookmark;
        this.setColor = this.setColor.bind(this);

        InlineWidget.call(this);
    }

    InlineColorEditor.colorRegEx = /#[a-f0-9]{6}|#[a-f0-9]{3}|rgb\( ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?\)|rgba\( ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b(1|0|0\.[0-9]{1,3}) ?\)|hsl\( ?\b([0-9]{1,2}|[12][0-9]{2}|3[0-5][0-9]|360)\b ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b([0-9]{1,2}|100)\b% ?\)|hsla\( ?\b([0-9]{1,2}|[12][0-9]{2}|3[0-5][0-9]|360)\b ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b(1|0|0\.[0-9]{1,3}) ?\)/gi;

    InlineColorEditor.prototype = new InlineWidget();
    InlineColorEditor.prototype.constructor = InlineColorEditor;
    InlineColorEditor.prototype.parentClass = InlineWidget.prototype;
    InlineColorEditor.prototype.$wrapperDiv = null;

    InlineColorEditor.prototype.setColor = function (colorLabel) {
        var start, end;
        if (!colorLabel) {
            return;
        }

        if (colorLabel !== this.color) {
            start = this.startBookmark.find();
            if (!start) {
                return;
            }

            end = this.endBookmark.find();
            if (!end || start.ch === end.ch) {
                end = { line: start.line,
                        ch: start.ch + (this.color ? this.color.length : 0) };
            }

            this.editor.document.replaceRange(colorLabel, start, end);
            this.editor.setSelection(start, {
                line: start.line,
                ch: start.ch + colorLabel.length
            });
            this.color = colorLabel;
        }
    };

    InlineColorEditor.prototype.load = function (hostEditor) {
        var selectedColors = [];
        this.editor = hostEditor;
        this.parentClass.load.call(this, hostEditor);
        selectedColors = this.editor.document.getText().match(InlineColorEditor.colorRegEx);
        selectedColors = this.usedColors(selectedColors, MAX_USED_COLORS);
        this.$wrapperDiv = $(InlineEditorTemplate);
        this.colorEditor = new ColorEditor(this.$wrapperDiv, this.color, this.setColor, selectedColors);
        this.$htmlContent.append(this.$wrapperDiv);
    };

    InlineColorEditor.prototype._editorHasFocus = function () {
        return true;
    };

    InlineColorEditor.prototype.clearBookmarks = function () {
        this.startBookmark.clear();
        this.endBookmark.clear();
    };

    InlineColorEditor.prototype.onAdded = function () {
        window.setTimeout(this._sizeEditorToContent.bind(this));
        this.colorEditor.focus();
    };

    InlineColorEditor.prototype._sizeEditorToContent = function () {
        this.hostEditor.setInlineWidgetHeight(this, this.$wrapperDiv.outerHeight(), true);
    };

    function _colorSort(a, b) {
        if (a.count === b.count) {
            return 0;
        }
        if (a.count > b.count) {
            return -1;
        }
        if (a.count < b.count) {
            return 1;
        }
    }

    InlineColorEditor.prototype.usedColors = function (originalArray, length) {
        var copyArray,
            compressed = [];

        copyArray = $.map(originalArray, function (color) {
            return color.toLowerCase();
        });

        compressed = $.map(originalArray, function (originalColor) {
            var a = {},
                lastIndex = 0,
                colorCount = 0,
                colorCopy = originalColor.toLowerCase();

            do {
                lastIndex = copyArray.indexOf(colorCopy, lastIndex);
                if (lastIndex !== -1) {
                    colorCount++;
                    copyArray.splice(lastIndex, 1);
                }
            } while (lastIndex !== -1 && copyArray.length);

            if (colorCount > 0) {
                a.value = originalColor;
                a.count = colorCount;
                return a;
            }
        }).sort(_colorSort);

        return compressed;
    };

    module.exports.InlineColorEditor = InlineColorEditor;
});
<commit_msg>Limit existing color swatches to be shown as the number defined in MAX_USED_COLORS.<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, nomen: true, regexp: true, maxerr: 50 */
/*global define, brackets, $, window */

define(function (require, exports, module) {
    "use strict";

    var InlineWidget         = brackets.getModule("editor/InlineWidget").InlineWidget,
        ColorEditor          = require("ColorEditor").ColorEditor,
        InlineEditorTemplate = require("text!InlineColorEditorTemplate.html");

    var MAX_USED_COLORS = 7;

    function InlineColorEditor(color, startBookmark, endBookmark) {
        this.color = color;
        this.startBookmark = startBookmark;
        this.endBookmark = endBookmark;
        this.setColor = this.setColor.bind(this);

        InlineWidget.call(this);
    }

    InlineColorEditor.colorRegEx = /#[a-f0-9]{6}|#[a-f0-9]{3}|rgb\( ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?\)|rgba\( ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b(1|0|0\.[0-9]{1,3}) ?\)|hsl\( ?\b([0-9]{1,2}|[12][0-9]{2}|3[0-5][0-9]|360)\b ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b([0-9]{1,2}|100)\b% ?\)|hsla\( ?\b([0-9]{1,2}|[12][0-9]{2}|3[0-5][0-9]|360)\b ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b(1|0|0\.[0-9]{1,3}) ?\)/gi;

    InlineColorEditor.prototype = new InlineWidget();
    InlineColorEditor.prototype.constructor = InlineColorEditor;
    InlineColorEditor.prototype.parentClass = InlineWidget.prototype;
    InlineColorEditor.prototype.$wrapperDiv = null;

    InlineColorEditor.prototype.setColor = function (colorLabel) {
        var start, end;
        if (!colorLabel) {
            return;
        }

        if (colorLabel !== this.color) {
            start = this.startBookmark.find();
            if (!start) {
                return;
            }

            end = this.endBookmark.find();
            if (!end || start.ch === end.ch) {
                end = { line: start.line,
                        ch: start.ch + (this.color ? this.color.length : 0) };
            }

            this.editor.document.replaceRange(colorLabel, start, end);
            this.editor.setSelection(start, {
                line: start.line,
                ch: start.ch + colorLabel.length
            });
            this.color = colorLabel;
        }
    };

    InlineColorEditor.prototype.load = function (hostEditor) {
        var selectedColors = [];
        this.editor = hostEditor;
        this.parentClass.load.call(this, hostEditor);
        selectedColors = this.editor.document.getText().match(InlineColorEditor.colorRegEx);
        selectedColors = this.usedColors(selectedColors, MAX_USED_COLORS);
        this.$wrapperDiv = $(InlineEditorTemplate);
        this.colorEditor = new ColorEditor(this.$wrapperDiv, this.color, this.setColor, selectedColors);
        this.$htmlContent.append(this.$wrapperDiv);
    };

    InlineColorEditor.prototype._editorHasFocus = function () {
        return true;
    };

    InlineColorEditor.prototype.clearBookmarks = function () {
        this.startBookmark.clear();
        this.endBookmark.clear();
    };

    InlineColorEditor.prototype.onAdded = function () {
        window.setTimeout(this._sizeEditorToContent.bind(this));
        this.colorEditor.focus();
    };

    InlineColorEditor.prototype._sizeEditorToContent = function () {
        this.hostEditor.setInlineWidgetHeight(this, this.$wrapperDiv.outerHeight(), true);
    };

    function _colorSort(a, b) {
        if (a.count === b.count) {
            return 0;
        }
        if (a.count > b.count) {
            return -1;
        }
        if (a.count < b.count) {
            return 1;
        }
    }

    InlineColorEditor.prototype.usedColors = function (originalArray, length) {
        var copyArray,
            compressed = [];

        copyArray = $.map(originalArray, function (color) {
            return color.toLowerCase();
        });

        compressed = $.map(originalArray, function (originalColor) {
            var a = {},
                lastIndex = 0,
                colorCount = 0,
                colorCopy = originalColor.toLowerCase();

            do {
                lastIndex = copyArray.indexOf(colorCopy, lastIndex);
                if (lastIndex !== -1) {
                    colorCount++;
                    copyArray.splice(lastIndex, 1);
                }
            } while (lastIndex !== -1 && copyArray.length);

            if (colorCount > 0) {
                a.value = originalColor;
                a.count = colorCount;
                return a;
            }
        }).sort(_colorSort);

        return compressed.slice(0, length);
    };

    module.exports.InlineColorEditor = InlineColorEditor;
});
<|endoftext|>


<commit_before>jsio('external .sizzle import Sizzle');

import math.geom.Rect;

function isWindow(el) {
	return el && !$.isElement(el) && $.isElement(el.document);
}

var singleId = /^#([\w-]+)$/;

var $ = exports.$ = function(selector, win) {
	switch(typeof selector) {
		case 'object':
			if ($.isElement(selector)) {
				return $.remove(selector);
			} else if ($.isElement(selector.document && selector.document.body)) {
				return $.size(selector);
			}
			return $.create(selector);
		case 'string':
			if (singleId.test(selector)) { return $.id(selector.substring(1), win); }
			return Sizzle.apply(GLOBAL, arguments);
	}
}

var DOM2 = typeof HTMLElement === "object";
$.isElement = DOM2
	? function(el) { return el && el instanceof HTMLElement; }
	: function(el) { return el && typeof el.nodeType == 'number' && typeof el.nodeName == 'string' };

$.id = function(id, win) { return typeof id == 'string' ? (win || window).document.getElementById(id) : id; }

$.apply = function(el, params) {
	if (params.attrs) {
		for(attr in params.attrs) {
			el.setAttribute(attr, params.attrs[attr]);
		}
	}

	if (params.id) { el.id = params.id; }
	if (params.style) { $.style(el, params.style); }
	if (params.src) { el.src = params.src; }
	if (params['class'] || params['className']) {
		el.className = params['class'] || params['className'];
	}

	var parent = params.parent || params.parentNode;
	if (parent && params.first) {
		$.insertBefore(parent, el, parent.firstChild);
	} else if (params.before) {
		$.insertBefore(params.before.parentNode || parent, el, params.before);
	} else if (params.after) {
		$.insertAfter(params.after.parentNode || parent, el, params.after);
	} else if (parent) {
		parent.appendChild(el);
	}

	if ('html' in params) { el.innerHTML = params.html; }
	if ('text' in params) { $.setText(el, params.text); }

	if (params.children) {
		var c = params.children;
		for (var i = 0, n = c.length; i < n; ++i) {
			el.appendChild($.isElement(c[i]) ? c[i] : $(c[i]));
		}
	}

	return el;
}

$.insertBefore = function(parentNode, el, beforeNode) {
	if (!parentNode || !el) { return; }
	if (beforeNode && beforeNode.parentNode == parentNode) {
		parentNode.insertBefore(el, beforeNode);
	} else {
		parentNode.appendChild(el);
	}
}

$.insertAfter = function(parentNode, el, afterNode) {
	if (!parentNode || !el) { return; }
	if (!afterNode || afterNode.parentNode != parentNode) {
		$.insertBefore(parentNode, el, parentNode.firstChild);
	} else if (!afterNode.nextSibling) {
		parentNode.appendChild(el);
	} else {
		parentNode.insertBefore(el, afterNode.nextSibling);
	}
}

$.create = function(params) {
	var doc = ((params && params.win) || window).document;
	if (!params || typeof params == 'string') {
		return doc.createElement(params || 'div');
	};

	return $.apply(params.el || doc.createElement(params.tag || params.tagName || 'div'), params);
}

$.show = function(el, how) { $.id(el).style.display = how || 'block'; }
$.hide = function(el) { $.id(el).style.display = 'none'; }

// accepts an array or a space-delimited string of classNames
$.addClass = function(el, classNames) {
	if (!el) { return; }
	var el = $.id(el);
	if (typeof classNames == "string") {
		classNames = classNames.split(' ');
	}

	var current = ' ' + el.className + ' ';
	for (var i = 0, len = classNames.length; i < len; ++i) {
		var c = classNames[i];
		if (current.indexOf(' ' + c + ' ') == -1) {
			current += c + ' ';
		}
	}

	el.className = current.replace(/^\s+|\s+$/g, '');
	return $;
}

$.getTag = function(from, tag) { return from.getElementsByTagName(tag); }

$.removeClass = function(el, classNames) {
	if (!el) { return; }
	var el = $.id(el);
	el.className = (' ' + el.className + ' ')
		.replace(' ', '  ')
		.replace(new RegExp('( ' + classNames.replace('\s+', ' | ').replace('-','\-') + ' )', 'g'), ' ')
		.replace(/\s+/, ' ')
		.replace(/^\s+|\s+$/g, '');
}

function ieGetAlpha(el) {
	try {
		return el.filters.item("alpha");
	} catch(e) {}

	try {
		return el.filters.item("progid:DXImageTransform.Microsoft.Alpha");
	} catch(e) {}

	return null;
}

$.style = function(el, style) {
	if(el instanceof Array) {
		for(var i = 0, o; o = el[i]; ++i) { $.style(o, style); }
		return;
	}

	el = $.id(el);
	var s = el.style;
	for(prop in style) {
		switch(prop) {
			case 'styleFloat':
			case 'cssFloat':
			case 'float':
				s.styleFloat = s.cssFloat = style[prop];
				break;
			case 'opacity':
				s.opacity = style[prop];
				if(el.filters) {
					try {
						var alpha = ieGetAlpha();
						var opacity = style[prop] == 1 ? 99.99 : style[prop] * 100;
						if(!alpha) {
							// TODO: this might destroy any existing filters?
							s.filter = "alpha(opacity=" + opacity + ")";
						} else {
							alpha.Opacity = opacity;
						}
					} catch(e) {}
				}
				break;
			case 'borderRadius':
				s.borderRadius = s.MozBorderRadius = style[prop];
				break;
			case 'boxSizing':
				s.MsBoxSizing = s.MozBoxSizing = s.WebkitBoxSizing = style[prop];
			default:
				s[prop] = style[prop];
				break;
		}
	}
};

$.onEvent = function(el, name, f) {
	if (typeof f != 'function') {
		f = bind.apply(GLOBAL, Array.prototype.slice.call(arguments, 2));
	}

	var handler = f;

	el = $.id(el);
	if(el.addEventListener) {
		el.addEventListener(name, handler, false);
	} else {
		handler = function(e) {
			var evt = e || window.event;
			// TODO: normalize the event object
			f(evt);
		};

		el.attachEvent('on' + name, handler);
	}

	return bind($, 'removeEvent', el, name, handler);
};

$.removeEvent = function(el, name, f) {
	el = $.id(el);
	if (el.addEventListener) {
		el.removeEventListener(name, f, false);
	} else {
		el.detachEvent('on' + name, f);
	}
}

$.stopEvent = function(e) {
	if (e) {
		e.cancelBubble = true;
		if(e.stopPropagation) e.stopPropagation();
		if(e.preventDefault) e.preventDefault();
	}
}

$.setText = function(el, text) {
	el = $.id(el);
	text = String(text);
	if ('textContent' in el) {
		el.textContent = text;
	} else if ('innerText' in el) {
		el.innerText = text.replace(/\n/g, ' ');
	} else {
		el.innerHTML = '';
		el.appendChild(document.createTextNode(text));
	}
}

$.setValue = function(el, value) {
	el = $.id(el);
	if ('value' in el) {
		el.value = value;
	} else if ('value' in el.firstChild) {
		el.firstChild.value = value;
	}
};

$.remove = function(el) {
	el = $.id(el);
	if(el && el.parentNode) {
		el.parentNode.removeChild(el);
	}
}

$.cursorPos = function(ev, el) {
	var offset = $.pos(el);
	offset.top = ev.clientY - offset.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
	offset.left = ev.clientX - offset.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft);
	return offset;
}

$.pos = function(el) {
	var parent = el;
	var offset = {top: 0, left: 0};
	while(parent && parent != document.body) {
		offset.left += parent.offsetLeft;
		offset.top += parent.offsetTop;
		while(parent.offsetParent != parent.parentNode) {
			offset.top -= parent.scrollTop; offset.left -= parent.scrollLeft;
			parent = parent.parentNode;
		}
		parent = parent.offsetParent;
	}
	return offset;
}

$.size = function(el) {
	if ($.isElement(el)) {
		return {width: el.offsetWidth, height: el.offsetHeight};
	} else if (el.document) {
		var doc = el.document.documentElement || el.document.body;
		return new math.geom.Rect(
			doc.offsetTop,
			doc.offsetLeft,
			el.innerWidth || (doc.clientWidth || doc.clientWidth),
			el.innerHeight || (doc.clientHeight || doc.clientHeight)
		);
	}
}

$.insertCSSFile = function(filename) {
	document.getElementsByTagName('head')[0].appendChild($({
		tag: 'link',
		attrs: {
			rel: 'stylesheet',
			type: 'text/css',
			href: filename
		}
	}));
}
<commit_msg>add hasClass method to browser utils<commit_after>jsio('external .sizzle import Sizzle');

import math.geom.Rect;

function isWindow(el) {
	return el && !$.isElement(el) && $.isElement(el.document);
}

var singleId = /^#([\w-]+)$/;

var $ = exports.$ = function(selector, win) {
	switch(typeof selector) {
		case 'object':
			if ($.isElement(selector)) {
				return $.remove(selector);
			} else if ($.isElement(selector.document && selector.document.body)) {
				return $.size(selector);
			}
			return $.create(selector);
		case 'string':
			if (singleId.test(selector)) { return $.id(selector.substring(1), win); }
			return Sizzle.apply(GLOBAL, arguments);
	}
}

var DOM2 = typeof HTMLElement === "object";
$.isElement = DOM2
	? function(el) { return el && el instanceof HTMLElement; }
	: function(el) { return el && typeof el.nodeType == 'number' && typeof el.nodeName == 'string' };

$.id = function(id, win) { return typeof id == 'string' ? (win || window).document.getElementById(id) : id; }

$.apply = function(el, params) {
	if (params.attrs) {
		for(attr in params.attrs) {
			el.setAttribute(attr, params.attrs[attr]);
		}
	}

	if (params.id) { el.id = params.id; }
	if (params.style) { $.style(el, params.style); }
	if (params.src) { el.src = params.src; }
	if (params['class'] || params['className']) {
		el.className = params['class'] || params['className'];
	}

	var parent = params.parent || params.parentNode;
	if (parent && params.first) {
		$.insertBefore(parent, el, parent.firstChild);
	} else if (params.before) {
		$.insertBefore(params.before.parentNode || parent, el, params.before);
	} else if (params.after) {
		$.insertAfter(params.after.parentNode || parent, el, params.after);
	} else if (parent) {
		parent.appendChild(el);
	}

	if ('html' in params) { el.innerHTML = params.html; }
	if ('text' in params) { $.setText(el, params.text); }

	if (params.children) {
		var c = params.children;
		for (var i = 0, n = c.length; i < n; ++i) {
			el.appendChild($.isElement(c[i]) ? c[i] : $(c[i]));
		}
	}

	return el;
}

$.insertBefore = function(parentNode, el, beforeNode) {
	if (!parentNode || !el) { return; }
	if (beforeNode && beforeNode.parentNode == parentNode) {
		parentNode.insertBefore(el, beforeNode);
	} else {
		parentNode.appendChild(el);
	}
}

$.insertAfter = function(parentNode, el, afterNode) {
	if (!parentNode || !el) { return; }
	if (!afterNode || afterNode.parentNode != parentNode) {
		$.insertBefore(parentNode, el, parentNode.firstChild);
	} else if (!afterNode.nextSibling) {
		parentNode.appendChild(el);
	} else {
		parentNode.insertBefore(el, afterNode.nextSibling);
	}
}

$.create = function(params) {
	var doc = ((params && params.win) || window).document;
	if (!params || typeof params == 'string') {
		return doc.createElement(params || 'div');
	};

	return $.apply(params.el || doc.createElement(params.tag || params.tagName || 'div'), params);
}

$.show = function(el, how) { $.id(el).style.display = how || 'block'; }
$.hide = function(el) { $.id(el).style.display = 'none'; }

// accepts an array or a space-delimited string of classNames
$.addClass = function(el, classNames) {
	if (!el) { return; }
	var el = $.id(el);
	if (typeof classNames == "string") {
		classNames = classNames.split(' ');
	}

	var current = ' ' + el.className + ' ';
	for (var i = 0, len = classNames.length; i < len; ++i) {
		var c = classNames[i];
		if (current.indexOf(' ' + c + ' ') == -1) {
			current += c + ' ';
		}
	}

	el.className = current.replace(/^\s+|\s+$/g, '');
	return $;
}

/* returns true if the given className is found in the list of
 * classes on the given element.
 */
$.hasClass = function(el, className) {
	if (!el) { return false; }

	var el = $.id(el);
	var classNames = el.className.split(' ');

	for (var i = 0, len = classNames.length; i < len; ++i) {
		if (classNames[i].trim() === className) {
			return true;
		}
	}

	return false;
};

$.getTag = function(from, tag) { return from.getElementsByTagName(tag); }

$.removeClass = function(el, classNames) {
	if (!el) { return; }
	var el = $.id(el);
	el.className = (' ' + el.className + ' ')
		.replace(' ', '  ')
		.replace(new RegExp('( ' + classNames.replace('\s+', ' | ').replace('-','\-') + ' )', 'g'), ' ')
		.replace(/\s+/, ' ')
		.replace(/^\s+|\s+$/g, '');
}

function ieGetAlpha(el) {
	try {
		return el.filters.item("alpha");
	} catch(e) {}

	try {
		return el.filters.item("progid:DXImageTransform.Microsoft.Alpha");
	} catch(e) {}

	return null;
}

$.style = function(el, style) {
	if(el instanceof Array) {
		for(var i = 0, o; o = el[i]; ++i) { $.style(o, style); }
		return;
	}

	el = $.id(el);
	var s = el.style;
	for(prop in style) {
		switch(prop) {
			case 'styleFloat':
			case 'cssFloat':
			case 'float':
				s.styleFloat = s.cssFloat = style[prop];
				break;
			case 'opacity':
				s.opacity = style[prop];
				if(el.filters) {
					try {
						var alpha = ieGetAlpha();
						var opacity = style[prop] == 1 ? 99.99 : style[prop] * 100;
						if(!alpha) {
							// TODO: this might destroy any existing filters?
							s.filter = "alpha(opacity=" + opacity + ")";
						} else {
							alpha.Opacity = opacity;
						}
					} catch(e) {}
				}
				break;
			case 'borderRadius':
				s.borderRadius = s.MozBorderRadius = style[prop];
				break;
			case 'boxSizing':
				s.MsBoxSizing = s.MozBoxSizing = s.WebkitBoxSizing = style[prop];
			default:
				s[prop] = style[prop];
				break;
		}
	}
};

$.onEvent = function(el, name, f) {
	if (typeof f != 'function') {
		f = bind.apply(GLOBAL, Array.prototype.slice.call(arguments, 2));
	}

	var handler = f;

	el = $.id(el);
	if(el.addEventListener) {
		el.addEventListener(name, handler, false);
	} else {
		handler = function(e) {
			var evt = e || window.event;
			// TODO: normalize the event object
			f(evt);
		};

		el.attachEvent('on' + name, handler);
	}

	return bind($, 'removeEvent', el, name, handler);
};

$.removeEvent = function(el, name, f) {
	el = $.id(el);
	if (el.addEventListener) {
		el.removeEventListener(name, f, false);
	} else {
		el.detachEvent('on' + name, f);
	}
}

$.stopEvent = function(e) {
	if (e) {
		e.cancelBubble = true;
		if(e.stopPropagation) e.stopPropagation();
		if(e.preventDefault) e.preventDefault();
	}
}

$.setText = function(el, text) {
	el = $.id(el);
	text = String(text);
	if ('textContent' in el) {
		el.textContent = text;
	} else if ('innerText' in el) {
		el.innerText = text.replace(/\n/g, ' ');
	} else {
		el.innerHTML = '';
		el.appendChild(document.createTextNode(text));
	}
}

$.setValue = function(el, value) {
	el = $.id(el);
	if ('value' in el) {
		el.value = value;
	} else if ('value' in el.firstChild) {
		el.firstChild.value = value;
	}
};

$.remove = function(el) {
	el = $.id(el);
	if(el && el.parentNode) {
		el.parentNode.removeChild(el);
	}
}

$.cursorPos = function(ev, el) {
	var offset = $.pos(el);
	offset.top = ev.clientY - offset.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
	offset.left = ev.clientX - offset.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft);
	return offset;
}

$.pos = function(el) {
	var parent = el;
	var offset = {top: 0, left: 0};
	while(parent && parent != document.body) {
		offset.left += parent.offsetLeft;
		offset.top += parent.offsetTop;
		while(parent.offsetParent != parent.parentNode) {
			offset.top -= parent.scrollTop; offset.left -= parent.scrollLeft;
			parent = parent.parentNode;
		}
		parent = parent.offsetParent;
	}
	return offset;
}

$.size = function(el) {
	if ($.isElement(el)) {
		return {width: el.offsetWidth, height: el.offsetHeight};
	} else if (el.document) {
		var doc = el.document.documentElement || el.document.body;
		return new math.geom.Rect(
			doc.offsetTop,
			doc.offsetLeft,
			el.innerWidth || (doc.clientWidth || doc.clientWidth),
			el.innerHeight || (doc.clientHeight || doc.clientHeight)
		);
	}
}

$.insertCSSFile = function(filename) {
	document.getElementsByTagName('head')[0].appendChild($({
		tag: 'link',
		attrs: {
			rel: 'stylesheet',
			type: 'text/css',
			href: filename
		}
	}));
}
<|endoftext|>