<commit_before>import {Form, form} from 'widget/form/form'
// import {Menu} from './menu'
import {Menu} from 'widget/menu/menu'
import {activatable} from 'widget/activation/activatable'
import {changeBaseLayer} from './baseLayer'
import {compose} from 'compose'
import {msg} from 'translate'
import {select} from 'store'
import ButtonSelect from 'widget/buttonSelect'
import Labels from './labels'
import PropTypes from 'prop-types'
import React from 'react'
import actionBuilder from 'action-builder'
// import moment from 'moment'
import styles from './layersMenu.module.css'

const fields = {
    // year: new Form.Field(),
    // month: new Form.Field(),
    dateRange: new Form.Field(),
    proc: new Form.Field()
}

const mapStateToProps = (state, ownProps) => ({
    labelsShown: select([ownProps.statePath, 'labelsShown']),
    baseLayer: select([ownProps.statePath, 'baseLayer']),
    mapOverlayIndex: select([ownProps.statePath, 'mapOverlayIndex']),
    featureOverlayIds: select([ownProps.statePath, 'featureOverlayIds']),
    dateRange: select([ownProps.statePath, 'mapLayer.dateRange']),
    proc: select([ownProps.statePath, 'mapLayer.proc'])
    // year: select([ownProps.statePath, 'options.year']),
    // month: select([ownProps.statePath, 'options.month'])
})

class _LayersMenu extends React.Component {
    render() {
        const {
            inputs: {dateRange, proc},
            // inputs: {year, month, proc},
            activatable: {deactivate},
            labelsShown, baseLayer, labelLayerIndex, statePath, mapContext
        } = this.props
        const mapOverlayOptions = this.getMapOverlays().map(layer =>
            <Menu.Option
                key={layer.layerIndex}
                id={layer.layerIndex}
                label={layer.label}
                description={layer.description}/>)
        const featureOverlayOptions = this.getFeatureOverlayIds().map(layer =>
            <Menu.Option
                key={layer.id}
                id={layer.id}
                label={layer.label}
                description={layer.description}/>)
        // const {yearOptions, monthOptions, procOptions} = this.getPlanetDateOptions()
        const {dateRangeOptions, procOptions} = this.getPlanetDateOptions()

        const procOption = procOptions.find(({value}) => proc.value === value)
        const dateRangeOption = dateRangeOptions.find(({value}) => dateRange.value === value)
        // const yearOption = yearOptions.find(({value}) => year.value === value)
        // const monthOption = monthOptions.find(({value}) => month.value === value)
        return (
            <Menu
                position='top-right'
                className={styles.panel}
                close={deactivate}>
                <Menu.Select
                    id={'BASE_LAYER'}
                    label={msg('process.mosaic.mapToolbar.layersMenu.baseLayer')}
                    onSelect={type => this.changeBaseLayer(type, dateRange, proc)}
                    // onSelect={type => this.changeBaseLayer(type, year, month, proc)}
                    selected={baseLayer || 'SEPAL'}>
                    <Menu.Option
                        id={'SEPAL'}
                        label={msg('process.mosaic.mapToolbar.layersMenu.SEPAL.label')}
                        description={msg('process.mosaic.mapToolbar.layersMenu.SEPAL.description')}/>
                    <Menu.Option
                        id={'GOOGLE_SATELLITE'}
                        label={msg('process.mosaic.mapToolbar.layersMenu.GOOGLE_SATELLITE.label')}
                        description={msg('process.mosaic.mapToolbar.layersMenu.GOOGLE_SATELLITE.description')}/>
                    <Menu.Option
                        id={'PLANET'}
                        label={msg('process.mosaic.mapToolbar.layersMenu.PLANET.label')}
                        description={msg('process.mosaic.mapToolbar.layersMenu.PLANET.description')}
                        right={

                                <ButtonSelect
                                    placement='below'
                                    alignment='left'
                                    input={proc}
                                    tooltipPlacement='bottom'
                                    options={procOptions}
                                    label={procOption && procOption.label}
                                    onSelect={proc => this.changeBaseLayer('PLANET', this.props.inputs.dateRange, proc)}
                                    // onSelect={proc => this.changeBaseLayer('PLANET', this.props.inputs.year, this.props.inputs.month, proc)}
                                />
                                <ButtonSelect
                                    placement='below'
                                    alignment='left'
                                    input={dateRange}
                                    tooltipPlacement='bottom'
                                    options={dateRangeOptions}
                                    label={dateRangeOption && dateRangeOption.label}
                                    onSelect={dateRange => this.changeBaseLayer('PLANET', dateRange, this.props.inputs.proc)}
                                />
                                {/*<ButtonSelect*/}
                                {/*    placement='below'*/}
                                {/*    alignment='left'*/}
                                {/*    input={year}*/}
                                {/*    tooltipPlacement='bottom'*/}
                                {/*    options={yearOptions}*/}
                                {/*    label={yearOption && yearOption.label}*/}
                                {/*    onSelect={year => this.changeBaseLayer('PLANET', year, this.props.inputs.month, this.props.inputs.proc)}*/}
                                {/*/>*/}
                                {/*<ButtonSelect*/}
                                {/*    placement='below'*/}
                                {/*    alignment='left'*/}
                                {/*    input={month}*/}
                                {/*    tooltipPlacement='bottom'*/}
                                {/*    options={monthOptions}*/}
                                {/*    label={monthOption && monthOption.label}*/}
                                {/*    onSelect={month => this.changeBaseLayer('PLANET', this.props.inputs.year, month, this.props.inputs.proc)}*/}
                                {/*/>*/}

                        }/>
                </Menu.Select>
                <Menu.Separator/>
                <Menu.Select
                    id={'MAP_OVERLAYS'}
                    label={msg('process.mosaic.mapToolbar.layersMenu.overlay')}
                    onSelect={selectedOverlayIndex => this.toggleMapOverlay(selectedOverlayIndex)}
                    selected={this.selectedMapOverlayIndex()}>
                    {mapOverlayOptions}
                </Menu.Select>
                <Menu.Select
                    id={'FEATURE_OVERLAYS'}
                    onSelect={selectedOverlayId => this.toggleFeatureOverlay(selectedOverlayId)}
                    selected={this.selectedFeatureOverlayIds()}>
                    {featureOverlayOptions}
                </Menu.Select>
                <Menu.Toggle
                    id={'SHOW_LABELS'}
                    label={msg('process.mosaic.mapToolbar.layersMenu.labels.label')}
                    description={msg('process.mosaic.mapToolbar.layersMenu.labels.description')}
                    selected={labelsShown}
                    onChange={shown =>
                        Labels.showLabelsAction({
                            mapContext,
                            shown,
                            layerIndex: labelLayerIndex,
                            statePath
                        }).dispatch()}/>
            </Menu>
        )
    }

    componentDidUpdate() {
        // const {inputs: {year, month, proc}} = this.props
        // if (!year.value)
        // year.set(this.props.year || moment().format('YYYY'))
        // if (!month.value)
        // month.set(this.props.month || moment().subtract(1, 'months').format('MM'))
        // else {
        // const {monthOptions} = this.getPlanetDateOptions()
        // if (!monthOptions.find(({value}) => month.value === value)) {
        //     const monthOption = monthOptions[0]
        //     month.set(monthOption.value)
        //     this.changeBaseLayer('PLANET', year, monthOption, )
        // }
        // }
        const {dateRange: prevDateRange, proc: prevProc, inputs: {dateRange, proc}} = this.props
        if (!proc.value)
            proc.set(prevProc || 'rgb')
        if (!dateRange.value)
            dateRange.set(prevDateRange || '2020-09')
    }

    getPlanetDateOptions() {
        // const {inputs: {year}} = this.props
        // const startDate = moment('2018-08-01')
        // const endDate = moment().subtract(1, 'months')
        //
        // const yearOptions = sequence(startDate.year(), moment().year())
        //     .map(year => ({value: `${year}`, label: `${year}`}))
        //
        // const allMonthOptions = moment.monthsShort()
        //     .map((label, i) => ({value: `${i + 1}`.padStart(2, '0'), label}))
        //
        // const monthOptions = year.value === `${startDate.year()}`
        //     ? allMonthOptions.slice(startDate.month() + 1)
        //     : year.value === `${endDate.year()}`
        //         ? allMonthOptions.slice(0, endDate.month() + 1)
        //         : allMonthOptions
        // return {yearOptions, monthOptions}

        const procOptions = [
            {value: 'rgb', label: 'RGB'},
            {value: 'cir', label: 'CIR'},
        ]
        const dateRangeOptions = [
            {value: '2018-12_2019-05', label: 'Dec 2018 (6 months)'},
            {value: '2019-06_2019-11', label: 'Jun 2019 (6 months)'},
            {value: '2019-12_2020-05', label: 'Dec 2019 (6 months)'},
            {value: '2020-06_2020-08', label: 'Jun 2020 (3 months)'},
            {value: '2020-09', label: 'Sep 2020 (1 month)'},
        ]
        return {procOptions, dateRangeOptions}
    }

    // changeBaseLayer(type, year, month, proc) {
    changeBaseLayer(type, dateRange, proc) {
        const {statePath, mapContext} = this.props
        const planetApiKey = mapContext.norwayPlanetApiKey
        changeBaseLayer({
            type,
            mapContext,
            statePath,
            options: {dateRange: dateRange.value, proc: proc.value, planetApiKey}
            // options: {year: year.value, month: month.value, proc: proc.value, planetApiKey}
        })
    }

    getMapOverlays() {
        const {mapContext: {sepalMap}} = this.props
        return sepalMap.toggleableLayers()
            .filter(({layerIndex}) => layerIndex !== undefined)
    }

    selectedMapOverlayIndex() {
        const {mapOverlayIndex} = this.props
        if (mapOverlayIndex === undefined) {
            const overlays = this.getMapOverlays()
            return overlays.length
                ? overlays.map(layer => layer.layerIndex)[0]
                : -1
        } else {
            return mapOverlayIndex
        }
    }

    toggleMapOverlay = selectedOverlayIndex => {
        const {statePath} = this.props
        const mapOverlays = this.getMapOverlays()

        const prevOverlayIndex = this.selectedMapOverlayIndex()
        if (selectedOverlayIndex !== prevOverlayIndex) {
            const prevOverlay = mapOverlays.find(layer => layer.layerIndex === prevOverlayIndex)
            prevOverlay && prevOverlay.hide(true)
        }

        const selectedOverlay = mapOverlays.find(layer => layer.layerIndex === selectedOverlayIndex)
        const hide = prevOverlayIndex === selectedOverlayIndex
        selectedOverlay && selectedOverlay.hide(hide)
        const nextOverlayIndex = hide ? -1 : selectedOverlayIndex

        actionBuilder('SET_MAP_OVERLAY', {nextOverlayIndex})
            .set([statePath, 'mapOverlayIndex'], nextOverlayIndex)
            .build()
            .dispatch()
    }

    getFeatureOverlayIds() {
        const {mapContext: {sepalMap}} = this.props
        return sepalMap.toggleableLayers()
            .filter(({layerIndex}) => layerIndex === undefined)
    }

    selectedFeatureOverlayIds() {
        const {featureOverlayIds} = this.props
        if (featureOverlayIds === undefined) {
            const overlays = this.getFeatureOverlayIds()
            return overlays.map(layer => layer.id)
        } else {
            return featureOverlayIds
        }
    }

    toggleFeatureOverlay = selectedOverlayId => {
        const {statePath} = this.props
        const featureOverlays = this.getFeatureOverlayIds()
        const prevOverlayIds = this.selectedFeatureOverlayIds()
        const alreadySelected = prevOverlayIds.includes(selectedOverlayId)
        const overlay = featureOverlays.find(layer => layer.id === selectedOverlayId)
        overlay && overlay.hide(alreadySelected)
        const nextOverlayIds = alreadySelected
            ? prevOverlayIds.filter(id => id !== selectedOverlayId)
            : [...prevOverlayIds, selectedOverlayId]
        actionBuilder('SET_FEATURE_OVERLAYS', {nextOverlayIds})
            .set([statePath, 'featureOverlayIds'], nextOverlayIds)
            .build()
            .dispatch()
    }
}

const policy = () => ({
    _: 'allow'
})

export const LayersMenu = compose(
    _LayersMenu,
    form({fields, mapStateToProps}),
    activatable({id: 'layersMenu', policy})
)

// const sequence = (start, end, step = 1) =>
//     Array.apply(null, {length: Math.floor((end - start) / step) + 1})
//         .map((_, i) => i * step + start)

LayersMenu.propTypes = {
    labelLayerIndex: PropTypes.any.isRequired,
    mapContext: PropTypes.object.isRequired,
    statePath: PropTypes.any.isRequired
}
<commit_msg>Dynamically added monthly Planet options to layers menu.<commit_after>import {Form, form} from 'widget/form/form'
import {Menu} from 'widget/menu/menu'
import {activatable} from 'widget/activation/activatable'
import {changeBaseLayer} from './baseLayer'
import {compose} from 'compose'
import {msg} from 'translate'
import {select} from 'store'
import ButtonSelect from 'widget/buttonSelect'
import Labels from './labels'
import PropTypes from 'prop-types'
import React from 'react'
import actionBuilder from 'action-builder'
import moment from 'moment'
import styles from './layersMenu.module.css'

const fields = {
    dateRange: new Form.Field(),
    proc: new Form.Field()
}

const mapStateToProps = (state, ownProps) => ({
    labelsShown: select([ownProps.statePath, 'labelsShown']),
    baseLayer: select([ownProps.statePath, 'baseLayer']),
    mapOverlayIndex: select([ownProps.statePath, 'mapOverlayIndex']),
    featureOverlayIds: select([ownProps.statePath, 'featureOverlayIds']),
    dateRange: select([ownProps.statePath, 'mapLayer.dateRange']),
    proc: select([ownProps.statePath, 'mapLayer.proc'])
})

class _LayersMenu extends React.Component {
    render() {
        const {
            inputs: {dateRange, proc},
            activatable: {deactivate},
            labelsShown, baseLayer, labelLayerIndex, statePath, mapContext
        } = this.props
        const mapOverlayOptions = this.getMapOverlays().map(layer =>
            <Menu.Option
                key={layer.layerIndex}
                id={layer.layerIndex}
                label={layer.label}
                description={layer.description}/>)
        const featureOverlayOptions = this.getFeatureOverlayIds().map(layer =>
            <Menu.Option
                key={layer.id}
                id={layer.id}
                label={layer.label}
                description={layer.description}/>)
        const {dateRangeOptions, procOptions} = this.getPlanetDateOptions()

        const procOption = procOptions.find(({value}) => proc.value === value)
        const dateRangeOption = dateRangeOptions.find(({value}) => dateRange.value === value)
        return (
            <Menu
                position='top-right'
                className={styles.panel}
                close={deactivate}>
                <Menu.Select
                    id={'BASE_LAYER'}
                    label={msg('process.mosaic.mapToolbar.layersMenu.baseLayer')}
                    onSelect={type => this.changeBaseLayer(type, dateRange, proc)}
                    // onSelect={type => this.changeBaseLayer(type, year, month, proc)}
                    selected={baseLayer || 'SEPAL'}>
                    <Menu.Option
                        id={'SEPAL'}
                        label={msg('process.mosaic.mapToolbar.layersMenu.SEPAL.label')}
                        description={msg('process.mosaic.mapToolbar.layersMenu.SEPAL.description')}/>
                    <Menu.Option
                        id={'GOOGLE_SATELLITE'}
                        label={msg('process.mosaic.mapToolbar.layersMenu.GOOGLE_SATELLITE.label')}
                        description={msg('process.mosaic.mapToolbar.layersMenu.GOOGLE_SATELLITE.description')}/>
                    <Menu.Option
                        id={'PLANET'}
                        label={msg('process.mosaic.mapToolbar.layersMenu.PLANET.label')}
                        description={msg('process.mosaic.mapToolbar.layersMenu.PLANET.description')}
                        right={

                                <ButtonSelect
                                    placement='below'
                                    alignment='left'
                                    input={proc}
                                    tooltipPlacement='bottom'
                                    options={procOptions}
                                    label={procOption && procOption.label}
                                    onSelect={proc => this.changeBaseLayer('PLANET', this.props.inputs.dateRange, proc)}
                                />
                                <ButtonSelect
                                    placement='below'
                                    alignment='left'
                                    input={dateRange}
                                    tooltipPlacement='bottom'
                                    options={dateRangeOptions}
                                    label={dateRangeOption && dateRangeOption.label}
                                    onSelect={dateRange => this.changeBaseLayer('PLANET', dateRange, this.props.inputs.proc)}
                                />

                        }/>
                </Menu.Select>
                <Menu.Separator/>
                <Menu.Select
                    id={'MAP_OVERLAYS'}
                    label={msg('process.mosaic.mapToolbar.layersMenu.overlay')}
                    onSelect={selectedOverlayIndex => this.toggleMapOverlay(selectedOverlayIndex)}
                    selected={this.selectedMapOverlayIndex()}>
                    {mapOverlayOptions}
                </Menu.Select>
                <Menu.Select
                    id={'FEATURE_OVERLAYS'}
                    onSelect={selectedOverlayId => this.toggleFeatureOverlay(selectedOverlayId)}
                    selected={this.selectedFeatureOverlayIds()}>
                    {featureOverlayOptions}
                </Menu.Select>
                <Menu.Toggle
                    id={'SHOW_LABELS'}
                    label={msg('process.mosaic.mapToolbar.layersMenu.labels.label')}
                    description={msg('process.mosaic.mapToolbar.layersMenu.labels.description')}
                    selected={labelsShown}
                    onChange={shown =>
                        Labels.showLabelsAction({
                            mapContext,
                            shown,
                            layerIndex: labelLayerIndex,
                            statePath
                        }).dispatch()}/>
            </Menu>
        )
    }

    componentDidUpdate() {
        const {dateRange: prevDateRange, proc: prevProc, inputs: {dateRange, proc}} = this.props
        if (!proc.value)
            proc.set(prevProc || 'rgb')
        if (!dateRange.value)
            dateRange.set(prevDateRange || moment().subtract(2, 'months').format('YYYY-MM'))
    }

    getPlanetDateOptions() {
        const startDate = moment('2020-09-01')
        const endDate = moment().subtract(1, 'months')
        const months = endDate.diff(startDate, 'months')
        const monthlyOptions = sequence(0, months).map(monthDelta => {
            const date = moment(startDate).add(monthDelta, 'months')
            return {
                value: date.format('YYYY-MM'),
                label: `${date.format('MMM YYYY')} (1 month)`
            }
        })

        const procOptions = [
            {value: 'rgb', label: 'RGB'},
            {value: 'cir', label: 'CIR'},
        ]
        const dateRangeOptions = [
            {value: '2018-12_2019-05', label: 'Dec 2018 (6 months)'},
            {value: '2019-06_2019-11', label: 'Jun 2019 (6 months)'},
            {value: '2019-12_2020-05', label: 'Dec 2019 (6 months)'},
            {value: '2020-06_2020-08', label: 'Jun 2020 (3 months)'},
            ...monthlyOptions
        ]
        return {procOptions, dateRangeOptions}
    }

    changeBaseLayer(type, dateRange, proc) {
        const {statePath, mapContext} = this.props
        const planetApiKey = mapContext.norwayPlanetApiKey
        changeBaseLayer({
            type,
            mapContext,
            statePath,
            options: {dateRange: dateRange.value, proc: proc.value, planetApiKey}
        })
    }

    getMapOverlays() {
        const {mapContext: {sepalMap}} = this.props
        return sepalMap.toggleableLayers()
            .filter(({layerIndex}) => layerIndex !== undefined)
    }

    selectedMapOverlayIndex() {
        const {mapOverlayIndex} = this.props
        if (mapOverlayIndex === undefined) {
            const overlays = this.getMapOverlays()
            return overlays.length
                ? overlays.map(layer => layer.layerIndex)[0]
                : -1
        } else {
            return mapOverlayIndex
        }
    }

    toggleMapOverlay = selectedOverlayIndex => {
        const {statePath} = this.props
        const mapOverlays = this.getMapOverlays()

        const prevOverlayIndex = this.selectedMapOverlayIndex()
        if (selectedOverlayIndex !== prevOverlayIndex) {
            const prevOverlay = mapOverlays.find(layer => layer.layerIndex === prevOverlayIndex)
            prevOverlay && prevOverlay.hide(true)
        }

        const selectedOverlay = mapOverlays.find(layer => layer.layerIndex === selectedOverlayIndex)
        const hide = prevOverlayIndex === selectedOverlayIndex
        selectedOverlay && selectedOverlay.hide(hide)
        const nextOverlayIndex = hide ? -1 : selectedOverlayIndex

        actionBuilder('SET_MAP_OVERLAY', {nextOverlayIndex})
            .set([statePath, 'mapOverlayIndex'], nextOverlayIndex)
            .build()
            .dispatch()
    }

    getFeatureOverlayIds() {
        const {mapContext: {sepalMap}} = this.props
        return sepalMap.toggleableLayers()
            .filter(({layerIndex}) => layerIndex === undefined)
    }

    selectedFeatureOverlayIds() {
        const {featureOverlayIds} = this.props
        if (featureOverlayIds === undefined) {
            const overlays = this.getFeatureOverlayIds()
            return overlays.map(layer => layer.id)
        } else {
            return featureOverlayIds
        }
    }

    toggleFeatureOverlay = selectedOverlayId => {
        const {statePath} = this.props
        const featureOverlays = this.getFeatureOverlayIds()
        const prevOverlayIds = this.selectedFeatureOverlayIds()
        const alreadySelected = prevOverlayIds.includes(selectedOverlayId)
        const overlay = featureOverlays.find(layer => layer.id === selectedOverlayId)
        overlay && overlay.hide(alreadySelected)
        const nextOverlayIds = alreadySelected
            ? prevOverlayIds.filter(id => id !== selectedOverlayId)
            : [...prevOverlayIds, selectedOverlayId]
        actionBuilder('SET_FEATURE_OVERLAYS', {nextOverlayIds})
            .set([statePath, 'featureOverlayIds'], nextOverlayIds)
            .build()
            .dispatch()
    }
}

const policy = () => ({
    _: 'allow'
})

export const LayersMenu = compose(
    _LayersMenu,
    form({fields, mapStateToProps}),
    activatable({id: 'layersMenu', policy})
)

const sequence = (start, end, step = 1) =>
    Array.apply(null, {length: Math.floor((end - start) / step) + 1})
        .map((_, i) => i * step + start)

LayersMenu.propTypes = {
    labelLayerIndex: PropTypes.any.isRequired,
    mapContext: PropTypes.object.isRequired,
    statePath: PropTypes.any.isRequired
}
<|endoftext|>


<commit_before>/**
 * GeoKnow Generator
 *    Configuration management
 *
 * @author Vadim Zaslawski
 *
 * ISQL:
 *   GRANT SPARQL_UPDATE TO "SPARQL"
 *   GRANT EXECUTE ON DB.DBA.L_O_LOOK TO "SPARQL"
 *
 * usage:
 *   CONFIG.setEndpoint(url)          - set SPARQL endpoint, should be called initially
 *   CONFIG.getEndpoint()             - get SPARQL endpoint
 *   CONFIG.getNS()                   - get base namespace
 *   CONFIG.getGraph()                - get graph name
 *   CONFIG.read([success(settings)]) - load settings
 *   CONFIG.getSettings()             - get loaded settings
 *   CONFIG.write()                   - save settings after editing CONFIG.getSettings() result
 *   CONFIG.select(property, value)   - select settings, e.g.: CONFIG.select("rdf:type", "lds:StackComponent")
 *   CONFIG.createGraph(name)         - create graph
 *   CONFIG.dropGraph(name)           - delete graph
 */

"use strict";

var CONFIG = CONFIG || (function()
{
	var endpoint  = "http://144.76.166.111:8890/sparql"
	,	NS        = "http://generator.geoknow.eu/"
	,	GRAPH_URI = NS + "settingsGraph";

	var namespaces =
	{
		"http://dbpedia.org/resource/"                     : "dbpedia:"
	,	"http://purl.org/dc/elements/1.1/"                 : "dc:"
	,	"http://purl.org/dc/terms/"                        : "dcterms:"
	,	"http://xmlns.com/foaf/0.1/"                       : "foaf:"
	,	"http://linkeddata.org/integrated-stack-schema/"   : "lds:"
	,	"http://www.w3.org/1999/02/22-rdf-syntax-ns#"      : "rdf:"
	,	"http://www.w3.org/2000/01/rdf-schema#"            : "rdfs:"
	,	"http://www.w3.org/ns/sparql-service-description#" : "sd:"
	,	"http://rdfs.org/ns/void#"                         : "void:"
	};
	namespaces[NS] = ":";

	var GRAPH      = "<" + GRAPH_URI + ">"
	,	FORMAT     = "application/sparql-results+json"
	,	EOL        = "\r\n"
	,	NAMESPACES = "";

	for (var namespace in namespaces)
		NAMESPACES += "PREFIX " + namespaces[namespace] + " <" + namespace + ">" + EOL;

	var settings = {};

	var isLoaded = false;

	var ns = function(v)
	{
		var value = v.value || v;

		if (!v.type || v.type == "uri")
		{
			var namespace = /.*[#\/]/.exec(value);
			if (namespace)
			{
				var prefix = namespaces[namespace = namespace[0]];
				if (prefix)
					return prefix + value.slice(namespace.length);
			}
		}

		return value;
	}

	return {
		setEndpoint: function(url)
		{
			endpoint = url;
		}
	,
		getEndpoint: function()
		{
			return endpoint;
		}

	,	getNS: function()
		{
			return NS;
		}

	,	getGraph: function()
		{
			return GRAPH;
		}

	,	getSettings: function()
		{
			return settings;
		}

	,	select: function(property, value)
		{
			property = ns(property);
			value    = ns(value);

			var elements = {};

			for (var resource in settings)
			{
				var element = settings[resource];
				var prop = element[property];
				if (prop)
					for (var i in prop)
						if (prop[i] == value)
						{
							elements[resource] = element;
							break;
						}
			}

			return elements;
		}

	,	read: function(success)
		{
			if (isLoaded)
			{
				if (success)
					try
					{
						success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				return;
			}

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "SELECT * FROM " + GRAPH + EOL
				+	"WHERE { ?s ?p ?o }" + EOL
				+	"ORDER BY ?s ?p ?o"
				}
			,	function(data)
				{
					try
					{
						var bindings = data.results.bindings
						,	triples  = [];

						for (var i in bindings)
						{
							var binding = bindings[i];
							triples.push([ ns(binding.s), ns(binding.p), ns(binding.o) ]);
						}

						settings = {};

						var bnodes = {};

						for (var i in triples)
						{
							var triple = triples[i]
							,	s = triple[0]
							,	p = triple[1]
							,	o = triple[2];

							if (/^nodeID:\/\//.test(s))
							{
								var id = s.slice(9);
								var map = bnodes[id] = bnodes[id] || {};
							}
							else
							{
								var map = settings[s] || (settings[s] = {});

								if (/^nodeID:\/\//.test(o))
								{
									var id = o.slice(9);
									o = bnodes[id] = bnodes[id] || {};
								}
							}

							(map[p] || (map[p] = [])).push(o);
						}

						isLoaded = true;

						if (success)
							success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	write: function()
		{
			var wrap = function(s)
			{
				return /^http:\/\//.test(s) ? "<" + s + ">" : !/^\w*:/.test(s) ? '"' + s + '"' : s;
			}

			var data = "",
				bnodeIndex = 0;

			var walk = function(s, map)
			{
				for (var p in map)
				{
					var arr = map[p];
					for (var i in arr)
					{
						var o = arr[i];
						if (typeof o === "string")
							data += wrap(s) + " " + wrap(p) + " " + wrap(o) + " ." + EOL;
						else
						{
							var bnode = "_:b" + ++bnodeIndex;
							data += wrap(s) + " " + wrap(p) + " " + bnode + " ." + EOL;
							walk(bnode, o);
						}
					}
				}
			}

			for (var s in settings)
				walk(s, settings[s]);

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: NAMESPACES
					+	"DROP SILENT GRAPH "   + GRAPH + EOL
					+	"CREATE SILENT GRAPH " + GRAPH + EOL
					+	"INSERT INTO "         + GRAPH + EOL
					+	"{" + EOL
					+	data
					+	"}"
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	createGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "CREATE SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	dropGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "DROP SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}
	};
})();
<commit_msg>Configuration management updated.<commit_after>/**
 * GeoKnow Generator
 *    Configuration management
 *
 * @author Vadim Zaslawski
 *
 * enable SPARQL Update
 * ISQL:
 *   GRANT SPARQL_UPDATE TO "SPARQL"
 *   GRANT EXECUTE ON DB.DBA.L_O_LOOK TO "SPARQL"
 *
 * enable CORS
 *
 * usage:
 *   CONFIG.setEndpoint(url)          - set SPARQL endpoint, should be called initially
 *   CONFIG.getEndpoint()             - get SPARQL endpoint
 *   CONFIG.getNS()                   - get base namespace
 *   CONFIG.getGraph()                - get graph name
 *   CONFIG.read([success(settings)]) - load settings
 *   CONFIG.getSettings()             - get loaded settings
 *   CONFIG.write()                   - save settings after editing CONFIG.getSettings() result
 *   CONFIG.select(property, value)   - select settings, e.g.: CONFIG.select("rdf:type", "lds:StackComponent")
 *   CONFIG.createGraph(name)         - create graph
 *   CONFIG.dropGraph(name)           - delete graph
 */

"use strict";

var CONFIG = CONFIG || (function()
{
	var endpoint  = "http://144.76.166.111:8890/sparql"
	,	NS        = "http://generator.geoknow.eu/"
	,	GRAPH_URI = NS + "settingsGraph";

	var namespaces =
	{
		"http://dbpedia.org/resource/"                     : "dbpedia:"
	,	"http://purl.org/dc/elements/1.1/"                 : "dc:"
	,	"http://purl.org/dc/terms/"                        : "dcterms:"
	,	"http://xmlns.com/foaf/0.1/"                       : "foaf:"
	,	"http://linkeddata.org/integrated-stack-schema/"   : "lds:"
	,	"http://www.w3.org/1999/02/22-rdf-syntax-ns#"      : "rdf:"
	,	"http://www.w3.org/2000/01/rdf-schema#"            : "rdfs:"
	,	"http://www.w3.org/ns/sparql-service-description#" : "sd:"
	,	"http://rdfs.org/ns/void#"                         : "void:"
	};
	namespaces[NS] = ":";

	var GRAPH      = "<" + GRAPH_URI + ">"
	,	FORMAT     = "application/sparql-results+json"
	,	EOL        = "\r\n";

	var NAMESPACES = "";
	for (var namespace in namespaces)
		NAMESPACES += "PREFIX " + namespaces[namespace] + " <" + namespace + ">" + EOL;

	var settings = {};

	var isLoaded = false;

	var ns = function(v)
	{
		var value = v.value || v;

		if (!v.type || v.type == "uri")
		{
			var namespace = /.*[#\/]/.exec(value);
			if (namespace)
			{
				var prefix = namespaces[namespace = namespace[0]];
				if (prefix)
					return prefix + value.slice(namespace.length);
			}
		}

		return value;
	}

	return {
		setEndpoint: function(url)
		{
			endpoint = url;
		}
	,
		getEndpoint: function()
		{
			return endpoint;
		}

	,	getNS: function()
		{
			return NS;
		}

	,	getGraph: function()
		{
			return GRAPH;
		}

	,	getSettings: function()
		{
			return settings;
		}

	,	select: function(property, value)
		{
			property = ns(property);
			value    = ns(value);

			var elements = {};

			for (var resource in settings)
			{
				var element = settings[resource];
				var prop = element[property];
				if (prop)
					for (var i in prop)
						if (prop[i] == value)
						{
							elements[resource] = element;
							break;
						}
			}

			return elements;
		}

	,	read: function(success)
		{
			if (isLoaded)
			{
				if (success)
					try
					{
						success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				return;
			}

			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "SELECT * FROM " + GRAPH + EOL
				+	"WHERE { ?s ?p ?o }" + EOL
				+	"ORDER BY ?s ?p ?o"
				}
			,	function(data)
				{
					try
					{
						var bindings = data.results.bindings
						,	triples  = [];

						for (var i in bindings)
						{
							var binding = bindings[i];
							triples.push([ ns(binding.s), ns(binding.p), ns(binding.o) ]);
						}

						settings = {};

						var bnodes = {};

						for (var i in triples)
						{
							var triple = triples[i]
							,	s = triple[0]
							,	p = triple[1]
							,	o = triple[2];

							if (/^nodeID:\/\//.test(s))
							{
								var id = s.slice(9);
								var map = bnodes[id] = bnodes[id] || {};
							}
							else
							{
								var map = settings[s] || (settings[s] = {});

								if (/^nodeID:\/\//.test(o))
								{
									var id = o.slice(9);
									o = bnodes[id] = bnodes[id] || {};
								}
							}

							(map[p] || (map[p] = [])).push(o);
						}

						isLoaded = true;

						if (success)
							success(settings);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	write: function()
		{
			var wrap = function(s)
			{
				return /^http:\/\//.test(s) ? "<" + s + ">" : !/^\w*:/.test(s) ? '"' + s + '"' : s;
			}

			var data = "",
				bnodeIndex = 0;

			var walk = function(s, map)
			{
				for (var p in map)
				{
					var arr = map[p];
					for (var i in arr)
					{
						var o = arr[i];
						if (typeof o === "string")
							data += wrap(s) + " " + wrap(p) + " " + wrap(o) + " ." + EOL;
						else
						{
							var bnode = "_:b" + ++bnodeIndex;
							data += wrap(s) + " " + wrap(p) + " " + bnode + " ." + EOL;
							walk(bnode, o);
						}
					}
				}
			}

			for (var s in settings)
				walk(s, settings[s]);

			$.post(endpoint
			,	{
					format: FORMAT
				,	query: NAMESPACES
					+	"DROP SILENT GRAPH "   + GRAPH + EOL
					+	"CREATE SILENT GRAPH " + GRAPH + EOL
					+	"INSERT INTO "         + GRAPH + EOL
					+	"{" + EOL
					+	data
					+	"}"
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			,	"json"
			);
		}

	,	createGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "CREATE SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}

	,	dropGraph: function(name)
		{
			$.getJSON(endpoint + "?callback=?",
				{
					format: FORMAT
				,	query: "DROP SILENT GRAPH " + name
				}
			,	function(data)
				{
					try
					{
						console.log(data.results.bindings[0]["callret-0"].value);
					}
					catch (e)
					{
						console.error(e);
					}
				}
			);
		}
	};
})();
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Global Biodiversity Information Facility (GBIF)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
$(function () {

  $('.seeAllFacet').each(function () {
    $("a.seeAllLink", this).bindDialogPopover($("div.dialogPopover", this));
  });

  var facetbox = $.url(window.location).param("facetbox");
  if (facetbox !== undefined) {
    $("#facetfilter" + facetbox + "  a.seeAllLink").trigger("click");
  };

  $('#resetFacetsButton').click(function (event) {
    $('.facet input:checkbox').each(function () {
      this.checked = false
    });
    $('#formSearch input:hidden').remove();
    $('#resetFacets input.defaultFacet').appendTo($('#formSearch'));
    $('#formSearch').submit();
    showWaitDialog();
  });

  // toggle a facet box
  $('.facet ul li:not([class])').each(function () {
    var thisLi = this;
    $('a', thisLi).click(function (event) {
      event.preventDefault();
      // a facet link is equivalent to toggling the box
      var $checkbox = $('input', thisLi);
      $checkbox.attr('checked', !$checkbox.attr('checked'));
      $checkbox.click();
    });
    $('input', thisLi).click(function (event) {
      // first lock all other facets so we dont get into concurrency problems
      $('.facet input:checkbox').each(function () {
        $(this).attr('disabled', 'true');
      });
      if (this.checked) {
        addFacet(this.value);
      } else {
        removeFacet(this.value);
      }
    })
  });

  $('.facetFilter').each(function () {
    var span = $("span.flabel", this);
    var facetFilter = span.text().toLowerCase();
    var facetValue = span.attr("val");
    $("a", this).click(function (event) {
      event.preventDefault();
      removeFacet(facetFilter, facetValue);
    });
  });

  // facetParam is the full query parameter e.g. rank=species
  function addFacet(facetParam) {
    var queryParams = currentQueryParams();
    queryParams.push(facetParam);
    changeLocation(queryParams.unique());
  }

  // facetParam is the full query parameter e.g. rank=species
  function removeFacet(facetParam) {
    var queryParams = currentQueryParams().unique();
    var idx = $.inArray(facetParam, queryParams);
    if (idx >= 0) {
      queryParams.splice(idx, 1);
    }
    changeLocation(queryParams);
  }

  function changeLocation(queryParams) {
    showWaitDialog();
    window.location.replace(window.location.pathname + '?' + queryParams.join('&'));
  }

  function showWaitDialog() {
    $('#waitDialog').css("top", getTopPosition($('#waitDialog')) + "px");
    $('#waitDialog').fadeIn("medium", function () {
      hidden = false;
    });
    $("body").append("

");
    $("#lock_screen").height($(document).height());
    $("#lock_screen").fadeIn("slow");
  }

  function getTopPosition(div) {
    return (( $(window).height() - div.height()) / 2) + $(window).scrollTop() - 50;
  }

  function currentQueryParams() {
    // get the pairs of params fist
    var pairs = unescape(location.search.substring(1)).split('&');
    var values = [];
    // now iterate each pair
    for (var i = 0; i < pairs.length; i++) {
      var params = pairs[i].split('=');
      if (params[0].indexOf("limit") > -1 && params[0].indexOf("offset") > -1) {
        values.push(pairs[i]);
      }
    }
    return values;
  };
})
<commit_msg>wrong filtering of facet parameters fixed<commit_after>/*
 * Copyright 2011 Global Biodiversity Information Facility (GBIF)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
$(function () {

  $('.seeAllFacet').each(function () {
    $("a.seeAllLink", this).bindDialogPopover($("div.dialogPopover", this));
  });

  var facetbox = $.url(window.location).param("facetbox");
  if (facetbox !== undefined) {
    $("#facetfilter" + facetbox + "  a.seeAllLink").trigger("click");
  };

  $('#resetFacetsButton').click(function (event) {
    $('.facet input:checkbox').each(function () {
      this.checked = false;
    });
    $('#formSearch input:hidden').remove();
    $('#resetFacets input.defaultFacet').appendTo($('#formSearch'));
    $('#formSearch').submit();
    showWaitDialog();
  });

  // toggle a facet box
  $('.facet ul li:not([class])').each(function () {
    var thisLi = this;
    $('a', thisLi).click(function (event) {
      event.preventDefault();
      // a facet link is equivalent to toggling the box
      var $checkbox = $('input', thisLi);
      $checkbox.attr('checked', !$checkbox.attr('checked'));
      $checkbox.click();
    });
    $('input', thisLi).click(function (event) {
      // first lock all other facets so we dont get into concurrency problems
      $('.facet input:checkbox').each(function () {
        $(this).attr('disabled', 'true');
      });
      if (this.checked) {
        addFacet(this.value);
      } else {
        removeFacet(this.value);
      }
    })
  });

  $('.facetFilter').each(function () {
    var span = $("span.flabel", this);
    var facetFilter = span.text().toLowerCase();
    var facetValue = span.attr("val");
    $("a", this).click(function (event) {
      event.preventDefault();
      removeFacet(facetFilter, facetValue);
    });
  });

  // facetParam is the full query parameter e.g. rank=species
  function addFacet(facetParam) {
    var queryParams = currentQueryParams();
    queryParams.push(facetParam);
    changeLocation(queryParams.unique());
  }

  // facetParam is the full query parameter e.g. rank=species
  function removeFacet(facetParam) {
    var queryParams = currentQueryParams().unique();
    var idx = $.inArray(facetParam, queryParams);
    if (idx >= 0) {
      queryParams.splice(idx, 1);
    }
    changeLocation(queryParams);
  }

  function changeLocation(queryParams) {
    showWaitDialog();
    window.location.replace(window.location.pathname + '?' + queryParams.join('&'));
  }

  function showWaitDialog() {
    $('#waitDialog').css("top", getTopPosition($('#waitDialog')) + "px");
    $('#waitDialog').fadeIn("medium", function () {
      hidden = false;
    });
    $("body").append("

");
    $("#lock_screen").height($(document).height());
    $("#lock_screen").fadeIn("slow");
  }

  function getTopPosition(div) {
    return (( $(window).height() - div.height()) / 2) + $(window).scrollTop() - 50;
  }

  function currentQueryParams() {
    // get the pairs of params fist
    var pairs = unescape(location.search.substring(1)).split('&');
    var values = [];
    // now iterate each pair
    for (var i = 0; i < pairs.length; i++) {
      var params = pairs[i].split('=');
      if (params[0].indexOf("limit") == -1 && params[0].indexOf("offset") == -1) {
        values.push(pairs[i]);
      }
    }
    return values;
  };
})
<|endoftext|>


<commit_before>'use strict';

retrospective.controller('RetroCtrl',
    function RetroCtrl($scope, $routeParams, retroService) {
        var retroId = $routeParams["id"];
        $scope.type = "START";
        $scope.description = "";
        $scope.retro = {};

        retroService.setUrl("retrospectiveWS/"+retroId);
        retroService.service.connect();

        retroService.service.subscribe(function(response) {
            $scope.retro = response;
            $scope.$apply();
        });

        $scope.submitForm = function() {
            if ($scope.inputForm.$valid) {
                var input = {description : $scope.description, type : $scope.type, votes : 0};
                if($scope.retro.inputs === undefined){
                    $scope.retro.inputs = [];
                }
                $scope.retro.inputs.push(input);
                retroService.addInput(retroId, input).then(function(){
                    $scope.description = "";
                    $scope.type = "START";
                });
            }
        };

        $scope.remove = function(input){
            var index = getIndex(input);
            $scope.retro.inputs.splice(index,1);
            retroService.removeInput(retroId, $scope.retro.inputs.indexOf(input));
        };

        $scope.addVote = function(input){
            var index = getIndex(input);
            $scope.retro.inputs[index].votes += 1;
            retroService.addVote(retroId, index);
        }

        $scope.save = function(){
            retroService.add($scope.retro);
            $scope.editCancel();
        }

        $scope.editCancel = function(){
            $(".edit").toggle();
        }

        function getIndex(input){
            return $scope.retro.inputs.indexOf(input);
        }

    }
);<commit_msg>minor fix deleting input<commit_after>'use strict';

retrospective.controller('RetroCtrl',
    function RetroCtrl($scope, $routeParams, retroService) {
        var retroId = $routeParams["id"];
        $scope.type = "START";
        $scope.description = "";
        $scope.retro = {};

        retroService.setUrl("retrospectiveWS/"+retroId);
        retroService.service.connect();

        retroService.service.subscribe(function(response) {
            $scope.retro = response;
            $scope.$apply();
        });

        $scope.submitForm = function() {
            if ($scope.inputForm.$valid) {
                var input = {description : $scope.description, type : $scope.type, votes : 0};
                if($scope.retro.inputs === undefined){
                    $scope.retro.inputs = [];
                }
                $scope.retro.inputs.push(input);
                retroService.addInput(retroId, input).then(function(){
                    $scope.description = "";
                    $scope.type = "START";
                });
            }
        };

        $scope.remove = function(input){
            var index = getIndex(input);
            $scope.retro.inputs.splice(index,1);
            retroService.removeInput(retroId, index);
        };

        $scope.addVote = function(input){
            var index = getIndex(input);
            $scope.retro.inputs[index].votes += 1;
            retroService.addVote(retroId, index);
        }

        $scope.save = function(){
            retroService.add($scope.retro);
            $scope.editCancel();
        }

        $scope.editCancel = function(){
            $(".edit").toggle();
        }

        function getIndex(input){
            return $scope.retro.inputs.indexOf(input);
        }

    }
);<|endoftext|>


<commit_before>/**
 * Breeze.js
 *
 * The purpose of this file is to handle all the client side code, the ajax call for the status, comments and other stuff
 * @package Breeze mod
 * @version 1.0 Beta 3
 * @author Jessica Gonzlez <missallsunday@simplemachines.org>
 * @copyright Copyright (c) 2012, Jessica Gonzlez
 * @license http://www.mozilla.org/MPL/MPL-1.1.html
 */

/*
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is http://missallsunday.com code.
 *
 * The Initial Developer of the Original Code is
 * Jessica Gonzlez.
 * Portions created by the Initial Developer are Copyright (c) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 */

/* The status stuff goes right here... */
	jQuery(document).ready(function()
	{
		jQuery('.status_button').livequery(function()
		{
			jQuery(this).click(function()
			{
				var test = jQuery('#content').val();
				var ownerID = jQuery('#owner_id').val();
				var posterID = jQuery('#poster_id').val();
				var loadImage = '
 ' + ajax_notification_text + '';

				/* Disable the button to prevent multiple clicks -_- */
				jQuery(this).attr('disabled', 'disabled');

				if(test=='')
				{
					alert(breeze_empty_message);

					/* Enable the button again... */
					jQuery('.status_button').removeAttr('disabled');
				}

				/* Shhh! */
				else if(test== 'about:breeze')
				{
					alert('Y es que tengo un coraz\xF3n t\xE1n necio \n que no comprende que no entiende \n que le hace da\xF1o amarte tanto \n no comprende que lo haz olvidado \n sigue aferrado a tu recuerdo y a tu amor \n Y es que tengo un coraz\xF3n t\xE1n necio \n que vive preso a las caricias de tus lindas manos \n al dulce beso de tus labios \n y aunque le hace da\xF1o \n te sigue amando igual o mucho m\xE1s que ayer \n mucho m\xE1s que ayer... \n');

					/* Enable the button again... */
					jQuery('.status_button').removeAttr('disabled');
				}

				else
				{
					jQuery('#breeze_load_image').fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=post',
						data: ({content : test, owner_id : ownerID, poster_id : posterID}),
						cache: false,
						dataType: 'json',
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									document.getElementById('content').value='';
									document.getElementById('content').focus();

									jQuery('#breeze_display_status').prepend(html.data);

									jQuery('#breeze_display_status').fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');

							/*
							 * Something happen while sending the request
							 *
							 * @todo identify the different errors and show more info about it to the forum admin
							 */
							jQuery('#breeze_load_image').slideUp('slow', 'linear', function(){
								showNotification(
								{
									message: breeze_error_message,
									type: 'error',
									autoClose: true,
									duration: 3
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

/* Handle the comments */
	jQuery(document).ready(function()
	{
		jQuery('.comment_submit').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var Id = element.attr('id');
				var commentBox = jQuery('#textboxcontent_'+Id).val();
				var loadcommentImage = ' ' + ajax_notification_text + '';
				var status_owner_id = jQuery('#status_owner_id'+Id).val();
				var poster_comment_id = jQuery('#poster_comment_id'+Id).val();
				var profile_owner_id = jQuery('#profile_owner_id'+Id).val();
				var status_id = jQuery('#status_id'+Id).val();
				var loadImage = '
 ' + ajax_notification_text + '';

				if(commentBox=='')
					alert(breeze_empty_message);

				else
				{
					jQuery('#breeze_load_image_comment_'+Id).fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=postcomment',
						data: ({content : commentBox, status_owner_id : status_owner_id, poster_comment_id : poster_comment_id, profile_owner_id: profile_owner_id, status_id : status_id}),
						cache: false,
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									document.getElementById('textboxcontent_'+Id).value='';
									document.getElementById('textboxcontent_'+Id).focus();

									jQuery('#comment_loadplace_'+Id).append(html);
									jQuery('#comment_loadplace_'+Id).fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',

										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function()
							{
								noty({
									text: breeze_error_message,
									timeout: 3500, type: 'error',
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

	/* Delete a comment */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_comment').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'comment';

				/* Show a nice confirmation box */
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: smf_scripturl + '?action=breezeajax;sa=delete',
								data: ({id : I, type : Type}),
								cache: false,
								success: function(html){
									if(html.type == 'error'){
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'deleted'){
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'ok'){
										jQuery('#comment_id_'+I).fadeIn('slow', 'linear', function(){
											noty({
												text: breeze_success_delete,
												timeout: 3500, type: 'success',
											});
										});
										$noty.close();
									}
								},
								error: function (html){
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

	/* Toggle the comment box */
	jQuery(document).ready(function()
	{
		$(".comment_button").click(function()
		{
			var element = jQuery(this);
			var I = element.attr('id');

			$("#slidepanel"+I).slideToggle(300);
			jQuery(this).toggleClass("active");

			return false;
		});
	});

	/* Delete a status */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_status').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'status';

				jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=delete',
						data: ({id : I, type : Type}),
						cache: false,
						success: function(html)
						{
							if(html == 'error_')
							{
								showNotification(
								{
									message: breeze_error_message,
									type: 'error',
									autoClose: true,
									duration: 3
								});
							}
							else
							{
								jQuery('#status_id_'+I).hide('slow');
								showNotification({
									message: breeze_success_delete,
									type: 'success',
									autoClose: true,
									duration: 3
								});
							}
						},
						error: function (html)
						{
							showNotification(
							{
								message: breeze_error_message,
								type: 'error',
								autoClose: true,
								duration: 3
							});
							jQuery('#status_id_'+I).hide('slow');
						},
					});
				return false;
			});
		});
	});

/* Facebox */
	jQuery(document).ready(function()
	{
		jQuery('a[rel*=facebox]').livequery(function()
		{
			jQuery(this).facebox(
			{
				loadingImage : smf_images_url + '/breeze/loading.gif',
				closeImage   : smf_images_url + '/breeze/error_close.png'
			});
		});
	});<commit_msg>layout: 'center'<commit_after>/**
 * Breeze.js
 *
 * The purpose of this file is to handle all the client side code, the ajax call for the status, comments and other stuff
 * @package Breeze mod
 * @version 1.0 Beta 3
 * @author Jessica Gonzlez <missallsunday@simplemachines.org>
 * @copyright Copyright (c) 2012, Jessica Gonzlez
 * @license http://www.mozilla.org/MPL/MPL-1.1.html
 */

/*
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is http://missallsunday.com code.
 *
 * The Initial Developer of the Original Code is
 * Jessica Gonzlez.
 * Portions created by the Initial Developer are Copyright (c) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 */

/* The status stuff goes right here... */
	jQuery(document).ready(function()
	{
		jQuery('.status_button').livequery(function()
		{
			jQuery(this).click(function()
			{
				var test = jQuery('#content').val();
				var ownerID = jQuery('#owner_id').val();
				var posterID = jQuery('#poster_id').val();
				var loadImage = '
 ' + ajax_notification_text + '';

				/* Disable the button to prevent multiple clicks -_- */
				jQuery(this).attr('disabled', 'disabled');

				if(test=='')
				{
					alert(breeze_empty_message);

					/* Enable the button again... */
					jQuery('.status_button').removeAttr('disabled');
				}

				/* Shhh! */
				else if(test== 'about:breeze')
				{
					alert('Y es que tengo un coraz\xF3n t\xE1n necio \n que no comprende que no entiende \n que le hace da\xF1o amarte tanto \n no comprende que lo haz olvidado \n sigue aferrado a tu recuerdo y a tu amor \n Y es que tengo un coraz\xF3n t\xE1n necio \n que vive preso a las caricias de tus lindas manos \n al dulce beso de tus labios \n y aunque le hace da\xF1o \n te sigue amando igual o mucho m\xE1s que ayer \n mucho m\xE1s que ayer... \n');

					/* Enable the button again... */
					jQuery('.status_button').removeAttr('disabled');
				}

				else
				{
					jQuery('#breeze_load_image').fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=post',
						data: ({content : test, owner_id : ownerID, poster_id : posterID}),
						cache: false,
						dataType: 'json',
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									document.getElementById('content').value='';
									document.getElementById('content').focus();

									jQuery('#breeze_display_status').prepend(html.data);

									jQuery('#breeze_display_status').fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');

							/*
							 * Something happen while sending the request
							 *
							 * @todo identify the different errors and show more info about it to the forum admin
							 */
							jQuery('#breeze_load_image').slideUp('slow', 'linear', function(){
								showNotification(
								{
									message: breeze_error_message,
									type: 'error',
									autoClose: true,
									duration: 3
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

/* Handle the comments */
	jQuery(document).ready(function()
	{
		jQuery('.comment_submit').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var Id = element.attr('id');
				var commentBox = jQuery('#textboxcontent_'+Id).val();
				var loadcommentImage = ' ' + ajax_notification_text + '';
				var status_owner_id = jQuery('#status_owner_id'+Id).val();
				var poster_comment_id = jQuery('#poster_comment_id'+Id).val();
				var profile_owner_id = jQuery('#profile_owner_id'+Id).val();
				var status_id = jQuery('#status_id'+Id).val();
				var loadImage = '
 ' + ajax_notification_text + '';

				if(commentBox=='')
					alert(breeze_empty_message);

				else
				{
					jQuery('#breeze_load_image_comment_'+Id).fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=postcomment',
						data: ({content : commentBox, status_owner_id : status_owner_id, poster_comment_id : poster_comment_id, profile_owner_id: profile_owner_id, status_id : status_id}),
						cache: false,
						success: function(html){
							/* The server side found an issue */
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									document.getElementById('textboxcontent_'+Id).value='';
									document.getElementById('textboxcontent_'+Id).focus();

									jQuery('#comment_loadplace_'+Id).append(html);
									jQuery('#comment_loadplace_'+Id).fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',

										});
									});
								});
							}

							/* Enable the button again... */
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function()
							{
								noty({
									text: breeze_error_message,
									timeout: 3500, type: 'error',
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

	/* Delete a comment */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_comment').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'comment';

				/* Show a nice confirmation box */
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					layout: 'center',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: smf_scripturl + '?action=breezeajax;sa=delete',
								data: ({id : I, type : Type}),
								cache: false,
								success: function(html){
									if(html.type == 'error'){
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'deleted'){
										noty({
											text: html.data,
											timeout: 3500, type: 'error',
										});
									}
									else if(html.type == 'ok'){
										jQuery('#comment_id_'+I).fadeIn('slow', 'linear', function(){
											noty({
												text: breeze_success_delete,
												timeout: 3500, type: 'success',
											});
										});
										$noty.close();
									}
								},
								error: function (html){
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

	/* Toggle the comment box */
	jQuery(document).ready(function()
	{
		$(".comment_button").click(function()
		{
			var element = jQuery(this);
			var I = element.attr('id');

			$("#slidepanel"+I).slideToggle(300);
			jQuery(this).toggleClass("active");

			return false;
		});
	});

	/* Delete a status */
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_status').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var Type = 'status';

				jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=delete',
						data: ({id : I, type : Type}),
						cache: false,
						success: function(html)
						{
							if(html == 'error_')
							{
								showNotification(
								{
									message: breeze_error_message,
									type: 'error',
									autoClose: true,
									duration: 3
								});
							}
							else
							{
								jQuery('#status_id_'+I).hide('slow');
								showNotification({
									message: breeze_success_delete,
									type: 'success',
									autoClose: true,
									duration: 3
								});
							}
						},
						error: function (html)
						{
							showNotification(
							{
								message: breeze_error_message,
								type: 'error',
								autoClose: true,
								duration: 3
							});
							jQuery('#status_id_'+I).hide('slow');
						},
					});
				return false;
			});
		});
	});

/* Facebox */
	jQuery(document).ready(function()
	{
		jQuery('a[rel*=facebox]').livequery(function()
		{
			jQuery(this).facebox(
			{
				loadingImage : smf_images_url + '/breeze/loading.gif',
				closeImage   : smf_images_url + '/breeze/error_close.png'
			});
		});
	});<|endoftext|>


<commit_before>/**
 * breeze.js
 *
 * The purpose of this file is to handle all the client side code, the ajax call for the status, comments and other stuff
 * @package Breeze mod
 * @version 1.0 Beta 3
 * @author Jessica Gonzlez <suki@missallsunday.com>
 * @copyright Copyright (c) 2013 Jessica Gonzlez
 * @license http://www.mozilla.org/MPL/MPL-1.1.html
 */

/*
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is http://missallsunday.com code.
 *
 * The Initial Developer of the Original Code is
 * Jessica Gonzlez.
 * Portions created by the Initial Developer are Copyright (c) 2012, 2013
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 */

// The status stuff goes right here...
	jQuery(document).ready(function()
	{
		jQuery('.status_button').livequery(function()
		{
			jQuery(this).click(function()
			{
				var test = jQuery('#content').val();
				var ownerID = jQuery('#owner_id').val();
				var posterID = jQuery('#poster_id').val();
				var loadImage = '
 ' + ajax_notification_text + '';

				// Disable the button to prevent multiple clicks -_-
				jQuery(this).attr('disabled', 'disabled');

				if(test=='')
				{
					alert(breeze_empty_message);

					// Enable the button again...
					jQuery('.status_button').removeAttr('disabled');
				}

				// Shhh!
				else
					if(test== 'about:breeze')
					{
						alert('Y es que tengo un coraz\xF3n t\xE1n necio \n que no comprende que no entiende \n que le hace da\xF1o amarte tanto \n no comprende que lo haz olvidado \n sigue aferrado a tu recuerdo y a tu amor \n Y es que tengo un coraz\xF3n t\xE1n necio \n que vive preso a las caricias de tus lindas manos \n al dulce beso de tus labios \n y aunque le hace da\xF1o \n te sigue amando igual o mucho m\xE1s que ayer \n mucho m\xE1s que ayer... \n');

						// Enable the button again...
						jQuery('.status_button').removeAttr('disabled');
					}

				else
				{
					jQuery('#breeze_load_image').fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=post;js=1',
						data: ({content : test, owner_id : ownerID, poster_id : posterID}),
						cache: false,
						dataType: 'json',
						success: function(html)
						{
							// The server side found an issue
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									document.getElementById('content').value='';
									document.getElementById('content').focus();

									jQuery('#breeze_display_status').prepend(html.data);

									jQuery('#breeze_display_status').fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							// Enable the button again...
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							// Enable the button again...
							jQuery('.status_button').removeAttr('disabled');

							/*
							 * Something happen while sending the request
							 *
							 * @todo identify the different errors and show more info about it to the forum admin
							 */
							jQuery('#breeze_load_image').slideUp('slow', 'linear', function(){
								noty({
									text: html.data,
									timeout: 3500, type: html.type,
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

// Handle the comments
	jQuery(document).ready(function()
	{
		jQuery('.comment_submit').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var Id = element.attr('id');
				var commentBox = jQuery('#textboxcontent_'+Id).val();
				var loadcommentImage = ' ' + ajax_notification_text + '';
				var status_owner_id = jQuery('#status_owner_id'+Id).val();
				var poster_comment_id = jQuery('#poster_comment_id'+Id).val();
				var profile_owner_id = jQuery('#profile_owner_id'+Id).val();
				var status_id = Id;
				var loadImage = '
 ' + ajax_notification_text + '';

				if(commentBox=='')
					alert(breeze_empty_message);

				else
				{
					jQuery('#breeze_load_image_comment_'+Id).fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=postcomment;js=1',
						data: ({content : commentBox, status_owner_id : status_owner_id, poster_comment_id : poster_comment_id, profile_owner_id: profile_owner_id, status_id : status_id}),
						cache: false,
						dataType: 'json',
						success: function(html){
							// The server side found an issue
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									noty({
										text: breeze_error_message,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									document.getElementById('textboxcontent_'+Id).value='';
									document.getElementById('textboxcontent_'+Id).focus();
									jQuery('#comment_loadplace_'+Id).append(html.data);
									jQuery('#comment_loadplace_'+Id).fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							// Enable the button again...
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow');
							noty({
								text: breeze_error_message,
								timeout: 3500, type: 'error',
							});
						},
					});
				}
				return false;
			});
		});
	});

	// Delete a comment
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_comment').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var typeMethod = 'comment';
				var urlParam = element.attr('href');

				// Show a nice confirmation box
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: urlParam + ';js=1',
								cache: false,
								dataType: 'json',
								success: function(html){
									$noty.close();

									switch(html.type)
									{
										case 'error':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'deleted':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'ok':
										jQuery('#comment_id_'+I).fadeOut('slow');
										noty({
											text: html.data,
											timeout: 3500, type: 'success',
										});
										break;
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

	// Delete a status
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_status').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var typeMethod = 'status';
				var urlParam = element.attr('href');

				// Show a nice confirmation box
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: urlParam + ';js=1',
								cache: false,
								dataType: 'json',
								success: function(html){
									$noty.close();
									switch(html.type)
									{
										case 'error':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'deleted':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'ok':
											jQuery('#status_id_'+I).fadeOut('slow');
											noty({
												text: html.data,
												timeout: 3500, type: 'success',
											});
										break;
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

// Facebox
jQuery(document).ready(function()
{
	jQuery('a[rel*=facebox]').livequery(function()
	{
		jQuery(this).facebox(
		{
			loadingImage : smf_images_url + '/breeze/loading.gif',
			closeImage   : smf_images_url + '/breeze/error_close.png'
		});
	});
});

// infinitescroll
jQuery(document).ready(function(){

	jQuery.noConflict();
	jQuery('#breeze_display_status').infinitescroll({
		loading: {
			finished: undefined,
			msg: null,
			msgText  : breeze_page_loading,
			img   : smf_images_url + "/breeze/loading.gif",
			finishedMsg     : breeze_page_loading_end,
			selector: null,
			speed: 'slow',
			start: undefined
		},
		navSelector  : "#breeze_pagination",
		nextSelector : "#breeze_next_link",
		itemSelector : "li.windowbg",
		animate      : true,
	});
});

// Mark as un/read
// jQuery(document).ready(function(){
	// jQuery('.Breeze_markRead').click(function(){

		// var element = jQuery(this);
		// var user = breeze_current_user;

		// jQuery.ajax({
			// type: 'GET',
			// url: element.attr('href') + 'js=1',
			// cache: false,
			// dataType: 'json',
			// success: function(html)
			// {
				// if(html.type == 'error')
				// {
					// noty({text: breeze_error_message, timeout: 3500, type: 'error'});
				// }

				// else if(html.type == 'ok')
				// {
					// noty({text: breeze_noti_delete_after, timeout: 3500, type: 'success'});
				// }
			// },
			// error: function (html)
			// {
				// noty({text: breeze_error_message, timeout: 3500, type: 'error'});
			// },
		// });
	// });
// });

// Delete a notification
// jQuery(document).ready(function(){
	// jQuery('.Breeze_delete').click(function(){

		// var element = jQuery(this);
		// var noti_id = element.attr('id').replace(/[^0-9]/gi, '');
		// noti_id = parseInt(noti_id, 10);
		// var user = breeze_current_user;

		// jQuery.ajax(
		// {
			// type: 'POST',
			// url: smf_scripturl + '?action=breezeajax;sa=notidelete;js=1',
			// data: ({content : noti_id, user : user}),
			// cache: false,
			// dataType: 'json',
			// success: function(html)
			// {
				// if(html.type == 'error')
				// {
					// noty({text: breeze_error_message, timeout: 3500, type: 'error'});
				// }

				// else if(html.type == 'ok')
				// {
					// noty({text: breeze_noti_markasread_after, timeout: 3500, type: 'success'});
				// }
			// },
			// error: function (html)
			// {
				// noty({text: breeze_error_message, timeout: 3500, type: 'error'});
			// },
		// });
	// });
// });

// Scroll to top
jQuery(document).ready(function(){

	// hide #breezeTop first
	jQuery("#breezeTop").hide();

	jQuery(function ()
	{
		jQuery(window).scroll(function ()
		{
			if (jQuery(this).scrollTop() > 100)
			{
				jQuery('#breezeTop').fadeIn();
			}
			else
			{
				jQuery('#breezeTop').fadeOut();
			}
		});

		jQuery('#breezeTop a').click(function ()
		{
			jQuery('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		});
	});
});

jQuery(document).ready(function(){
	jQuery('textarea[rel*=atwhoMention]').bind("focus", function(event){
		jQuery.ajax({
			url: smf_scripturl + '?action=breezeajax;sa=usersmention;js=1',
			type: "GET",
			dataType: "json",
			success: function(result)
			{
				jQuery('textarea[rel*=atwhoMention]').atwho('@', {
					search_key: "name",
					tpl: "
${name} ${id}
",
					data: result,
					limit: breeze_how_many_mentions_options,
					callback: {
						filter: function (query, data, search_key) {
							return jQuery.map(data, function(item, i) {
								return item[search_key].toLowerCase().indexOf(query) < 0 ? null : item
							})
						},
					}
				});
			},
		});
	});
});
<commit_msg>No need for this<commit_after>/**
 * breeze.js
 *
 * The purpose of this file is to handle all the client side code, the ajax call for the status, comments and other stuff
 * @package Breeze mod
 * @version 1.0 Beta 3
 * @author Jessica Gonzlez <suki@missallsunday.com>
 * @copyright Copyright (c) 2013 Jessica Gonzlez
 * @license http://www.mozilla.org/MPL/MPL-1.1.html
 */

/*
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is http://missallsunday.com code.
 *
 * The Initial Developer of the Original Code is
 * Jessica Gonzlez.
 * Portions created by the Initial Developer are Copyright (c) 2012, 2013
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 */

// The status stuff goes right here...
	jQuery(document).ready(function()
	{
		jQuery('.status_button').livequery(function()
		{
			jQuery(this).click(function()
			{
				var test = jQuery('#content').val();
				var ownerID = jQuery('#owner_id').val();
				var posterID = jQuery('#poster_id').val();
				var loadImage = '
 ' + ajax_notification_text + '';

				// Disable the button to prevent multiple clicks -_-
				jQuery(this).attr('disabled', 'disabled');

				if(test=='')
				{
					alert(breeze_empty_message);

					// Enable the button again...
					jQuery('.status_button').removeAttr('disabled');
				}

				// Shhh!
				else
					if(test== 'about:breeze')
					{
						alert('Y es que tengo un coraz\xF3n t\xE1n necio \n que no comprende que no entiende \n que le hace da\xF1o amarte tanto \n no comprende que lo haz olvidado \n sigue aferrado a tu recuerdo y a tu amor \n Y es que tengo un coraz\xF3n t\xE1n necio \n que vive preso a las caricias de tus lindas manos \n al dulce beso de tus labios \n y aunque le hace da\xF1o \n te sigue amando igual o mucho m\xE1s que ayer \n mucho m\xE1s que ayer... \n');

						// Enable the button again...
						jQuery('.status_button').removeAttr('disabled');
					}

				else
				{
					jQuery('#breeze_load_image').fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=post;js=1',
						data: ({content : test, owner_id : ownerID, poster_id : posterID}),
						cache: false,
						dataType: 'json',
						success: function(html)
						{
							// The server side found an issue
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									noty({
										text: html.data,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image').fadeOut('slow', 'linear', function(){
									document.getElementById('content').value='';
									document.getElementById('content').focus();

									jQuery('#breeze_display_status').prepend(html.data);

									jQuery('#breeze_display_status').fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							// Enable the button again...
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							// Enable the button again...
							jQuery('.status_button').removeAttr('disabled');

							/*
							 * Something happen while sending the request
							 *
							 * @todo identify the different errors and show more info about it to the forum admin
							 */
							jQuery('#breeze_load_image').slideUp('slow', 'linear', function(){
								noty({
									text: html.data,
									timeout: 3500, type: html.type,
								});
							});
						},
					});
				}
				return false;
			});
		});
	});

// Handle the comments
	jQuery(document).ready(function()
	{
		jQuery('.comment_submit').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var Id = element.attr('id');
				var commentBox = jQuery('#textboxcontent_'+Id).val();
				var loadcommentImage = ' ' + ajax_notification_text + '';
				var status_owner_id = jQuery('#status_owner_id'+Id).val();
				var poster_comment_id = jQuery('#poster_comment_id'+Id).val();
				var profile_owner_id = jQuery('#profile_owner_id'+Id).val();
				var status_id = Id;
				var loadImage = '
 ' + ajax_notification_text + '';

				if(commentBox=='')
					alert(breeze_empty_message);

				else
				{
					jQuery('#breeze_load_image_comment_'+Id).fadeIn('slow').html(loadImage);

					jQuery.ajax(
					{
						type: 'POST',
						url: smf_scripturl + '?action=breezeajax;sa=postcomment;js=1',
						data: ({content : commentBox, status_owner_id : status_owner_id, poster_comment_id : poster_comment_id, profile_owner_id: profile_owner_id, status_id : status_id}),
						cache: false,
						dataType: 'json',
						success: function(html){
							// The server side found an issue
							if(html.type == 'error')
							{
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									noty({
										text: breeze_error_message,
										timeout: 3500, type: html.type,
									});
								});
							}

							else if(html.type == 'ok'){
								jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow', 'linear', function(){
									document.getElementById('textboxcontent_'+Id).value='';
									document.getElementById('textboxcontent_'+Id).focus();
									jQuery('#comment_loadplace_'+Id).append(html.data);
									jQuery('#comment_loadplace_'+Id).fadeIn('slow', 'linear', function(){
										noty({
											text: breeze_success_message,
											timeout: 3500, type: 'success',
										});
									});
								});
							}

							// Enable the button again...
							jQuery('.status_button').removeAttr('disabled');
						},
						error: function (html)
						{
							jQuery('#breeze_load_image_comment_'+Id).fadeOut('slow');
							noty({
								text: breeze_error_message,
								timeout: 3500, type: 'error',
							});
						},
					});
				}
				return false;
			});
		});
	});

	// Delete a comment
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_comment').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var typeMethod = 'comment';
				var urlParam = element.attr('href');

				// Show a nice confirmation box
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: urlParam + ';js=1',
								cache: false,
								dataType: 'json',
								success: function(html){
									$noty.close();

									switch(html.type)
									{
										case 'error':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'deleted':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'ok':
										jQuery('#comment_id_'+I).fadeOut('slow');
										noty({
											text: html.data,
											timeout: 3500, type: 'success',
										});
										break;
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

	// Delete a status
	jQuery(document).ready(function()
	{
		jQuery('.breeze_delete_status').livequery(function()
		{
			jQuery(this).click(function()
			{
				var element = jQuery(this);
				var I = element.attr('id');
				var typeMethod = 'status';
				var urlParam = element.attr('href');

				// Show a nice confirmation box
				noty({
					text: breeze_confirm_delete,
					type: 'confirmation',
					dismissQueue: false,
					closeWith: ['button'],
					buttons: [{
						addClass: 'button_submit', text: breeze_confirm_yes, onClick: function($noty) {
							jQuery.ajax({
								type: 'POST',
								url: urlParam + ';js=1',
								cache: false,
								dataType: 'json',
								success: function(html){
									$noty.close();
									switch(html.type)
									{
										case 'error':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'deleted':
											noty({
												text: html.data,
												timeout: 3500, type: 'error',
											});
										break;
										case 'ok':
											jQuery('#status_id_'+I).fadeOut('slow');
											noty({
												text: html.data,
												timeout: 3500, type: 'success',
											});
										break;
									}
								},
								error: function (html){
									$noty.close();
									noty({
										text: html.data,
										timeout: 3500, type: 'error',
									});
								},
							});
						}
					},
						{addClass: 'button_submit', text: breeze_confirm_cancel, onClick: function($noty) {
							$noty.close();
						}}
					]
				});
				return false;
			});
		});
	});

// Facebox
jQuery(document).ready(function()
{
	jQuery('a[rel*=facebox]').livequery(function()
	{
		jQuery(this).facebox(
		{
			loadingImage : smf_images_url + '/breeze/loading.gif',
			closeImage   : smf_images_url + '/breeze/error_close.png'
		});
	});
});

// infinitescroll
jQuery(document).ready(function(){

	jQuery.noConflict();
	jQuery('#breeze_display_status').infinitescroll({
		loading: {
			finished: undefined,
			msg: null,
			msgText  : breeze_page_loading,
			img   : smf_images_url + "/breeze/loading.gif",
			finishedMsg     : breeze_page_loading_end,
			selector: null,
			speed: 'slow',
			start: undefined
		},
		navSelector  : "#breeze_pagination",
		nextSelector : "#breeze_next_link",
		itemSelector : "li.windowbg",
		animate      : true,
	});
});

// Scroll to top
jQuery(document).ready(function(){

	// hide #breezeTop first
	jQuery("#breezeTop").hide();

	jQuery(function ()
	{
		jQuery(window).scroll(function ()
		{
			if (jQuery(this).scrollTop() > 100)
			{
				jQuery('#breezeTop').fadeIn();
			}
			else
			{
				jQuery('#breezeTop').fadeOut();
			}
		});

		jQuery('#breezeTop a').click(function ()
		{
			jQuery('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		});
	});
});

jQuery(document).ready(function(){
	jQuery('textarea[rel*=atwhoMention]').bind("focus", function(event){
		jQuery.ajax({
			url: smf_scripturl + '?action=breezeajax;sa=usersmention;js=1',
			type: "GET",
			dataType: "json",
			success: function(result)
			{
				jQuery('textarea[rel*=atwhoMention]').atwho('@', {
					search_key: "name",
					tpl: "
${name} ${id}
",
					data: result,
					limit: breeze_how_many_mentions_options,
					callback: {
						filter: function (query, data, search_key) {
							return jQuery.map(data, function(item, i) {
								return item[search_key].toLowerCase().indexOf(query) < 0 ? null : item
							})
						},
					}
				});
			},
		});
	});
});
<|endoftext|>