<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';

import {
	addComponent,
	removeComponent,
	watchComponent,
	updateQuery,
} from '@appbaseio/reactivecore/lib/actions';
import {
	checkValueChange,
	checkPropChange,
	getClassName,
} from '@appbaseio/reactivecore/lib/utils/helper';
import types from '@appbaseio/reactivecore/lib/utils/types';

import Title from '../../styles/Title';
import Button, { numberBoxContainer } from '../../styles/Button';
import Flex from '../../styles/Flex';

class NumberBox extends Component {
	constructor(props) {
		super(props);

		this.type = 'term';
		this.state = {
			currentValue: this.props.data.start,
		};
		this.locked = false;
	}

	componentWillMount() {
		this.props.addComponent(this.props.componentId);
		this.setReact(this.props);

		if (this.props.selectedValue) {
			this.setValue(this.props.selectedValue);
		} else if (this.props.defaultSelected) {
			this.setValue(this.props.defaultSelected);
		}
	}

	componentWillReceiveProps(nextProps) {
		checkPropChange(this.props.react, nextProps.react, () => {
			this.setReact(nextProps);
		});
		checkPropChange(this.props.defaultSelected, nextProps.defaultSelected, () => {
			this.setValue(nextProps.defaultSelected, nextProps);
		});
		checkPropChange(this.props.queryFormat, nextProps.queryFormat, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});
		checkPropChange(this.props.dataField, nextProps.dataField, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});
	}

	componentWillUnmount() {
		this.props.removeComponent(this.props.componentId);
	}

	defaultQuery = (value, props) => {
		switch (props.queryFormat) {
			case 'exact':
				return {
					term: {
						[props.dataField]: value,
					},
				};
			case 'lte':
				return {
					range: {
						[props.dataField]: {
							lte: value,
							boost: 2.0,
						},
					},
				};
			case 'gte':
				return {
					range: {
						[props.dataField]: {
							gte: value,
							boost: 2.0,
						},
					},
				};
			default:
				return null;
		}
	};

	setReact(props) {
		if (props.react) {
			props.watchComponent(props.componentId, props.react);
		}
	}

	incrementValue = () => {
		if (this.state.currentValue === this.props.data.end) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue + 1);
	};

	decrementValue = () => {
		if (this.state.currentValue === this.props.data.start) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue - 1);
	};

	setValue = (value, props = this.props) => {
		// ignore state updates when component is locked
		if (props.beforeValueChange && this.locked) {
			return;
		}

		this.locked = true;
		const performUpdate = () => {
			this.setState({
				currentValue: value,
			}, () => {
				this.updateQuery(value, props);
				this.locked = false;
			});
		};
		checkValueChange(
			props.componentId,
			value,
			props.beforeValueChange,
			props.onValueChange,
			performUpdate,
		);
	};

	updateQuery = (value, props) => {
		const query = props.customQuery || this.defaultQuery;
		let onQueryChange = null;
		if (props.onQueryChange) {
			onQueryChange = props.onQueryChange;
		}
		props.updateQuery({
			componentId: props.componentId,
			query: query(value, props),
			value,
			onQueryChange,
			showFilter: false, // we don't need filters for NumberBox
			URLParams: props.URLParams,
		});
	};

	render() {
		return (

				{this.props.title && (
					<Title className={getClassName(this.props.innerClass, 'title') || null}>
						{this.props.title}
					</Title>
				)}
				<Flex labelPosition={this.props.labelPosition} justifyContent="space-between" className={numberBoxContainer}>

						{this.props.data.label}

						<Button
							className={getClassName(this.props.innerClass, 'button') || null}
							onClick={this.decrementValue}
							disabled={this.state.currentValue === this.props.data.start}
						>
							-
						</Button>
						{this.state.currentValue}
						<Button
							className={getClassName(this.props.innerClass, 'button') || null}
							onClick={this.incrementValue}
							disabled={this.state.currentValue === this.props.data.end}
						>
							+
						</Button>

				</Flex>

		);
	}
}

NumberBox.propTypes = {
	addComponent: types.funcRequired,
	componentId: types.stringRequired,
	defaultSelected: types.number,
	dataField: types.stringRequired,
	data: types.dataNumberBox,
	react: types.react,
	removeComponent: types.funcRequired,
	title: types.title,
	queryFormat: types.queryFormatNumberBox,
	labelPosition: types.labelPosition,
	URLParams: types.boolRequired,
	selectedValue: types.selectedValue,
	style: types.style,
	className: types.string,
	innerClass: types.style,
};

NumberBox.defaultProps = {
	queryFormat: 'gte',
	labelPosition: 'left',
	URLParams: false,
	style: {},
	className: null,
};

const mapStateToProps = (state, props) => ({
	selectedValue: state.selectedValues[props.componentId]
		? state.selectedValues[props.componentId].value
		: null,
});

const mapDispatchtoProps = dispatch => ({
	addComponent: component => dispatch(addComponent(component)),
	removeComponent: component => dispatch(removeComponent(component)),
	watchComponent: (component, react) => dispatch(watchComponent(component, react)),
	updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)),
});

export default connect(mapStateToProps, mapDispatchtoProps)(NumberBox);
<commit_msg>Fix onQueryChange prop-type<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';

import {
	addComponent,
	removeComponent,
	watchComponent,
	updateQuery,
} from '@appbaseio/reactivecore/lib/actions';
import {
	checkValueChange,
	checkPropChange,
	getClassName,
} from '@appbaseio/reactivecore/lib/utils/helper';
import types from '@appbaseio/reactivecore/lib/utils/types';

import Title from '../../styles/Title';
import Button, { numberBoxContainer } from '../../styles/Button';
import Flex from '../../styles/Flex';

class NumberBox extends Component {
	constructor(props) {
		super(props);

		this.type = 'term';
		this.state = {
			currentValue: this.props.data.start,
		};
		this.locked = false;
	}

	componentWillMount() {
		this.props.addComponent(this.props.componentId);
		this.setReact(this.props);

		if (this.props.selectedValue) {
			this.setValue(this.props.selectedValue);
		} else if (this.props.defaultSelected) {
			this.setValue(this.props.defaultSelected);
		}
	}

	componentWillReceiveProps(nextProps) {
		checkPropChange(this.props.react, nextProps.react, () => {
			this.setReact(nextProps);
		});
		checkPropChange(this.props.defaultSelected, nextProps.defaultSelected, () => {
			this.setValue(nextProps.defaultSelected, nextProps);
		});
		checkPropChange(this.props.queryFormat, nextProps.queryFormat, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});
		checkPropChange(this.props.dataField, nextProps.dataField, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});
	}

	componentWillUnmount() {
		this.props.removeComponent(this.props.componentId);
	}

	defaultQuery = (value, props) => {
		switch (props.queryFormat) {
			case 'exact':
				return {
					term: {
						[props.dataField]: value,
					},
				};
			case 'lte':
				return {
					range: {
						[props.dataField]: {
							lte: value,
							boost: 2.0,
						},
					},
				};
			case 'gte':
				return {
					range: {
						[props.dataField]: {
							gte: value,
							boost: 2.0,
						},
					},
				};
			default:
				return null;
		}
	};

	setReact(props) {
		if (props.react) {
			props.watchComponent(props.componentId, props.react);
		}
	}

	incrementValue = () => {
		if (this.state.currentValue === this.props.data.end) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue + 1);
	};

	decrementValue = () => {
		if (this.state.currentValue === this.props.data.start) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue - 1);
	};

	setValue = (value, props = this.props) => {
		// ignore state updates when component is locked
		if (props.beforeValueChange && this.locked) {
			return;
		}

		this.locked = true;
		const performUpdate = () => {
			this.setState({
				currentValue: value,
			}, () => {
				this.updateQuery(value, props);
				this.locked = false;
			});
		};
		checkValueChange(
			props.componentId,
			value,
			props.beforeValueChange,
			props.onValueChange,
			performUpdate,
		);
	};

	updateQuery = (value, props) => {
		const query = props.customQuery || this.defaultQuery;
		let onQueryChange = null;
		if (props.onQueryChange) {
			onQueryChange = props.onQueryChange;
		}
		props.updateQuery({
			componentId: props.componentId,
			query: query(value, props),
			value,
			onQueryChange,
			showFilter: false, // we don't need filters for NumberBox
			URLParams: props.URLParams,
		});
	};

	render() {
		return (

				{this.props.title && (
					<Title className={getClassName(this.props.innerClass, 'title') || null}>
						{this.props.title}
					</Title>
				)}
				<Flex labelPosition={this.props.labelPosition} justifyContent="space-between" className={numberBoxContainer}>

						{this.props.data.label}

						<Button
							className={getClassName(this.props.innerClass, 'button') || null}
							onClick={this.decrementValue}
							disabled={this.state.currentValue === this.props.data.start}
						>
							-
						</Button>
						{this.state.currentValue}
						<Button
							className={getClassName(this.props.innerClass, 'button') || null}
							onClick={this.incrementValue}
							disabled={this.state.currentValue === this.props.data.end}
						>
							+
						</Button>

				</Flex>

		);
	}
}

NumberBox.propTypes = {
	addComponent: types.funcRequired,
	componentId: types.stringRequired,
	defaultSelected: types.number,
	dataField: types.stringRequired,
	data: types.dataNumberBox,
	react: types.react,
	removeComponent: types.funcRequired,
	title: types.title,
	queryFormat: types.queryFormatNumberBox,
	labelPosition: types.labelPosition,
	URLParams: types.boolRequired,
	selectedValue: types.selectedValue,
	style: types.style,
	className: types.string,
	innerClass: types.style,
	onQueryChange: types.func,
};

NumberBox.defaultProps = {
	queryFormat: 'gte',
	labelPosition: 'left',
	URLParams: false,
	style: {},
	className: null,
};

const mapStateToProps = (state, props) => ({
	selectedValue: state.selectedValues[props.componentId]
		? state.selectedValues[props.componentId].value
		: null,
});

const mapDispatchtoProps = dispatch => ({
	addComponent: component => dispatch(addComponent(component)),
	removeComponent: component => dispatch(removeComponent(component)),
	watchComponent: (component, react) => dispatch(watchComponent(component, react)),
	updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)),
});

export default connect(mapStateToProps, mapDispatchtoProps)(NumberBox);
<|endoftext|>


<commit_before>Handlebars.registerHelper('methodSelect', function(inMethod, index){
    var methods=["GET", "POST", "PUT", "DELETE", "UPDATE"];

    var html = "<select class='classField' id='method"+index+"'>"

    methods.forEach(function(element){
        html += "<option vale='"+element+"' ";
        if(element == inMethod){
            html += "selected";
        }
        html += ">"+element+"</option>";
    });

    html += "</select>";

    return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('input', function(index, id, value, inPlaceholder, inType){
    var placeholder = typeof inPlaceholder == "string" ? inPlaceholder : " ",
        type = typeof inType == "string" ? inType : "text";

    var html = "<input class='classField' type='"+type+"' value='"+value+"' id='"+id+index+"' placeholder='"+placeholder+"'>";

    return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('textarea', function(index, id, value, inPlaceholder){
    var placeholder = typeof inPlaceholder == "string" ? inPlaceholder : " ";

    var html = "<textarea class='classField' id='"+id+index+"' placeholder='"+placeholder+"'>"+JSON.stringify(value)+"</textarea>";

    return new Handlebars.SafeString(html);
});

window.Adjure = {};

Adjure.defaultCall = {
    title: "New call",
    method: "GET",
    url: "/api/test",
    data: {
        key: "value"
    },
    isDirty: true
};

Adjure.currentData = {
    calls: []
};

Adjure.storedData = {
    calls: []
};

Adjure.init = function(){
    var source = $("#calls-template").html();
    Adjure.callsTemplate = Handlebars.compile(source);
    Adjure.load();
    Adjure.renderLoop();
};

Adjure.renderLoop = function(){
    var html = Adjure.callsTemplate(Adjure.currentData);
    $('#body-js').html(html);
};

Adjure.new = function(){
    Adjure.currentData.calls.push(Adjure.defaultCall);
    //Adjure.storedData.calls.push(Adjure.defaultCall);
    Adjure.renderLoop();
}

Adjure.runCall = function(index){
    var url = Adjure.currentData.calls[index].url,
        method = Adjure.currentData.calls[index].method,
        data = Adjure.currentData.calls[index].data;

        if(method === 'GET') {
            url += '?';
            $.each(data, function(key,value) {
                url += key + '=' + value + '&';
            });
            url = url.substring(0,url.length-1);
        }

    $.ajax({
        url: url,
        content: data,
        type: method
    })
}

Adjure.syncCall = function(index){

    var callObject = {
        title: $("#title"+index).html().toString(),
        method: $("#method"+index).val(),
        url: $("#url"+index).val(),
        data: JSON.parse($("#data"+index).val()),
        isDirty: true
    };

    if(Adjure.currentData.calls[index].isDirty){
        Adjure.currentData.calls[index] = callObject;
    } else {
        Adjure.currentData.calls[index] = callObject;
        Adjure.setIsDirtyMarker(index, true);
    }
}

Adjure.load = function(){
    var loaded = JSON.parse(localStorage.getItem("adjure-data-store"));

    if(loaded != null && Array.isArray(loaded)){
        loaded.forEach(function(element){
            Adjure.currentData.calls.push(element);
            Adjure.storedData.calls.push(element);
        });
    }

    if(Adjure.currentData.calls.length == 0){
        Adjure.currentData.calls[0] = Adjure.defaultCall;
        Adjure.storedData.calls[0] = Adjure.defaultCall;
    }
};

Adjure._save = function(){
    localStorage.setItem("adjure-data-store", JSON.stringify(Adjure.storedData.calls));
}

Adjure.delete = function(index){
    Adjure.currentData.calls.splice(index, 1);
    Adjure.storedData.calls.splice(index, 1);
    Adjure._save();
    Adjure.renderLoop();
}

Adjure.saveAll = function(){
    var needUpdate = false;
    Adjure.currentData.calls.forEach(function(item){
        if(!needUpdate && item.isDirty){
            needUpdate = true;
        }
        item.isDirty = false;
    });
    if (needUpdate) {
        Adjure.storedData.calls = Adjure.currentData.calls;
        Adjure._save();
        Adjure.renderLoop();
    }
};

Adjure.saveOne = function(index){
    if(Adjure.currentData.calls[index].isDirty) {
        Adjure.currentData.calls[index].isDirty = false;
        Adjure.storedData.calls[index] = Adjure.currentData.calls[index];
        Adjure._save
        Adjure.setIsDirtyMarker(index, false)
    }
};

Adjure.setIsDirtyMarker = function(index, isDirty) {
    isDirtyMarker = $("#is-dirty"+index);

    if(isDirty) {
        isDirtyMarker.removeClass("hide");
    } else {
        isDirtyMarker.addClass("hide");
    }
};

Adjure._getIndex = function(target){
    return $(target).parents(".call").attr("data-index");
}

// Event Listeners

$("#new-call-js").on('click', function(){
    Adjure.new();
});

$("#save-all-js").on('click', function(){
    Adjure.saveAll();
});

$("#body-js").on('change input', '.classField', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.syncCall(index);
});

$("#body-js").on('click', '.call-run-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.runCall(index);
});

$("#body-js").on('click', '.call-save-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.saveOne(index);
});

$("#body-js").on('click', '.call-delete-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.delete(index);
});

$("#body-js").on('blur paste input', '.content-editable-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.syncCall(index);
    console.log("title changed");
})
<commit_msg>Fixed error with adjure calls not saving on saveOne<commit_after>Handlebars.registerHelper('methodSelect', function(inMethod, index){
    var methods=["GET", "POST", "PUT", "DELETE", "UPDATE"];

    var html = "<select class='classField' id='method"+index+"'>"

    methods.forEach(function(element){
        html += "<option vale='"+element+"' ";
        if(element == inMethod){
            html += "selected";
        }
        html += ">"+element+"</option>";
    });

    html += "</select>";

    return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('input', function(index, id, value, inPlaceholder, inType){
    var placeholder = typeof inPlaceholder == "string" ? inPlaceholder : " ",
        type = typeof inType == "string" ? inType : "text";

    var html = "<input class='classField' type='"+type+"' value='"+value+"' id='"+id+index+"' placeholder='"+placeholder+"'>";

    return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('textarea', function(index, id, value, inPlaceholder){
    var placeholder = typeof inPlaceholder == "string" ? inPlaceholder : " ";

    var html = "<textarea class='classField' id='"+id+index+"' placeholder='"+placeholder+"'>"+JSON.stringify(value)+"</textarea>";

    return new Handlebars.SafeString(html);
});

window.Adjure = {};

Adjure.defaultCall = {
    title: "New call",
    method: "GET",
    url: "/api/test",
    data: {
        key: "value"
    },
    isDirty: true
};

Adjure.currentData = {
    calls: []
};

Adjure.storedData = {
    calls: []
};

Adjure.init = function(){
    var source = $("#calls-template").html();
    Adjure.callsTemplate = Handlebars.compile(source);
    Adjure.load();
    Adjure.renderLoop();
};

Adjure.renderLoop = function(){
    var html = Adjure.callsTemplate(Adjure.currentData);
    $('#body-js').html(html);
};

Adjure.new = function(){
    Adjure.currentData.calls.push(Adjure.defaultCall);
    //Adjure.storedData.calls.push(Adjure.defaultCall);
    Adjure.renderLoop();
}

Adjure.runCall = function(index){
    var url = Adjure.currentData.calls[index].url,
        method = Adjure.currentData.calls[index].method,
        data = Adjure.currentData.calls[index].data;

        if(method === 'GET') {
            url += '?';
            $.each(data, function(key,value) {
                url += key + '=' + value + '&';
            });
            url = url.substring(0,url.length-1);
        }

    $.ajax({
        url: url,
        content: data,
        type: method
    })
}

Adjure.syncCall = function(index){

    var callObject = {
        title: $("#title"+index).html().toString(),
        method: $("#method"+index).val(),
        url: $("#url"+index).val(),
        data: JSON.parse($("#data"+index).val()),
        isDirty: true
    };

    if(Adjure.currentData.calls[index].isDirty){
        Adjure.currentData.calls[index] = callObject;
    } else {
        Adjure.currentData.calls[index] = callObject;
        Adjure.setIsDirtyMarker(index, true);
    }
}

Adjure.load = function(){
    var loaded = JSON.parse(localStorage.getItem("adjure-data-store"));

    if(loaded != null && Array.isArray(loaded)){
        loaded.forEach(function(element){
            Adjure.currentData.calls.push(element);
            Adjure.storedData.calls.push(element);
        });
    }

    if(Adjure.currentData.calls.length == 0){
        Adjure.currentData.calls[0] = Adjure.defaultCall;
        Adjure.storedData.calls[0] = Adjure.defaultCall;
    }
};

Adjure._save = function(){
    localStorage.setItem("adjure-data-store", JSON.stringify(Adjure.storedData.calls));
}

Adjure.delete = function(index){
    Adjure.currentData.calls.splice(index, 1);
    Adjure.storedData.calls.splice(index, 1);
    Adjure._save();
    Adjure.renderLoop();
}

Adjure.saveAll = function(){
    var needUpdate = false;
    Adjure.currentData.calls.forEach(function(item){
        if(!needUpdate && item.isDirty){
            needUpdate = true;
        }
        item.isDirty = false;
    });
    if (needUpdate) {
        Adjure.storedData.calls = Adjure.currentData.calls;
        Adjure._save();
        Adjure.renderLoop();
    }
};

Adjure.saveOne = function(index){
    if(Adjure.currentData.calls[index].isDirty) {
        Adjure.currentData.calls[index].isDirty = false;
        Adjure.storedData.calls[index] = Adjure.currentData.calls[index];
        Adjure._save();
        Adjure.setIsDirtyMarker(index, false)
    }
};

Adjure.setIsDirtyMarker = function(index, isDirty) {
    isDirtyMarker = $("#is-dirty"+index);

    if(isDirty) {
        isDirtyMarker.removeClass("hide");
    } else {
        isDirtyMarker.addClass("hide");
    }
};

Adjure._getIndex = function(target){
    return $(target).parents(".call").attr("data-index");
}

// Event Listeners

$("#new-call-js").on('click', function(){
    Adjure.new();
});

$("#save-all-js").on('click', function(){
    Adjure.saveAll();
});

$("#body-js").on('change input', '.classField', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.syncCall(index);
});

$("#body-js").on('click', '.call-run-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.runCall(index);
});

$("#body-js").on('click', '.call-save-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.saveOne(index);
});

$("#body-js").on('click', '.call-delete-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.delete(index);
});

$("#body-js").on('blur paste input', '.content-editable-js', function(e){
    var index = Adjure._getIndex(e.target);
    Adjure.syncCall(index);
    console.log("title changed");
})
<|endoftext|>


<commit_before>// Use Primo Method to Check if this is a mobile device
window.onload = function() {
    try {
        (function(a) {
            (jQuery.browser = jQuery.browser || {}).mobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))
        })(navigator.userAgent || navigator.vendor || window.opera);
        if (($(window).width() <= 500 && jQuery.browser.mobile) || ('true' == getRequestParameterByName('debug_mobile'))) {
            $('body').addClass('mobile-device');
        }
    } catch (mobileErr) {
        log('JS changes for mobile failed:' + mobileErr);
    }
}

// .exists function for jQuery
$.fn.exists = function(callback) {
    var args = [].slice.call(arguments, 1);
    if (this.length) {
        callback.call(this, args);
    }
    return this;
};

$.fn.isMissing = function(callback) {
    var args = [].slice.call(arguments, 1);
    if (!this.length) {
        callback.call(this, args);
    }
    return this;
};

function isKorean() {
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function expandableMobileFacet(trigger_query, parent_query) {
    $(trigger_query).bind('click', function(e) {
        $(this).closest(parent_query).toggleClass('expanded-for-mobile');
        e.preventDefault();
    });
};

function initFilterExpand() {
    $("#exlidFacetTile").exists(function() {
        if (isKorean()) {
            $(this).prepend('

검색 필터

');
        } else {
            $(this).prepend('

Search Filters

');
        }
        expandableMobileFacet($(this).find(".filters-expand-title"), $(this));
    });
}

// Responsive Menu
$(document).ready(function() {
    var triggerBttn = $('#responsive-menu-trigger'),
        overlay = $('#responsive-menu-overlay'),
        closeBttn = overlay.find('button.overlay-close'),
        navigationHeader = $('#responsive-header');

    function toggleOverlay() {
        if (overlay.hasClass('open')) {
            overlay.removeClass('open');
            navigationHeader.removeClass('open');
            ensureMenusAreClosed();
        } else if (navigationHeader.hasClass('open')) {
            overlay.removeClass('open');
            navigationHeader.removeClass('open');
            ensureMenusAreClosed();
        } else {
            overlay.addClass('open');
            navigationHeader.addClass('open');
        }
    }

    triggerBttn.click(function() {
        toggleOverlay();
    });

    closeBttn.click(function() {
        toggleOverlay();
    });

    // Menu Expands
    function ensureMenusAreClosed() {
        var firstLevelItems = $('#responsive-menu-overlay nav > ul > li, #responsive-menu-overlay nav > div > ul > li');
        firstLevelItems.removeClass('expanded');
    }

    function initJsExpands() {
        var firstLevelItems = $('#responsive-menu-overlay nav > ul > li, #responsive-menu-overlay nav > div > ul > li'),
            secondLevelItems = $('#responsive-menu-overlay nav > ul > li > ul > li');

        firstLevelItems.each(function() {
            if ($(this).children('ul').length != 0) {
                $(this).addClass('is-expandable');
            }
        });

        // Remove any accidental third level
        secondLevelItems.each(function() {
            $(this).find('ul').remove();
        });

        // Bind the links to expand / collapse
        firstLevelItems.children('a').click(function(e) {
            e.preventDefault();
            $(this).parent().toggleClass('expanded');
        })
    }

    // JS Menu Expands Run
    initJsExpands();
    ensureMenusAreClosed();

    // Responsive Search Behavior
    $("#goButtonResponsive").click(function() {
        var text = $("#search_field_responsive").val();
        if (text == "") {
            alert('Enter Search Keyword.');
            return;
        }

        $body = $("body");
        $body.addClass("loading");
        window.location.href = "/search_primo/all/" + text;
    });

    $("#search_field_responsive").keydown(function(event) {
        if (event.which == 13 && $("#search_field").val() != "") {
            event.preventDefault();
            $("#goButtonResponsive").trigger("click");
        } else if (event.which == 13 && $("#search_field_responsive").val() == "") {
            alert('Enter Search Keyword.');
        }
    });
});<commit_msg>Deploying changes<commit_after>// Use Primo Method to Check if this is a mobile device
window.onload = function() {
    try {
        (function(a) {
            (jQuery.browser = jQuery.browser || {}).mobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))
        })(navigator.userAgent || navigator.vendor || window.opera);
        if (($(window).width() <= 500 && jQuery.browser.mobile) || ('true' == getRequestParameterByName('debug_mobile'))) {
            $('body').addClass('mobile-device');
        }
    } catch (mobileErr) {
        log('JS changes for mobile failed:' + mobileErr);
    }
}

// .exists function for jQuery
$.fn.exists = function(callback) {
    var args = [].slice.call(arguments, 1);
    if (this.length) {
        callback.call(this, args);
    }
    return this;
};

$.fn.isMissing = function(callback) {
    var args = [].slice.call(arguments, 1);
    if (!this.length) {
        callback.call(this, args);
    }
    return this;
};

function isKorean() {
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function expandableMobileFacet(trigger_query, parent_query) {
    $(trigger_query).bind('click', function(e) {
        $(this).closest(parent_query).toggleClass('expanded-for-mobile');
        e.preventDefault();
    });
};

function initFilterExpand() {
    $("#exlidFacetTile").exists(function() {
        if (isKorean()) {
            $(this).prepend('

검색 필터

');
        } else {
            $(this).prepend('

Search Filters

');
        }
        expandableMobileFacet($(this).find(".filters-expand-title"), $(this));
    });
}

// Responsive Menu
$(document).ready(function() {
    var triggerBttn = $('#responsive-menu-trigger'),
        overlay = $('#responsive-menu-overlay'),
        closeBttn = overlay.find('button.overlay-close'),
        navigationHeader = $('#responsive-header');

    function toggleOverlay() {
        if (overlay.hasClass('open')) {
            overlay.removeClass('open');
            navigationHeader.removeClass('open');
            ensureMenusAreClosed();
        } else if (navigationHeader.hasClass('open')) {
            overlay.removeClass('open');
            navigationHeader.removeClass('open');
            ensureMenusAreClosed();
        } else {
            overlay.addClass('open');
            navigationHeader.addClass('open');
        }
    }

    triggerBttn.click(function() {
        toggleOverlay();
    });

    closeBttn.click(function() {
        toggleOverlay();
    });

    // Menu Expands
    function ensureMenusAreClosed() {
        var firstLevelItems = $('#responsive-menu-overlay nav > ul > li, #responsive-menu-overlay nav > div > ul > li');
        firstLevelItems.removeClass('expanded');
    }

    function initJsExpands() {
        var firstLevelItems = $('#responsive-menu-overlay nav > ul > li, #responsive-menu-overlay nav > div > ul > li'),
            secondLevelItems = $('#responsive-menu-overlay nav > ul > li > ul > li');

        firstLevelItems.each(function() {
            if ($(this).children('ul').length != 0) {
                $(this).addClass('is-expandable');
            }
        });

        // Remove any accidental third level
        secondLevelItems.each(function() {
            $(this).find('ul').remove();
        });

        // Bind the links to expand / collapse
        firstLevelItems.children('a').click(function(e) {
            e.preventDefault();
            $(this).parent().toggleClass('expanded');
        })
    }

    // JS Menu Expands Run
    initJsExpands();
    ensureMenusAreClosed();

    // Responsive Search Behavior
    $("#goButtonResponsive").click(function() {
        var text = $("#search_field_responsive").val();
        if (text == "") {
            alert('Enter Search Keyword.');
            return;
        }

        $body = $("body");
        $body.addClass("loading");
        window.location.href = "http://library.unist.ac.kr/search_primo/all/" + text;
    });

    $("#search_field_responsive").keydown(function(event) {
        if (event.which == 13 && $("#search_field").val() != "") {
            event.preventDefault();
            $("#goButtonResponsive").trigger("click");
        } else if (event.which == 13 && $("#search_field_responsive").val() == "") {
            alert('Enter Search Keyword.');
        }
    });
});<|endoftext|>


<commit_before>(function($){

	/* ---------------------------------------------- /*
	 * Preloader
	/* ---------------------------------------------- */

	$(window).load(function() {
		$('#status').fadeOut();
		$('#preloader').delay(300).fadeOut('slow');
	});

	$(document).ready(function() {

		/* ---------------------------------------------- /*
		 * Local Weather
		/* ---------------------------------------------- */

		getLocation();

		function getLocation() {
			$.get("http://ipinfo.io", function(location) {
				console.log(location);

				$('.location').html("How's the weather in good old " + location.city + "?");

				getWeather(location.city, location.region);
			}, "jsonp");
		}

		function getWeather(city, region) {
			var city = city; console.log(city);
			var state = getAbbreviation(region); console.log(state);

			function getAbbreviation(state) {
				var usStates = [
				    { name: 'ALABAMA', abbreviation: 'AL'},
				    { name: 'ALASKA', abbreviation: 'AK'},
				    { name: 'AMERICAN SAMOA', abbreviation: 'AS'},
				    { name: 'ARIZONA', abbreviation: 'AZ'},
				    { name: 'ARKANSAS', abbreviation: 'AR'},
				    { name: 'CALIFORNIA', abbreviation: 'CA'},
				    { name: 'COLORADO', abbreviation: 'CO'},
				    { name: 'CONNECTICUT', abbreviation: 'CT'},
				    { name: 'DELAWARE', abbreviation: 'DE'},
				    { name: 'DISTRICT OF COLUMBIA', abbreviation: 'DC'},
				    { name: 'FEDERATED STATES OF MICRONESIA', abbreviation: 'FM'},
				    { name: 'FLORIDA', abbreviation: 'FL'},
				    { name: 'GEORGIA', abbreviation: 'GA'},
				    { name: 'GUAM', abbreviation: 'GU'},
				    { name: 'HAWAII', abbreviation: 'HI'},
				    { name: 'IDAHO', abbreviation: 'ID'},
				    { name: 'ILLINOIS', abbreviation: 'IL'},
				    { name: 'INDIANA', abbreviation: 'IN'},
				    { name: 'IOWA', abbreviation: 'IA'},
				    { name: 'KANSAS', abbreviation: 'KS'},
				    { name: 'KENTUCKY', abbreviation: 'KY'},
				    { name: 'LOUISIANA', abbreviation: 'LA'},
				    { name: 'MAINE', abbreviation: 'ME'},
				    { name: 'MARSHALL ISLANDS', abbreviation: 'MH'},
				    { name: 'MARYLAND', abbreviation: 'MD'},
				    { name: 'MASSACHUSETTS', abbreviation: 'MA'},
				    { name: 'MICHIGAN', abbreviation: 'MI'},
				    { name: 'MINNESOTA', abbreviation: 'MN'},
				    { name: 'MISSISSIPPI', abbreviation: 'MS'},
				    { name: 'MISSOURI', abbreviation: 'MO'},
				    { name: 'MONTANA', abbreviation: 'MT'},
				    { name: 'NEBRASKA', abbreviation: 'NE'},
				    { name: 'NEVADA', abbreviation: 'NV'},
				    { name: 'NEW HAMPSHIRE', abbreviation: 'NH'},
				    { name: 'NEW JERSEY', abbreviation: 'NJ'},
				    { name: 'NEW MEXICO', abbreviation: 'NM'},
				    { name: 'NEW YORK', abbreviation: 'NY'},
				    { name: 'NORTH CAROLIN A', abbreviation: 'NC'},
				    { name: 'NORTH DAKOTA', abbreviation: 'ND'},
				    { name: 'NORTHERN MARIANA ISLANDS', abbreviation: 'MP'},
				    { name: 'OHIO', abbreviation: 'OH'},
				    { name: 'OKLAHOMA', abbreviation: 'OK'},
				    { name: 'OREGON', abbreviation: 'OR'},
				    { name: 'PALAU', abbreviation: 'PW'},
				    { name: 'PENNSYLVANIA', abbreviation: 'PA'},
				    { name: 'PUERTO RICO', abbreviation: 'PR'},
				    { name: 'RHODE ISLAND', abbreviation: 'RI'},
				    { name: 'SOUTH CAROLINA', abbreviation: 'SC'},
				    { name: 'SOUTH DAKOTA', abbreviation: 'SD'},
				    { name: 'TENNESSEE', abbreviation: 'TN'},
				    { name: 'TEXAS', abbreviation: 'TX'},
				    { name: 'UTAH', abbreviation: 'UT'},
				    { name: 'VERMONT', abbreviation: 'VT'},
				    { name: 'VIRGIN ISLANDS', abbreviation: 'VI'},
				    { name: 'VIRGINIA', abbreviation: 'VA'},
				    { name: 'WASHINGTON', abbreviation: 'WA'},
				    { name: 'WEST VIRGINIA', abbreviation: 'WV'},
				    { name: 'WISCONSIN', abbreviation: 'WI'},
				    { name: 'WYOMING', abbreviation: 'WY' }
				];
				usStates.find(function(obj) {
					return obj.name === state.toUpperCase();
				})
			}

			var weatherApiUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20item.condition.text%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + city + "%2C%20" + state + "%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

			$.get(weatherApiUrl, function(weather) {
				console.log(weather);
				debugger;
				$(".location").append(" " + weather.query.results.channel.item.condition.text + "?");

			}, "jsonp");
		}

		/* ---------------------------------------------- /*
		 * Smooth scroll / Scroll To Top
		/* ---------------------------------------------- */

		$('a[href*=#]').bind("click", function(e){

			var anchor = $(this);
			$('html, body').stop().animate({
				scrollTop: $(anchor.attr('href')).offset().top
			}, 1000);
			e.preventDefault();
		});

		$(window).scroll(function() {
			if ($(this).scrollTop() > 100) {
				$('.scroll-up').fadeIn();
			} else {
				$('.scroll-up').fadeOut();
			}
		});

		/* ---------------------------------------------- /*
		 * Navbar
		/* ---------------------------------------------- */

		$('.header').sticky({
			topSpacing: 0
		});

		$('body').scrollspy({
			target: '.navbar-custom',
			offset: 70
		})

        /* ---------------------------------------------- /*
		 * Skills
        /* ---------------------------------------------- */
        //var color = $('#home').css('backgroundColor');

        $('.skills').waypoint(function(){
            $('.chart').each(function(){
            $(this).easyPieChart({
                    size:140,
                    animate: 2000,
                    lineCap:'butt',
                    scaleColor: false,
                    barColor: '#FF5252',
                    trackColor: 'transparent',
                    lineWidth: 10
                });
            });
        },{offset:'80%'});

        /* ---------------------------------------------- /*
		 * Quote Rotator
		/* ---------------------------------------------- */

			$( function() {
				/*
				- how to call the plugin:
				$( selector ).cbpQTRotator( [options] );
				- options:
				{
					// default transition speed (ms)
					speed : 700,
					// default transition easing
					easing : 'ease',
					// rotator interval (ms)
					interval : 8000
				}
				- destroy:
				$( selector ).cbpQTRotator( 'destroy' );
				*/

				$( '#cbp-qtrotator' ).cbpQTRotator();

			} );

		/* ---------------------------------------------- /*
		 * Home BG
		/* ---------------------------------------------- */

		$(".screen-height").height($(window).height());

		$(window).resize(function(){
			$(".screen-height").height($(window).height());
		});

		if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
			$('#home').css({'background-attachment': 'scroll'});
		} else {
			$('#home').parallax('50%', 0.1);
		}

		/* ---------------------------------------------- /*
		 * WOW Animation When You Scroll
		/* ---------------------------------------------- */

		wow = new WOW({
			mobile: false
		});
		wow.init();

		/* ---------------------------------------------- /*
		 * E-mail validation
		/* ---------------------------------------------- */

		function isValidEmailAddress(emailAddress) {
			var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
			return pattern.test(emailAddress);
		};

		/* ---------------------------------------------- /*
		 * Contact form ajax
		/* ---------------------------------------------- */

		$('#contact-form').submit(function(e) {

			e.preventDefault();

			var c_name = $('#c_name').val();
			var c_email = $('#c_email').val();
			var c_message = $('#c_message ').val();
			var response = $('#contact-form .ajax-response');

			var formData = {
				'name'       : c_name,
				'email'      : c_email,
				'message'    : c_message
			};

			if (( c_name== '' || c_email == '' || c_message == '') || (!isValidEmailAddress(c_email) )) {
				response.fadeIn(500);
				response.html(' Please fix the errors and try again.');
			}

			else {
					 $.ajax({
							type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
							url         : 'assets/php/contact.php', // the url where we want to POST '//formspree.io/you@email.com'
							data        : formData, // our data object
							dataType    : 'json', // what type of data do we expect back from the server
							encode      : true,
							success		: function(res){
											var ret = $.parseJSON(JSON.stringify(res));
											response.html(ret.message).fadeIn(500);
							}
						});
				}
            	return false;
			});

	});

})(jQuery);
<commit_msg>Add lightbox js<commit_after>(function($){

	/* ---------------------------------------------- /*
	 * Preloader
	/* ---------------------------------------------- */

	$(window).load(function() {
		$('#status').fadeOut();
		$('#preloader').delay(300).fadeOut('slow');
	});

	$(document).ready(function() {

		/* ---------------------------------------------- /*
		 * Lightbox
		/* ---------------------------------------------- */

		$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
		    event.preventDefault();
		    $(this).ekkoLightbox();
		});

		/* ---------------------------------------------- /*
		 * Local Weather
		/* ---------------------------------------------- */

		getLocation();

		function getLocation() {
			$.get("http://ipinfo.io", function(location) {

				$('.location').html("How's the weather in good old " + location.city + "?");

				getWeather(location.city, location.region);
			}, "jsonp");
		}

		function getWeather(city, region) {
			var city = city;
			var state = getAbbreviation(region);

			function getAbbreviation(state) {
				var usStates = [
				    { name: 'ALABAMA', abbreviation: 'AL'},
				    { name: 'ALASKA', abbreviation: 'AK'},
				    { name: 'AMERICAN SAMOA', abbreviation: 'AS'},
				    { name: 'ARIZONA', abbreviation: 'AZ'},
				    { name: 'ARKANSAS', abbreviation: 'AR'},
				    { name: 'CALIFORNIA', abbreviation: 'CA'},
				    { name: 'COLORADO', abbreviation: 'CO'},
				    { name: 'CONNECTICUT', abbreviation: 'CT'},
				    { name: 'DELAWARE', abbreviation: 'DE'},
				    { name: 'DISTRICT OF COLUMBIA', abbreviation: 'DC'},
				    { name: 'FEDERATED STATES OF MICRONESIA', abbreviation: 'FM'},
				    { name: 'FLORIDA', abbreviation: 'FL'},
				    { name: 'GEORGIA', abbreviation: 'GA'},
				    { name: 'GUAM', abbreviation: 'GU'},
				    { name: 'HAWAII', abbreviation: 'HI'},
				    { name: 'IDAHO', abbreviation: 'ID'},
				    { name: 'ILLINOIS', abbreviation: 'IL'},
				    { name: 'INDIANA', abbreviation: 'IN'},
				    { name: 'IOWA', abbreviation: 'IA'},
				    { name: 'KANSAS', abbreviation: 'KS'},
				    { name: 'KENTUCKY', abbreviation: 'KY'},
				    { name: 'LOUISIANA', abbreviation: 'LA'},
				    { name: 'MAINE', abbreviation: 'ME'},
				    { name: 'MARSHALL ISLANDS', abbreviation: 'MH'},
				    { name: 'MARYLAND', abbreviation: 'MD'},
				    { name: 'MASSACHUSETTS', abbreviation: 'MA'},
				    { name: 'MICHIGAN', abbreviation: 'MI'},
				    { name: 'MINNESOTA', abbreviation: 'MN'},
				    { name: 'MISSISSIPPI', abbreviation: 'MS'},
				    { name: 'MISSOURI', abbreviation: 'MO'},
				    { name: 'MONTANA', abbreviation: 'MT'},
				    { name: 'NEBRASKA', abbreviation: 'NE'},
				    { name: 'NEVADA', abbreviation: 'NV'},
				    { name: 'NEW HAMPSHIRE', abbreviation: 'NH'},
				    { name: 'NEW JERSEY', abbreviation: 'NJ'},
				    { name: 'NEW MEXICO', abbreviation: 'NM'},
				    { name: 'NEW YORK', abbreviation: 'NY'},
				    { name: 'NORTH CAROLIN A', abbreviation: 'NC'},
				    { name: 'NORTH DAKOTA', abbreviation: 'ND'},
				    { name: 'NORTHERN MARIANA ISLANDS', abbreviation: 'MP'},
				    { name: 'OHIO', abbreviation: 'OH'},
				    { name: 'OKLAHOMA', abbreviation: 'OK'},
				    { name: 'OREGON', abbreviation: 'OR'},
				    { name: 'PALAU', abbreviation: 'PW'},
				    { name: 'PENNSYLVANIA', abbreviation: 'PA'},
				    { name: 'PUERTO RICO', abbreviation: 'PR'},
				    { name: 'RHODE ISLAND', abbreviation: 'RI'},
				    { name: 'SOUTH CAROLINA', abbreviation: 'SC'},
				    { name: 'SOUTH DAKOTA', abbreviation: 'SD'},
				    { name: 'TENNESSEE', abbreviation: 'TN'},
				    { name: 'TEXAS', abbreviation: 'TX'},
				    { name: 'UTAH', abbreviation: 'UT'},
				    { name: 'VERMONT', abbreviation: 'VT'},
				    { name: 'VIRGIN ISLANDS', abbreviation: 'VI'},
				    { name: 'VIRGINIA', abbreviation: 'VA'},
				    { name: 'WASHINGTON', abbreviation: 'WA'},
				    { name: 'WEST VIRGINIA', abbreviation: 'WV'},
				    { name: 'WISCONSIN', abbreviation: 'WI'},
				    { name: 'WYOMING', abbreviation: 'WY' }
				];
				usStates.find(function(obj) {
					return obj.name === state.toUpperCase();
				})
			}

			var weatherApiUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20item.condition.text%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" + city + "%2C%20" + state + "%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

			$.get(weatherApiUrl, function(weather) {

				$(".location").append(" " + weather.query.results.channel.item.condition.text + "?");

			}, "jsonp");
		}

		/* ---------------------------------------------- /*
		 * Smooth scroll / Scroll To Top
		/* ---------------------------------------------- */

		$('a[href*=#]').bind("click", function(e){

			var anchor = $(this);
			$('html, body').stop().animate({
				scrollTop: $(anchor.attr('href')).offset().top
			}, 1000);
			e.preventDefault();
		});

		$(window).scroll(function() {
			if ($(this).scrollTop() > 100) {
				$('.scroll-up').fadeIn();
			} else {
				$('.scroll-up').fadeOut();
			}
		});

		/* ---------------------------------------------- /*
		 * Navbar
		/* ---------------------------------------------- */

		$('.header').sticky({
			topSpacing: 0
		});

		$('body').scrollspy({
			target: '.navbar-custom',
			offset: 70
		})

        /* ---------------------------------------------- /*
		 * Skills
        /* ---------------------------------------------- */
        //var color = $('#home').css('backgroundColor');

        $('.skills').waypoint(function(){
            $('.chart').each(function(){
            $(this).easyPieChart({
                    size:140,
                    animate: 2000,
                    lineCap:'butt',
                    scaleColor: false,
                    barColor: '#FF5252',
                    trackColor: 'transparent',
                    lineWidth: 10
                });
            });
        },{offset:'80%'});

        /* ---------------------------------------------- /*
		 * Quote Rotator
		/* ---------------------------------------------- */

			$( function() {
				/*
				- how to call the plugin:
				$( selector ).cbpQTRotator( [options] );
				- options:
				{
					// default transition speed (ms)
					speed : 700,
					// default transition easing
					easing : 'ease',
					// rotator interval (ms)
					interval : 8000
				}
				- destroy:
				$( selector ).cbpQTRotator( 'destroy' );
				*/

				$( '#cbp-qtrotator' ).cbpQTRotator();

			} );

		/* ---------------------------------------------- /*
		 * Home BG
		/* ---------------------------------------------- */

		$(".screen-height").height($(window).height());

		$(window).resize(function(){
			$(".screen-height").height($(window).height());
		});

		if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
			$('#home').css({'background-attachment': 'scroll'});
		} else {
			$('#home').parallax('50%', 0.1);
		}

		/* ---------------------------------------------- /*
		 * WOW Animation When You Scroll
		/* ---------------------------------------------- */

		wow = new WOW({
			mobile: false
		});
		wow.init();

		/* ---------------------------------------------- /*
		 * E-mail validation
		/* ---------------------------------------------- */

		function isValidEmailAddress(emailAddress) {
			var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
			return pattern.test(emailAddress);
		};

		/* ---------------------------------------------- /*
		 * Contact form ajax
		/* ---------------------------------------------- */

		$('#contact-form').submit(function(e) {

			e.preventDefault();

			var c_name = $('#c_name').val();
			var c_email = $('#c_email').val();
			var c_message = $('#c_message ').val();
			var response = $('#contact-form .ajax-response');

			var formData = {
				'name'       : c_name,
				'email'      : c_email,
				'message'    : c_message
			};

			if (( c_name== '' || c_email == '' || c_message == '') || (!isValidEmailAddress(c_email) )) {
				response.fadeIn(500);
				response.html(' Please fix the errors and try again.');
			}

			else {
					 $.ajax({
							type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
							url         : 'assets/php/contact.php', // the url where we want to POST '//formspree.io/you@email.com'
							data        : formData, // our data object
							dataType    : 'json', // what type of data do we expect back from the server
							encode      : true,
							success		: function(res){
											var ret = $.parseJSON(JSON.stringify(res));
											response.html(ret.message).fadeIn(500);
							}
						});
				}
            	return false;
			});

	});

})(jQuery);
<|endoftext|>


<commit_before>// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

/*
    Usage
    ------
    Four parameters you can use:
    'parent'     = parent element object or id
    'wrapper_id' = the attribute that you need this innerwrapped element to have

    Example
    -------
    wrapInner(parent, 'wrapper_id');
*/

function wrapInner(parent, wrapperID) {
    wrapper = document.createElement('div');
    wrapper.setAttribute('id', wrapperID);
    wrapper.className = wrapperID
    if (typeof parent === "string") { parent = document.getElementById(parent); }
    var div = parent.appendChild(wrapper);
    while (parent.firstChild !== wrapper) {
        wrapper.appendChild(parent.firstChild);
    }
}

function initResponsiveHeader() {
    responsiveHeaderHTML = '\
     \

 \

 \

SNUL
 \

 \

 \

 \
                     \

 \

User Login
 \

 \

 \
    ';
    responsiveHeader = $(responsiveHeaderHTML);
    headerContainer = $('#header');
    responsiveHeader.insertAfter(headerContainer);
}

function initResponsiveContainers() {
    scrollerContainerID = "scroller";
    naviPusherID = "navi-pusher";
    responsiveContainerID = "responsive-container";
    // initiate contstruction
    wrapInner(document.body, responsiveContainerID);
    wrapInner(responsiveContainerID, naviPusherID);
    wrapInner(naviPusherID, scrollerContainerID);
    $('').insertBefore("#" + scrollerContainerID);
}

function isKorean(){
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function convertResponsiveMenu(desktopMenu) {
    // Initial Variables
    menuContainer    = $('#responsive-menu');
    responsiveMenu   = desktopMenu.clone();
    menuLevelDiv     = '

';
    firstLevelItems  = responsiveMenu.children('li');
    submenuTitleDiv  = '

';
    backButtonAnchor = 'back';

    // Responsive id and navi menu class
    responsiveMenu.attr('id', "responsive-menu-main");

    // First level
    menuContainer.append($('
Main Menu
'));

    // Second level
    firstLevelItems.each(function(index) {
        title = $(this).children('a').first();
        $(backButtonAnchor).insertAfter(title);
        $(submenuTitleDiv).append(title.text()).insertAfter(title);
        $(this).wrapInner(menuLevelDiv);
        $(this).prepend(title);
    });

    // Combine Levels
    menuContainer.append(responsiveMenu);
    menuContainer.wrapInner(menuLevelDiv);

    return menuContainer;
}

function initResponsiveMenu(callback) {
    if (isKorean()) {
        convertResponsiveMenu($('#korean-main-navigation'));
    } else {
        convertResponsiveMenu($('#english-main-menu'));
    }

    callback();
}

$(document).ready(function () {
    // Responsive Header
    initResponsiveHeader();
    // Responsive Containers
    initResponsiveContainers();
    // Responsive Menu
    initResponsiveMenu(function() {
        new pushMenu(document.getElementById('responsive-menu'), document.getElementById('responsive-menu-trigger'), {
            type: 'cover'
        });
    });
});<commit_msg>Deploying changes<commit_after>// Wrap an HTMLElement around each element in an HTMLElement array.
HTMLElement.prototype.wrap = function(elms) {
    // Convert `elms` to an array, if necessary.
    if (!elms.length) elms = [elms];

    // Loops backwards to prevent having to clone the wrapper on the
    // first element (see `child` below).
    for (var i = elms.length - 1; i >= 0; i--) {
        var child = (i > 0) ? this.cloneNode(true) : this;
        var el    = elms[i];

        // Cache the current parent and sibling.
        var parent  = el.parentNode;
        var sibling = el.nextSibling;

        // Wrap the element (is automatically removed from its current
        // parent).
        child.appendChild(el);

        // If the element had a sibling, insert the wrapper before
        // the sibling to maintain the HTML structure; otherwise, just
        // append it to the parent.
        if (sibling) {
            parent.insertBefore(child, sibling);
        } else {
            parent.appendChild(child);
        }
    }
};

/*
    Usage
    ------
    Four parameters you can use:
    'parent'     = parent element object or id
    'wrapper_id' = the attribute that you need this innerwrapped element to have

    Example
    -------
    wrapInner(parent, 'wrapper_id');
*/

function wrapInner(parent, wrapperID) {
    wrapper = document.createElement('div');
    wrapper.setAttribute('id', wrapperID);
    wrapper.className = wrapperID
    if (typeof parent === "string") { parent = document.getElementById(parent); }
    var div = parent.appendChild(wrapper);
    while (parent.firstChild !== wrapper) {
        wrapper.appendChild(parent.firstChild);
    }
}

function initResponsiveHeader() {
    responsiveHeaderHTML = '\
     \

 \

 \

SNUL
 \

 \

 \

 \
                     \

 \

User Login
 \

 \

 \
    ';
    responsiveHeader = $(responsiveHeaderHTML);
    headerContainer = $('#header');
    responsiveHeader.insertAfter(headerContainer);
}

function initResponsiveContainers() {
    scrollerContainerID = "scroller";
    naviPusherID = "navi-pusher";
    responsiveContainerID = "responsive-container";
    // initiate contstruction
    wrapInner(document.body, responsiveContainerID);
    wrapInner(responsiveContainerID, naviPusherID);
    wrapInner(naviPusherID, scrollerContainerID);
    $('').insertBefore("#" + scrollerContainerID);
}

function isKorean(){
    return $('body').hasClass('EXLCurrentLang_ko_KR');
}

function convertResponsiveMenu(desktopMenu) {
    // Initial Variables
    menuContainer    = $('#responsive-menu');
    responsiveMenu   = desktopMenu.clone();
    menuLevelDiv     = '

';
    firstLevelItems  = responsiveMenu.children('li');
    submenuTitleDiv  = '

';
    backButtonAnchor = 'back';

    // Responsive id and navi menu class
    responsiveMenu.attr('id', "responsive-menu-main");

    // First level
    menuContainer.append($('
Main Menu
'));

    // Second level
    firstLevelItems.each(function(index) {
        title = $(this).children('a').first();
        $(backButtonAnchor).insertAfter(title);
        $(submenuTitleDiv).append(title.text()).insertAfter(title);
        menuLevelDiv.attr('data-level', "2");
        $(this).wrapInner(menuLevelDiv);
        $(this).prepend(title);
    });

    // Combine Levels
    menuContainer.append(responsiveMenu);
    menuContainer.wrapInner(menuLevelDiv);

    return menuContainer;
}

function initResponsiveMenu(callback) {
    if (isKorean()) {
        convertResponsiveMenu($('#korean-main-navigation'));
    } else {
        convertResponsiveMenu($('#english-main-menu'));
    }

    callback();
}

$(document).ready(function () {
    // Responsive Header
    initResponsiveHeader();
    // Responsive Containers
    initResponsiveContainers();
    // Responsive Menu
    initResponsiveMenu(function() {
        new pushMenu(document.getElementById('responsive-menu'), document.getElementById('responsive-menu-trigger'), {
            type: 'cover'
        });
    });
});<|endoftext|>


<commit_before>// If rooms list exists, let's populate it.
if ($('.rooms-list').length > 0) {
    $.getJSON('/rooms', function (data) {
        var items = [];
        $.each(data.rooms, function(index, room) {
            items.push('
'+room.name+'
');
        });
        $('.rooms-list').html(items);
    });
}

// If groups list exists, let's populate it.
if ($('.groups-list').length > 0) {
    $.getJSON('/groups', function (data) {
        var items = [];
        $.each(data.groups, function(index, group) {
            items.push('
'+group.name+'
');
        });
        $('.groups-list').html(items);
    });
}

// Highlight the current nav item
$('.nav-stacked a[href="'+window.location.pathname+'"]').parent('li').addClass('active');
<commit_msg>Add default contents to rooms and groups list when empty.<commit_after>var emptyList = '

No results found

';

// If rooms list exists, let's populate it.
if ($('.rooms-list').length > 0) {
    $.getJSON('/rooms', function (data) {
        var items = [];
        $.each(data.rooms, function(index, room) {
            items.push('
'+room.name+'
');
        });
        if (items.length > 0) {
            $('.rooms-list').html(items);
        } else {
            $('.rooms-list').html(emptyList);
        }
    }).fail(function (err) {
        $('.rooms-list').html(emptyList);
    });
}

// If groups list exists, let's populate it.
if ($('.groups-list').length > 0) {
    $.getJSON('/groups', function (data) {
        var items = [];
        $.each(data.groups, function(index, group) {
            items.push('
'+group.name+'
');
        });
        if (items.length > 0) {
            $('.groups-list').html(items);
        } else {
            $('.groups-list').html(emptyList);
        }
    }).fail(function (err) {
        $('.groups-list').html(emptyList);
    });
}

// Highlight the current nav item
$('.nav-stacked a[href="'+window.location.pathname+'"]').parent('li').addClass('active');
<|endoftext|>


<commit_before>/**
 * Handles loading slides from JSON using AngularJS
 */

// Assuming this script is loaded synchronous (not async)
// Reliably grab current running script tag
var config;
var scripts;
var script = document.currentScript;
if (!script) {
    scripts = document.getElementsByTagName("script");
    script = script[scripts.length - 1];
}

// Initialize our containers on the global RevealJS object
Reveal.Revealular = {};
Reveal.Revealular.config = {};

// Check for an attribute/config
if (script.hasAttribute("data-ext")) {
	// Parse it
	Reveal.Revealular.config.ext = script.getAttribute("data-ext");
}
if (script.hasAttribute("data-slides")) {
	// Parse it
	Reveal.Revealular.config.slides = script.getAttribute("data-slides");
}
if (script.hasAttribute("data-init")) {
	// Parse it
	Reveal.Revealular.config.init = script.getAttribute("data-init");
}

var Revealular = (function () {
    var app = angular.module("revealular", []);

    function parseUrl (url) {
        var loc = window.location;
        var a = document.createElement("a");
        a.href = url;

        var parsed = {
            href : a.href,
            host : a.host,
            hostname : a.hostname,
            port : a.port || "", // Avoid "0" ports for local URL's - Safari 5.1
            pathname : a.pathname,
            protocol : a.protocol,
            hash : a.hash,
            search : a.search
        };

        if (":" === a.protocol) { // Avoid empty "hostname", "port" & "protocol" for local URL's - IE
            parsed.host = loc.host;
            parsed.hostname = lc.hostname;
            parsed.port = loc.port;
            parsed.protocol = loc.protocol;
        }

        a = null;

        return parsed;
    };

    function isSameOrigin (url) {
        var loc = window.location;
        var parsed = parseUrl(url);

        return parsed.hostname === loc.hostname && parsed.port === loc.port && parsed.protocol === loc.protocol;
    };

    function parseStep (sce, step, elem) {
        step = step || "";
        if (!elem) {
            elem = angular.element("<section>");
        }
        if ("string" === typeof step) {
            elem.html(step);
        }
        else if (step) {
            for (var i = 0; i < step.length; i++) {
                var item = step[i];
                if (item && "object" === typeof item) {
                    var source = item.name;
                    if ("notes" === source.toLowerCase()) {
                        var additionalData = "";
                        if (item.attributes && true === item.attributes.trim) {
                          additionalData = " data-trim=\"true\"";
                        }
                        var notes = angular.element(sce.trustAsHtml("<aside class=\"notes\"" + additionalData + ">").toString());
                        if (item.value.join) {
                            notes.html(item.value.join("\n"));
                        }
                        else {
                            notes.html(item.value);
                        }
                        elem.append(notes);
                    }
                    else {
                        if (item.attributes) {
                            for (var attr in item.attributes) {
                                if (attr && item.attributes.hasOwnProperty(attr)) {
                                    source += " " + attr + "=\"" + item.attributes[attr] + "\"";
                                }
                            }
                        }
                        var html = sce.trustAsHtml("<" + source + ">").toString();
                        var subElem = angular.element(html);
                        parseStep(sce, item.value, subElem);
                        elem.append(subElem);
                    }
                }
                else if (item && "string" === typeof item) {
                    elem.html(item);
                }
            }
        }

        return elem;
    }

    function addScript (js, scope, q) {
        var deferred = q.defer();

        // Inject js into a script tag
        var script = document.createElement("script");

        script.setAttribute("type", "text/javascript");
        script.setAttribute("async", true);
        script.setAttribute("src", encodeURI(js));
        script.setAttribute("onload", function () {
            // The script is ready for use, resolve promise
            scope.$apply(deferred.resolve());
        });

        document.body.appendChild(script);

        return deferred.promise;
    }

    app.controller("RevealularController", function ($scope, $http) {
        $scope.slides = [];
    });

    app.directive("slideshow", function ($http, $sce, $q) {
        return {
            scope : {
                slides : "=slideshow"
            },
            link : function (scope, elem, attrs) {
                var query = Reveal.getQueryHash();
                var ext = (query.ext || Reveal.Revealular.config.ext || ".json");
                var slides = (query.slides || Reveal.Revealular.config.slides || "slides") + ext;
                var init = (query.init || Reveal.Revealular.config.init || "init") + ".js";
                var local = isSameOrigin(slides);
                var action = local ? "get" : "jsonp";
                var deferred = new $q.defer();

                elem.addClass("slides");

                if (!local) {
                    Reveal.Revealular.gotSlides = function (data) {
                        deferred.resolve({ data : data });
                    };
                    slides += "?callback=Reveal.Revealular.gotSlides"
                }

                deferred.promise.then(function (res, status, headers, config) {
                        scope.slides = res.data;

                        if (scope.slides) {
                            for (var i = 0; i < scope.slides.length; i++) {
                                var steps = scope.slides[i].steps;
                                var section;

                                if (1 === steps.length) {
                                    section = parseStep($sce, steps[0]);
                                }
                                else {
                                    section = angular.element("<section>");
                                    for (var j = 0; j < steps.length; j++) {
                                        var subSection = parseStep($sce, steps[j]);
                                        section.append(subSection);
                                    }
                                }

                                if (section) {
                                    elem.append(section);
                                }
                            }

                            addScript(init, scope, $q).then(function (res) {
                                    // Initialize script loaded!
                                }, function (res) {
                                    scope.error = true;
                                });
                        }
                    }, function (res, status, headers, config) {
                        scope.error = true;
                    });

                // Get the slides
                $http[action](slides).then(function (res) {
                        deferred.resolve(res);
                    }, function (error) {
                        deferred.reject(error);
                    });
            }
        };
    });

})();
<commit_msg>Update revealular.js<commit_after>/**
 * Handles loading slides from JSON using AngularJS
 */

// Assuming this script is loaded synchronous (not async)
// Reliably grab current running script tag
var config;
var scripts;
var script = document.currentScript;
if (!script) {
    scripts = document.getElementsByTagName("script");
    script = script[scripts.length - 1];
}

// Initialize our containers on the global RevealJS object
Reveal.Revealular = {};
Reveal.Revealular.config = {};

// Check for an attribute/config
if (script.hasAttribute("data-ext")) {
	// Parse it
	Reveal.Revealular.config.ext = script.getAttribute("data-ext");
}
if (script.hasAttribute("data-slides")) {
	// Parse it
	Reveal.Revealular.config.slides = script.getAttribute("data-slides");
}
if (script.hasAttribute("data-init")) {
	// Parse it
	Reveal.Revealular.config.init = script.getAttribute("data-init");
}

var Revealular = (function () {
    var app = angular.module("revealular", []);

    function parseUrl (url) {
        var loc = window.location;
        var a = document.createElement("a");
        a.href = url;

        var parsed = {
            href : a.href,
            host : a.host,
            hostname : a.hostname,
            port : a.port || "", // Avoid "0" ports for local URL's - Safari 5.1
            pathname : a.pathname,
            protocol : a.protocol,
            hash : a.hash,
            search : a.search
        };

        if (":" === a.protocol) { // Avoid empty "hostname", "port" & "protocol" for local URL's - IE
            parsed.host = loc.host;
            parsed.hostname = lc.hostname;
            parsed.port = loc.port;
            parsed.protocol = loc.protocol;
        }

        a = null;

        return parsed;
    };

    function isSameOrigin (url) {
        var loc = window.location;
        var parsed = parseUrl(url);

        return parsed.hostname === loc.hostname && parsed.port === loc.port && parsed.protocol === loc.protocol;
    };

    function parseStep (sce, step, elem) {
        step = step || "";
        if (!elem) {
            elem = angular.element("<section>");
        }
        if ("string" === typeof step) {
            elem.html(step);
        }
        else if (step) {
            for (var i = 0; i < step.length; i++) {
                var item = step[i];
                if (item && "object" === typeof item) {
                    var source = item.name;
                    if ("notes" === source.toLowerCase()) {
                        var additionalData = "";
                        if (item.attributes && true === item.attributes.trim) {
                            additionalData = " data-trim=\"true\"";
                        }
                        var notes = angular.element(sce.trustAsHtml("<aside class=\"notes\"" + additionalData + ">").toString());
                        if (item.value.join) {
                            notes.html(item.value.join("\n"));
                        }
                        else {
                            notes.html(item.value);
                        }
                        elem.append(notes);
                    }
                    else {
                        if (item.attributes) {
                            for (var attr in item.attributes) {
                                if (attr && item.attributes.hasOwnProperty(attr)) {
                                    source += " " + attr + "=\"" + item.attributes[attr] + "\"";
                                }
                            }
                        }
                        var html = sce.trustAsHtml("<" + source + ">").toString();
                        var subElem = angular.element(html);
                        parseStep(sce, item.value, subElem);
                        elem.append(subElem);
                    }
                }
                else if (item && "string" === typeof item) {
                    elem.html(item);
                }
            }
        }

        return elem;
    }

    function addScript (js, scope, q) {
        var deferred = q.defer();

        // Inject js into a script tag
        var script = document.createElement("script");

        script.setAttribute("type", "text/javascript");
        script.setAttribute("async", true);
        script.setAttribute("src", encodeURI(js));
        script.setAttribute("onload", function () {
            // The script is ready for use, resolve promise
            scope.$apply(deferred.resolve());
        });

        document.body.appendChild(script);

        return deferred.promise;
    }

    app.controller("RevealularController", function ($scope, $http) {
        $scope.slides = [];
    });

    app.directive("slideshow", function ($http, $sce, $q) {
        return {
            scope : {
                slides : "=slideshow"
            },
            link : function (scope, elem, attrs) {
                var query = Reveal.getQueryHash();
                var ext = (query.ext || Reveal.Revealular.config.ext || ".json");
                var slides = (query.slides || Reveal.Revealular.config.slides || "slides") + ext;
                var init = (query.init || Reveal.Revealular.config.init || "init") + ".js";
                var local = isSameOrigin(slides);
                var action = local ? "get" : "jsonp";
                var deferred = new $q.defer();

                elem.addClass("slides");

                if (!local) {
                    Reveal.Revealular.gotSlides = function (data) {
                        deferred.resolve({ data : data });
                    };
                    slides += "?callback=Reveal.Revealular.gotSlides"
                }

                deferred.promise.then(function (res, status, headers, config) {
                        scope.slides = res.data;

                        if (scope.slides) {
                            for (var i = 0; i < scope.slides.length; i++) {
                                var steps = scope.slides[i].steps;
                                var section;

                                if (1 === steps.length) {
                                    section = parseStep($sce, steps[0]);
                                }
                                else {
                                    section = angular.element("<section>");
                                    for (var j = 0; j < steps.length; j++) {
                                        var subSection = parseStep($sce, steps[j]);
                                        section.append(subSection);
                                    }
                                }

                                if (section) {
                                    elem.append(section);
                                }
                            }

                            addScript(init, scope, $q).then(function (res) {
                                    // Initialize script loaded!
                                }, function (res) {
                                    scope.error = true;
                                });
                        }
                    }, function (res, status, headers, config) {
                        scope.error = true;
                    });

                // Get the slides
                $http[action](slides).then(function (res) {
                        deferred.resolve(res);
                    }, function (error) {
                        deferred.reject(error);
                    });
            }
        };
    });

})();
<|endoftext|>