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

var _paramValueEverywhere = ['depth', 'count', 'forbidden_uris[]', 'filter', 'bss_stands'];
var _collections = [
    'addresses', 'commercial_modes', 'companies', 'contributors', 'coord', 'coverage',
    'datasets', 'disruptions', 'lines', 'networks', 'places', 'poi_types', 'pois',
    'physical_modes', 'routes', 'stop_areas', 'stop_points', 'vehicle_journeys'].sort();
var _additionalFeatures = ['departures', 'journeys', 'places_nearby', 'pt_objects', 'route_schedules', 'stop_schedules',
                            'arrivals', 'isochrones', 'heat_maps'];
var _paramJourneyCommon = ['from', 'to', 'datetime','traveler_type', 'data_freshness',
            'first_section_mode[]', 'last_section_mode[]'].concat(_paramValueEverywhere).sort();

// ParamKey
var _depArrParams = ['from_datetime', 'duration', 'data_freshness'].concat(_paramValueEverywhere).sort();
var _schedulesParams = ['from_datetime', 'duration', 'items_per_schedule', 'data_freshness'].concat(_paramValueEverywhere).sort();
var _placesParams = ['q', 'type[]', 'admin_uri[]'].concat(_paramValueEverywhere).sort();

// ParamValue
var _fallbackMode = ['walking', 'car', 'bike', 'bss'].sort();
var _booleanValues = ['true', 'false'];

var autocomplete = {
    autocompleteTree: {
        pathKey: {
            empty : ['coverage', 'places', 'coord'],
            all : _collections,
        },
        features: {
            all: _collections.concat(_additionalFeatures).sort(),
        },
        paramKey: {
            arrivals: _depArrParams,
            coord: _paramValueEverywhere,
            coverage: _paramValueEverywhere,
            departures: _depArrParams,
            journeys: ['datetime_represents'].concat(_paramJourneyCommon).sort(),
            isochrones: [ 'max_duration', 'min_duration', 'boundary_duration[]'].concat(_paramJourneyCommon).sort(),
            heat_maps: [ 'max_duration', 'resolution'].concat(_paramJourneyCommon).sort(),
            lines: _paramValueEverywhere,
            places_nearby: _placesParams.sort(),
            places: _placesParams,
            pois: ['distance'].concat(_paramValueEverywhere).sort(),
            pt_objects: ['q', 'type[]'].concat(_paramValueEverywhere),
            stop_areas: _paramValueEverywhere,
            stop_points: _paramValueEverywhere,
            routes: _paramValueEverywhere,
            route_schedules: _schedulesParams,
            stop_schedules: _schedulesParams,
            empty: _paramValueEverywhere,
        },
        paramValue : {
            traveler_type : ['luggage', 'standard', 'fast_walker', 'slow_walker'],
            datetime_represents : ['arrival', 'departure'],
            data_freshness: ['base_schedule', 'adapted_schedule', 'realtime'],
            debug: _booleanValues,
            wheelchair: _booleanValues,
            disable_geojson: _booleanValues,
            bss_stands: _booleanValues,
            'first_section_mode[]': _fallbackMode,
            'last_section_mode[]': _fallbackMode,
        }
    },
    apiAutocomplete: function() {
        var input = $("#api input.api");
        var apis = storage.getApis();
        autocomplete._customAutocompleteHelper(input, apis, {
            close: setSaveTokenButtonStatus,
            focus: setSaveTokenButtonStatus,
            select: function (event, ui) {
                $(input).val(ui.item.value);
                $("#token input.token").val(storage.getToken(ui.item.value));
            }
        });
    },
    valueAutoComplete: function (input, key) {
        if (isDatetimeType(key)) {
            autocomplete._makeDatetime(input);
        } else if (key in this.autocompleteTree.paramValue){
            autocomplete._customAutocompleteHelper(input, this.autocompleteTree.paramValue[key]);
        } else if (this.staticAutocompleteTypes.indexOf(key) > -1) {
            this.staticAutocomplete(input, key);
        } else if (this.dynamicAutocompleteTypes.indexOf(key) > -1) {
            this.dynamicAutocomplete(input, key);
        }
    },
    addKeyAutocomplete: function(input, type) {
        var source;
        if (type === 'pathKey' && ! $('#pathFrame').find('.value').length) {
            source = this.autocompleteTree[type].empty;
        } else if (type === 'paramKey'){
            var feature = $('#featureInput').val();
            source = this.autocompleteTree[type][feature] || this.autocompleteTree[type].empty;
        } else {
            source = this.autocompleteTree[type].all;
        }
        source = source || [];
        autocomplete._customAutocompleteHelper(input, source,
            {
                select: function(event, ui) { $(input).val(ui.item.value).change(); }
            });
    },
    staticAutocompleteTypes: [
        'coverage',
        'physical_modes',
        'poi_types',
    ],
    staticAutocomplete: function(input, staticType) {
        var old_request = '';
        var old_token = '';
        var handle = function() {
            var api = $('#api input.api').val();
            var token = $('#token input.token').val();
            var cov = getCoverage();
            var request = api +  '/coverage/';
            if (staticType !== 'coverage') {
                request +=  cov + '/' + staticType;
            }
            request += '?disable_geojson=true'
            if (request !== old_request || token !== old_token) {
                old_request = request;
                old_token = token;
                autocomplete.updateStaticAutocomplete(input, staticType, request, token);
            } else if ($(input).is(':focus') && $(input).autocomplete('instance')) {
                $(input).autocomplete('search', '');
            }

        };
        handle();
        $(input).focus(handle);
    },
    updateStaticAutocomplete: function(input, staticType, request, token) {
        if ($(input).autocomplete('instance')) {
            // be shure that out-of-date autocompletion will not be active
            $(input).autocomplete('destroy');
        }
        $.ajax({
            headers: manageToken(token),
            dataType: 'json',
            url: request,
            success: function(data) {
                var res = [];
                staticType = (staticType==='coverage') ? 'regions' :  staticType;
                data[staticType].forEach(function(elt) {
                    var s = summary.run(new response.Context(data), getType(staticType), elt);
                    res.push({ value: elt.id, label: s.textContent, desc: s });
                });
                res = res.sort(function(a, b) {
                    if (a.label < b.label) { return -1; }
                    if (a.label > b.label) { return 1; }
                    return 0;
                });
                $(input).autocomplete({
                    close: function() { updateUrl($(input)[0]); },
                    focus: function() { updateUrl($(input)[0]); },
                    source: res,
                    minLength: 0,
                    scroll: true,
                    delay: 500
                }).autocomplete('instance')._renderItem = function(ul, item) {
                    return $('<li>').append(item.desc).appendTo(ul);
                };
                $(input).autocomplete('enable');
                if ($(input).is(':focus') && $(input).autocomplete('instance')) {
                    $(input).autocomplete('search', '');
                }
            },
            error: function(data, status, xhr) {
                notifyOnError(data, 'Autocomplete');
            }
        });
    },
    dynamicAutocompleteTypes: [
        'addresses',
        'administrative_regions',
        'commercial_modes',
        'coord',
        'forbidden_uris[]',
        'lines',
        'networks',
        'places',
        'pois',
        'routes',
        'stop_areas',
        'stop_points',
        'from',
        'to',
    ],
    dynamicAutocomplete: function (elt, dynamicType) {
        var formatPtReq = function (v){
            return sprintf('pt_objects/?type[]=%s&q=', v);
        };
        var formatPlacesReq = function (v){
            return sprintf('places/?type[]=%s&q=', v);
        };
        var dynamicTypeRequest = {
            addresses: formatPlacesReq('address'),
            administrative_regions: formatPlacesReq('administrative_region'),
            commercial_modes: formatPtReq('commercial_mode'),
            coord: formatPlacesReq('address'),
            'forbidden_uris[]': 'pt_objects/?q=',
            lines: formatPtReq('line'),
            networks: formatPtReq('network'),
            places: 'places/?&q=',
            pois: formatPlacesReq('poi'),
            routes: formatPtReq('route'),
            stop_areas: formatPtReq('stop_area'),
            stop_points: formatPlacesReq('stop_point'),
            from: 'places/?&q=',
            to: 'places/?&q=',
        };
        var httpReq = dynamicTypeRequest[dynamicType];
        if (! httpReq) {
            return;
        }
        $(elt).autocomplete({
            delay: 200,
            close: function() { updateUrl($(elt)[0]); },
            focus: function() { updateUrl($(elt)[0]); },
            source: function (request, res) {
                var token = $('#token input.token').val();
                var url = $('#api input.api').val();
                var cov = getCoverage();
                // cov can be null in case where coverage is not specified
                cov = cov ? ('coverage/' + cov) : '';
                $.ajax({
                    url: sprintf('%s/%s/%s%s&display_geojson=false', url, cov, httpReq, encodeURIComponent(request.term)),
                    headers: manageToken(token),
                    success: function (data) {
                        var result = [];
                        // TODO: use summary
                        var search = null;
                        var type = null;
                        if ('places' in data) {
                            search = data.places;
                            type = 'place';
                        } else if ('pt_objects' in data) {
                            search = data.pt_objects;
                            type = 'pt_object';
                        }
                        if (search) {
                            search.forEach(function(s) {
                                var sum = summary.run(new response.Context(data), type, s);
                                result.push({ value: s.id, label: sum });
                            });
                        }
                        res(result);
                    },
                    error: function(data, status, xhr) {
                        res([]);
                        notifyOnError(data, 'Autocomplete');
                    }
                });
            }
        }).autocomplete('instance')._renderItem = function(ul, item) {
            return $('<li>').append(item.label).appendTo(ul);
        };
    },
    _customAutocompleteHelper: function(input, source, customOptions) {
        if (source.length && source[0] instanceof Object) {
            source = source.sort(function(a, b) {
                if (a.value < b.value) { return -1; }
                if (a.value > b.value) { return 1; }
                return 0;
            });
        } else {
            source = source.sort();
        }
        var options = {
            close: function() { updateUrl($(input)[0]); },
            focus: function() { updateUrl($(input)[0]); },
            source: source,
            minLength: 0,
            scroll: true,
            delay: 500
        };
        if (customOptions) { $.extend(true, options, customOptions); }
        $(input).autocomplete(options).focus(function() {
            $(this).autocomplete('search', '');
        });
    },
    _makeDatetime: function(elt) {
        $(elt).datetimepicker({
            dateFormat: 'yymmdd',
            timeFormat: 'HHmmss',
            timeInput: true,
            separator: 'T',
            controlType: 'select',
            oneLine: true,
        });
    },
}
<commit_msg>autocomplete reindentation<commit_after>// Copyright (c) 2016 CanalTP
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

var _paramValueEverywhere = ['depth', 'count', 'forbidden_uris[]', 'filter', 'bss_stands'];
var _collections = [
    'addresses', 'commercial_modes', 'companies', 'contributors', 'coord', 'coverage',
    'datasets', 'disruptions', 'lines', 'networks', 'places', 'poi_types', 'pois',
    'physical_modes', 'routes', 'stop_areas', 'stop_points', 'vehicle_journeys'].sort();
var _additionalFeatures = ['departures', 'journeys', 'places_nearby', 'pt_objects', 'route_schedules', 'stop_schedules',
                            'arrivals', 'isochrones', 'heat_maps'];
var _paramJourneyCommon = ['from', 'to', 'datetime','traveler_type', 'data_freshness',
            'first_section_mode[]', 'last_section_mode[]'].concat(_paramValueEverywhere).sort();

// ParamKey
var _depArrParams = ['from_datetime', 'duration', 'data_freshness'].concat(_paramValueEverywhere).sort();
var _schedulesParams = ['from_datetime', 'duration', 'items_per_schedule', 'data_freshness'].concat(_paramValueEverywhere).sort();
var _placesParams = ['q', 'type[]', 'admin_uri[]'].concat(_paramValueEverywhere).sort();

// ParamValue
var _fallbackMode = ['walking', 'car', 'bike', 'bss'].sort();
var _booleanValues = ['true', 'false'];

var autocomplete = {};

autocomplete.autocompleteTree = {
    pathKey: {
        empty : ['coverage', 'places', 'coord'],
        all : _collections,
    },
    features: {
        all: _collections.concat(_additionalFeatures).sort(),
    },
    paramKey: {
        arrivals: _depArrParams,
        coord: _paramValueEverywhere,
        coverage: _paramValueEverywhere,
        departures: _depArrParams,
        journeys: ['datetime_represents'].concat(_paramJourneyCommon).sort(),
        isochrones: [ 'max_duration', 'min_duration', 'boundary_duration[]'].concat(_paramJourneyCommon).sort(),
        heat_maps: [ 'max_duration', 'resolution'].concat(_paramJourneyCommon).sort(),
        lines: _paramValueEverywhere,
        places_nearby: _placesParams.sort(),
        places: _placesParams,
        pois: ['distance'].concat(_paramValueEverywhere).sort(),
        pt_objects: ['q', 'type[]'].concat(_paramValueEverywhere),
        stop_areas: _paramValueEverywhere,
        stop_points: _paramValueEverywhere,
        routes: _paramValueEverywhere,
        route_schedules: _schedulesParams,
        stop_schedules: _schedulesParams,
        empty: _paramValueEverywhere,
    },
    paramValue : {
        traveler_type : ['luggage', 'standard', 'fast_walker', 'slow_walker'],
        datetime_represents : ['arrival', 'departure'],
        data_freshness: ['base_schedule', 'adapted_schedule', 'realtime'],
        debug: _booleanValues,
        wheelchair: _booleanValues,
        disable_geojson: _booleanValues,
        bss_stands: _booleanValues,
        'first_section_mode[]': _fallbackMode,
        'last_section_mode[]': _fallbackMode,
    }
};

autocomplete.apiAutocomplete = function() {
    var input = $("#api input.api");
    var apis = storage.getApis();
    autocomplete._customAutocompleteHelper(input, apis, {
        close: setSaveTokenButtonStatus,
        focus: setSaveTokenButtonStatus,
        select: function (event, ui) {
            $(input).val(ui.item.value);
            $("#token input.token").val(storage.getToken(ui.item.value));
        }
    });
};

autocomplete.valueAutoComplete = function (input, key) {
    if (isDatetimeType(key)) {
        autocomplete._makeDatetime(input);
    } else if (key in this.autocompleteTree.paramValue){
        autocomplete._customAutocompleteHelper(input, this.autocompleteTree.paramValue[key]);
    } else if (this.staticAutocompleteTypes.indexOf(key) > -1) {
        this.staticAutocomplete(input, key);
    } else if (this.dynamicAutocompleteTypes.indexOf(key) > -1) {
        this.dynamicAutocomplete(input, key);
    }
};

autocomplete.addKeyAutocomplete = function(input, type) {
    var source;
    if (type === 'pathKey' && ! $('#pathFrame').find('.value').length) {
        source = this.autocompleteTree[type].empty;
    } else if (type === 'paramKey'){
        var feature = $('#featureInput').val();
        source = this.autocompleteTree[type][feature] || this.autocompleteTree[type].empty;
    } else {
        source = this.autocompleteTree[type].all;
    }
    source = source || [];
    autocomplete._customAutocompleteHelper(input, source, {
        select: function(event, ui) { $(input).val(ui.item.value).change(); }
    });
};

autocomplete.staticAutocompleteTypes = [
    'coverage',
    'physical_modes',
    'poi_types',
];

autocomplete.staticAutocomplete = function(input, staticType) {
    var old_request = '';
    var old_token = '';
    var handle = function() {
        var api = $('#api input.api').val();
        var token = $('#token input.token').val();
        var cov = getCoverage();
        var request = api +  '/coverage/';
        if (staticType !== 'coverage') {
            request +=  cov + '/' + staticType;
        }
        request += '?disable_geojson=true'
        if (request !== old_request || token !== old_token) {
            old_request = request;
            old_token = token;
            autocomplete.updateStaticAutocomplete(input, staticType, request, token);
        } else if ($(input).is(':focus') && $(input).autocomplete('instance')) {
            $(input).autocomplete('search', '');
        }
    };
    handle();
    $(input).focus(handle);
};

autocomplete.updateStaticAutocomplete = function(input, staticType, request, token) {
    if ($(input).autocomplete('instance')) {
        // be shure that out-of-date autocompletion will not be active
        $(input).autocomplete('destroy');
    }
    $.ajax({
        headers: manageToken(token),
        dataType: 'json',
        url: request,
        success: function(data) {
            var res = [];
            staticType = (staticType==='coverage') ? 'regions' :  staticType;
            data[staticType].forEach(function(elt) {
                var s = summary.run(new response.Context(data), getType(staticType), elt);
                res.push({ value: elt.id, label: s.textContent, desc: s });
            });
            res = res.sort(function(a, b) {
                if (a.label < b.label) { return -1; }
                if (a.label > b.label) { return 1; }
                return 0;
            });
            $(input).autocomplete({
                close: function() { updateUrl($(input)[0]); },
                focus: function() { updateUrl($(input)[0]); },
                source: res,
                minLength: 0,
                scroll: true,
                delay: 500
            }).autocomplete('instance')._renderItem = function(ul, item) {
                return $('<li>').append(item.desc).appendTo(ul);
            };
            $(input).autocomplete('enable');
            if ($(input).is(':focus') && $(input).autocomplete('instance')) {
                $(input).autocomplete('search', '');
            }
        },
        error: function(data, status, xhr) {
            notifyOnError(data, 'Autocomplete');
        }
    });
};

autocomplete.dynamicAutocompleteTypes = [
    'addresses',
    'administrative_regions',
    'commercial_modes',
    'coord',
    'forbidden_uris[]',
    'lines',
    'networks',
    'places',
    'pois',
    'routes',
    'stop_areas',
    'stop_points',
    'from',
    'to',
];

autocomplete.dynamicAutocomplete = function (elt, dynamicType) {
    var formatPtReq = function (v){
        return sprintf('pt_objects/?type[]=%s&q=', v);
    };
    var formatPlacesReq = function (v){
        return sprintf('places/?type[]=%s&q=', v);
    };
    var dynamicTypeRequest = {
        addresses: formatPlacesReq('address'),
        administrative_regions: formatPlacesReq('administrative_region'),
        commercial_modes: formatPtReq('commercial_mode'),
        coord: formatPlacesReq('address'),
        'forbidden_uris[]': 'pt_objects/?q=',
        lines: formatPtReq('line'),
        networks: formatPtReq('network'),
        places: 'places/?&q=',
        pois: formatPlacesReq('poi'),
        routes: formatPtReq('route'),
        stop_areas: formatPtReq('stop_area'),
        stop_points: formatPlacesReq('stop_point'),
        from: 'places/?&q=',
        to: 'places/?&q=',
    };
    var httpReq = dynamicTypeRequest[dynamicType];
    if (! httpReq) {
        return;
    }
    $(elt).autocomplete({
        delay: 200,
        close: function() { updateUrl($(elt)[0]); },
        focus: function() { updateUrl($(elt)[0]); },
        source: function (request, res) {
            var token = $('#token input.token').val();
            var url = $('#api input.api').val();
            var cov = getCoverage();
            // cov can be null in case where coverage is not specified
            cov = cov ? ('coverage/' + cov) : '';
            $.ajax({
                url: sprintf('%s/%s/%s%s&display_geojson=false', url, cov, httpReq, encodeURIComponent(request.term)),
                headers: manageToken(token),
                success: function (data) {
                    var result = [];
                    // TODO: use summary
                    var search = null;
                    var type = null;
                    if ('places' in data) {
                        search = data.places;
                        type = 'place';
                    } else if ('pt_objects' in data) {
                        search = data.pt_objects;
                        type = 'pt_object';
                    }
                    if (search) {
                        search.forEach(function(s) {
                            var sum = summary.run(new response.Context(data), type, s);
                            result.push({ value: s.id, label: sum });
                        });
                    }
                    res(result);
                },
                error: function(data, status, xhr) {
                    res([]);
                    notifyOnError(data, 'Autocomplete');
                }
            });
        }
    }).autocomplete('instance')._renderItem = function(ul, item) {
        return $('<li>').append(item.label).appendTo(ul);
    };
};

autocomplete._customAutocompleteHelper = function(input, source, customOptions) {
    if (source.length && source[0] instanceof Object) {
        source = source.sort(function(a, b) {
            if (a.value < b.value) { return -1; }
            if (a.value > b.value) { return 1; }
            return 0;
        });
    } else {
        source = source.sort();
    }
    var options = {
        close: function() { updateUrl($(input)[0]); },
        focus: function() { updateUrl($(input)[0]); },
        source: source,
        minLength: 0,
        scroll: true,
        delay: 500
    };
    if (customOptions) { $.extend(true, options, customOptions); }
    $(input).autocomplete(options).focus(function() {
        $(this).autocomplete('search', '');
    });
};

autocomplete._makeDatetime = function(elt) {
    $(elt).datetimepicker({
        dateFormat: 'yymmdd',
        timeFormat: 'HHmmss',
        timeInput: true,
        separator: 'T',
        controlType: 'select',
        oneLine: true,
    });
};
<|endoftext|>


<commit_before>var gnames = gNames();
for(var i=0; i<gnames.length; i++){
	$(".result").append('
'+gnames[i].city+'
');
	$(".result").append('<gcse:searchresults-only gname="'+gnames[i].gname+'"></gcse:searchresults-only>');
}
var QueryString = queryString();
if(jQuery.isEmptyObject(QueryString) === false) {
	for(var t in QueryString) {
		if(t == "q") $("#what").val(QueryString[t]);
		if(t == "zipcode") $("#where").val(QueryString[t]);
		if(t == "max_dist") $("#max_dist").val(QueryString[t]);
		if(t == "min_price") $("#min_price").val(QueryString[t]);
		if(t == "max_price") $("#max_price").val(QueryString[t]);
		if(t == "min_meter") $("#min_meter").val(QueryString[t]);
		if(t == "max_meter") $("#max_meter").val(QueryString[t]);
	}

	window.__gcse = {
			callback: googleCSELoaded
	};

	// CSE Code. This is a free version, so please don't make too many requests.
	(function() {
		//var cx = '001386805071419863133:cb1vfab8b4y';
		var cx = '014940883816157527715:_1dsxowig5w';
		var gcse = document.createElement('script');
		gcse.type = 'text/javascript';
		gcse.async = true;
		gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(gcse, s);
	})();
}
<commit_msg>Changed fields names<commit_after>var gnames = gNames();
for(var i=0; i<gnames.length; i++){
	$(".result").append('
'+gnames[i].city+'
');
	$(".result").append('<gcse:searchresults-only gname="'+gnames[i].gname+'"></gcse:searchresults-only>');
}
var QueryString = queryString();
if(jQuery.isEmptyObject(QueryString) === false) {
	for(var t in QueryString) {
		if(t == "q") $("#search_string").val(QueryString[t]);
		if(t == "zipcode") $("#location").val(QueryString[t]);
		if(t == "max_dist") $("#max_dist").val(QueryString[t]);
		if(t == "min_price") $("#minAsk8").val(QueryString[t]);
		if(t == "max_price") $("#maxAsk8").val(QueryString[t]);
		if(t == "min_meter") $("#minYear8").val(QueryString[t]);
		if(t == "max_meter") $("#maxYear8").val(QueryString[t]);
	}

	window.__gcse = {
			callback: googleCSELoaded
	};

	// CSE Code. This is a free version, so please don't make too many requests.
	(function() {
		//var cx = '001386805071419863133:cb1vfab8b4y';
		var cx = '014940883816157527715:_1dsxowig5w';
		var gcse = document.createElement('script');
		gcse.type = 'text/javascript';
		gcse.async = true;
		gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(gcse, s);
	})();
}
<|endoftext|>


<commit_before>(function($) {
     window['Devtools'] = { //window represents the browser window
        //by putting it in window, it's essentially greating a global variable

        // development settings.
        //VERSION: 0.1,

        defaults: {
            logging: false,  // false to turn off logging
            production: false
        },

	get_rid : function(name) {

        var rids = {
            "rulesets": {"prod": "b506607x14",
                          "dev": "b506607x14"
            }
        };

	    return this.defaults.production ? rids[name].prod : rids[name].dev;
	},

    rid_eci: null, //fleet_eci
    rid_summary: {}, //vehicle_summary
    rid_list: [], //vehicles

    log: function() {
        if (this.defaults.logging && console && console.log) {
            [].unshift.call(arguments, "Devtools:"); // arguments is Array-like, it's not an Array
            console.log.apply(console, arguments);
        }
    },

    getProfile: function(channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
            Devtools.log("Retrieving profile for user");

        return CloudOS.skyCloud("a169x676", "get_all_me", {}, function(res) { //fix this up. what rule is this calling?
            CloudOS.clean(res);
            if(typeof cb !== "undefined"){
                cb(res);
            }
        },
        {"eci": channel});
    },

    getRulesets: function(cb, options) //almost like getProfile in fuse-api.js
    {

        cb = cb || function(){};
        options = options || {};
        //var rid = "rulesets";
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showRulesets", {}, function(json) {
            Devtools.log("Displaying rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

//---------the functions for updating rulesets

    ridSummary: function(cb, options) {
            cb = cb || function(){};
            options = options || {};
            //if(isEmpty(Devtools.vehicle_summary)) {
            //options.force = true;
            //}
            return Devtools.ask_fleet("ridSummary", {}, Devtools.rid_summary, function(json) {
            if(typeof json.error === "undefined") {
                Devtools.rid_summary = json;
                Devtools.log("Retrieve vehicle summary", json);
                cb(json);
            } else {
                console.log("Bad vehicle summary fetch ", json);
            }
            }, options);
        },

    ridChannels: function(cb, options){
            cb = cb || function(){};
            options = options || {};
                Devtools.log("Retrieving vehicles");
            return Devtools.ask_fleet("ridChannels", {}, Devtools.rid_list, function(json) {
            if(typeof json.error === "undefined") {
                Devtools.rid_list = json;       //retrieved vehicles
                Devtools.log("Retrieved vehicles", json);
                cb(json);
            } else {
                console.log("Bad vehicle channel fetch: ", json);
            }
            }, options);
        },

    updateRIDSummary: function(id, profile) {
            Devtools.rid_summary = Devtools.rid_summary || {};
            Devtools.rid_summary[id] = Devtools.rid_summary[id] || {};
            $.each(profile, function(k,v){
            k = (k === "myProfileName") ? "profileName"
                      : (k === "myProfilePhoto") ? "profilePhoto"
                      : k;
            console.log("Storing in vehicle summary ", k, v);
            Devtools.rid_summary[id][k] = v;
            });
        },

    ask_fleet: function(funcName, args, cache, cb, options) {  //replace fleet with pico?
            cb = cb || function(){};
            options = options || {};
            var rid = options.rid || "fleet";

            if (isEmpty(cache)
              || options.force
               ) {
                       Devtools.log("Calling " + funcName);
               Devtools.picoChannel(function(fc) {
                   Devtools.log("Using fleet channel ", fc);
                   if(fc !== "none") {
                   return CloudOS.skyCloud(Devtools.get_rid(rid), funcName, args, cb, {"eci": fc});
                   } else {
                   Devtools.log("fleet_eci is undefined, you must get the fleet channel first");
                   return null;
                   }
               });
               } else {
               cb(cache);
               return cache;
               }
        },

    picoChannel: function(cb, options) //fleetChannel
    {
        cb = cb || function(){};
        options = options || {};
        if (typeof Devtools.rid_eci === "undefined" || Devtools.rid_eci == "" || Devtools.rid_eci == null || options.force) {
                Devtools.log("Retrieving fleet channel");
        return CloudOS.skyCloud(Devtools.get_rid("owner"), "picoChannel", {}, function(json) {
            if(json.eci != null)  {
            Devtools.rid_eci = json.eci;
            Devtools.log("Retrieved fleet channel", json);
            cb(json.eci);
            } else {
            console.log("Seeing null fleet eci, not storing...");
            cb(null);
            }
        });
        } else {
        Devtools.log("Using cached value of fleet channel ", Devtools.rid_eci);
        cb(Devtools.rid_eci);
        return Devtools.rid_eci;
        }
    },

}; //closes the "window" inside the function DON'T DELETE

//----------------------------------

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj == null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
                if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;

        };

})(jQuery);<commit_msg>update with comments<commit_after>(function($) {
     window['Devtools'] = { //window represents the browser window
        //by putting it in window, it's essentially greating a global variable

        // development settings.
        //VERSION: 0.1,

        defaults: {
            logging: false,  // false to turn off logging
            production: false
        },

	get_rid : function(name) {

        var rids = {
            "rulesets": {"prod": "b506607x14",
                          "dev": "b506607x14"
            }
        };

	    return this.defaults.production ? rids[name].prod : rids[name].dev;
	},

    rid_eci: null, //fleet_eci
    rid_summary: {}, //vehicle_summary
    rid_list: [], //vehicles

    log: function() {
        if (this.defaults.logging && console && console.log) {
            [].unshift.call(arguments, "Devtools:"); // arguments is Array-like, it's not an Array
            console.log.apply(console, arguments);
        }
    },

    getProfile: function(channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
            Devtools.log("Retrieving profile for user");

        return CloudOS.skyCloud("a169x676", "get_all_me", {}, function(res) { //fix this up. what rule is this calling?
            CloudOS.clean(res);
            if(typeof cb !== "undefined"){
                cb(res);
            }
        },
        {"eci": channel});
    },

    getRulesets: function(cb, options) //almost like getProfile in fuse-api.js
    {

        cb = cb || function(){};
        options = options || {};
        //var rid = "rulesets";
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showRulesets", {}, function(json) {
            Devtools.log("Displaying rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

//---------the functions for updating rulesets

    ridSummary: function(cb, options) //vehicleSummary
    {
            cb = cb || function(){};
            options = options || {};
            //if(isEmpty(Devtools.vehicle_summary)) {
            //options.force = true;
            //}
            return Devtools.ask_fleet("ridSummary", {}, Devtools.rid_summary, function(json) {
            if(typeof json.error === "undefined") {
                Devtools.rid_summary = json;
                Devtools.log("Retrieve vehicle summary", json);
                cb(json);
            } else {
                console.log("Bad vehicle summary fetch ", json);
            }
            }, options);
        },

    ridChannels: function(cb, options) //vehicleChannels
    {
            cb = cb || function(){};
            options = options || {};
                Devtools.log("Retrieving vehicles");
            return Devtools.ask_fleet("ridChannels", {}, Devtools.rid_list, function(json) {
            if(typeof json.error === "undefined") {
                Devtools.rid_list = json;       //retrieved vehicles
                Devtools.log("Retrieved vehicles", json);
                cb(json);
            } else {
                console.log("Bad vehicle channel fetch: ", json);
            }
            }, options);
        },

    updateRIDSummary: function(id, profile) //updateVehicleSummary
    {
            Devtools.rid_summary = Devtools.rid_summary || {};
            Devtools.rid_summary[id] = Devtools.rid_summary[id] || {};
            $.each(profile, function(k,v){
            k = (k === "myProfileName") ? "profileName"
                      : (k === "myProfilePhoto") ? "profilePhoto"
                      : k;
            console.log("Storing in vehicle summary ", k, v);
            Devtools.rid_summary[id][k] = v;
            });
        },

    ask_fleet: function(funcName, args, cache, cb, options) {  //replace fleet with pico?
            cb = cb || function(){};
            options = options || {};
            var rid = options.rid || "fleet";

            if (isEmpty(cache)
              || options.force
               ) {
                       Devtools.log("Calling " + funcName);
               Devtools.picoChannel(function(fc) {
                   Devtools.log("Using fleet channel ", fc);
                   if(fc !== "none") {
                   return CloudOS.skyCloud(Devtools.get_rid(rid), funcName, args, cb, {"eci": fc});
                   } else {
                   Devtools.log("fleet_eci is undefined, you must get the fleet channel first");
                   return null;
                   }
               });
               } else {
               cb(cache);
               return cache;
               }
        },

    picoChannel: function(cb, options) //fleetChannel
    {
        cb = cb || function(){};
        options = options || {};
        if (typeof Devtools.rid_eci === "undefined" || Devtools.rid_eci == "" || Devtools.rid_eci == null || options.force) {
                Devtools.log("Retrieving fleet channel");
        return CloudOS.skyCloud(Devtools.get_rid("owner"), "picoChannel", {}, function(json) {
            if(json.eci != null)  {
            Devtools.rid_eci = json.eci;
            Devtools.log("Retrieved fleet channel", json);
            cb(json.eci);
            } else {
            console.log("Seeing null fleet eci, not storing...");
            cb(null);
            }
        });
        } else {
        Devtools.log("Using cached value of fleet channel ", Devtools.rid_eci);
        cb(Devtools.rid_eci);
        return Devtools.rid_eci;
        }
    },

}; //closes the "window" inside the function DON'T DELETE

//----------------------------------

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj == null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
                if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;

        };

})(jQuery);<|endoftext|>


<commit_before>var layout = {
  div: document.createElement('div'),
  content: document.createElement('div'),
}
function renderFinder(){
  layout.div.className = 'bodyDiv';
  layout.content.className = 'contentDiv';
  document.body.appendChild(layout.div);
  layout.div.appendChild(layout.content);
}
function makeCell(){
  var cell = document.createElement('div');
  cell.className = 'drinkDiv';
  layout.content.appendChild(cell);
  return cell;
}
function divCell(target){
  var divide = document.createElement('div');
  divide.className = 'innerDiv';
  target.appendChild(divide);
  return divide;
}
function renderDrink(drinkObj){
  var img = document.createElement('img');
  img.setAttribute('src', drinkObj.imageProperty);
  if (!ingredientID.image){img.setAttribute('src', 'img/missingDrink.jpg');}
  img.className = 'ingIcon';
  var cell = makeCell();
  var idCont = divCell(cell);
  var title = document.createElement('p');
  title.textContent = drinkObj.drinkName;
  title.className = 'ingTitle';
  idCont.appendChild(img);
  idCont.appendChild(title);

  var mismatchCell = divCell(cell)
  mismatchCell.className = 'mismatch';

  var haveIng = divCell(mismatchCell);
  haveIng.className = 'misCell';
  var haveText = document.createElement('p');
  haveText.className = 'ingTitle'
  haveText.textContent = 'Matching Ingredients:';
  haveIng.appendChild(haveText);
  var missIng = divCell(mismatchCell);
  missIng.className = 'misCell';
  var missText = document.createElement('p');
  missText.className = 'ingTitle'
  missText.textContent = 'Missing Ingredients:'
  missIng.appendChild(missText);

  var missMatch = getMissMatch(drinkObj);
  var miss = document.createElement('p');
  var match = document.createElement('p');
  miss.textContent = missMatch.missing.join(', ');
  match.textContent = missMatch.matching.join(', ');
  miss.className = 'missingText';
  match.className = 'matchingText';
  missIng.appendChild(miss);
  haveIng.appendChild(match);

  var delCont = divCell(cell);
  var delButton = document.createElement('img');
  delButton.className = 'delButton';
  delButton.setAttribute('src', 'img/delIcon.png');
  delButton.addEventListener('click', function(){
    layout.content.removeChild(cell);
    // delDrink(drinkObj.drinkName);
  })
  delCont.appendChild(delButton);

  imgListener(img, drinkObj, cell);
}
function imgListener(img, drinkObj, cell){
  var imgOpen = false;
  var bufferCell;
  img.addEventListener('click', function(){
    if (!imgOpen){
      imgOpen = true;

      bufferCell = divCell(cell);
      bufferCell.className = 'buffer';

      var ingCell = divCell(bufferCell); // Render Ingredients
      ingCell.className = 'ingCell';
      var ingTitle = document.createElement('p');
      ingTitle.textContent = 'Ingredients:'
      ingTitle.className = 'ingTitle';
      ingCell.appendChild(ingTitle);
      var ingList = document.createElement('ul');
      ingList.className = 'descText';
      ingCell.appendChild(ingList);
      fillIngList(ingList, drinkObj); // Fill ingredient list

      var descCell = divCell(bufferCell); // Render Description
      descCell.className = 'descCell';
      var descTitle = document.createElement('p');
      descTitle.textContent = 'Recipe Description:'
      descTitle.className = 'ingTitle';
      descCell.appendChild(descTitle);
      var description = document.createElement('p');
      description.textContent = drinkObj.drinkRecipe;
      description.className = 'descText';
      descCell.appendChild(description);

      imgEl = document.createElement('input'); // Render image input box
      imgEl.type = 'text';
      imgEl.value = 'Enter new ' + drinkObj.drinkName + ' image location.';
      descCell.appendChild(imgEl);
      subEl = document.createElement('input')
      subEl.setAttribute('type', 'submit');
      subEl.setAttribute('value', 'Submit');
      subEl.addEventListener('click', function(){
        drinkObj.imageProperty = imgEl.value
        imgEl.value = '';
        updateDrinks();
        refreshDrinks(drinkArray);
      })
      descCell.appendChild(subEl);

    } else {
      cell.removeChild(bufferCell);
      imgOpen = false;
    }
  })
}
function fillIngList(target, objRef){
  objRef.ingredients.forEach(function(ingArrRef){
    var listEntry = document.createElement('li');
    listEntry.textContent = ingArrRef[0] + ', ' + ingArrRef[1];
    target.appendChild(listEntry);
  })
}
function refreshDrinks(array){
  if(layout.div.childNodes[0]){layout.div.removeChild(layout.content);}
  layout.content = document.createElement('div');
  renderFinder();
  array.forEach(function(drinkID){
    renderDrink(drinkID);
  })
}
function getMissMatch(drinkObj){
  var ingmatch = {matching: [], missing: []};
  drinkObj.ingredients.forEach(function(ingArr){
    var match = false
    ingArray.forEach(function(ingObj){
      if (ingArr[0].toLowerCase() === ingObj.ingName.toLowerCase()){match = true;}
    })
    if (match){
      ingmatch.matching.push(ingArr[0]);
    } else {
      ingmatch.missing.push(ingArr[0]);
    }
  })
  return ingmatch
}

// refreshDrinks(drinkArray);
<commit_msg>fixed finderRender<commit_after>var layout = {
  div: document.createElement('div'),
  content: document.createElement('div'),
}
function renderFinder(){
  layout.div.className = 'bodyDiv';
  layout.content.className = 'contentDiv';
  document.body.appendChild(layout.div);
  layout.div.appendChild(layout.content);
}
function makeCell(){
  var cell = document.createElement('div');
  cell.className = 'drinkDiv';
  layout.content.appendChild(cell);
  return cell;
}
function divCell(target){
  var divide = document.createElement('div');
  divide.className = 'innerDiv';
  target.appendChild(divide);
  return divide;
}
function renderDrink(drinkObj){
  var img = document.createElement('img');
  img.setAttribute('src', drinkObj.imageProperty);
  if (!drinkObj.imageProperty){img.setAttribute('src', 'img/missingDrink.jpg');}
  img.className = 'ingIcon';
  var cell = makeCell();
  var idCont = divCell(cell);
  var title = document.createElement('p');
  title.textContent = drinkObj.drinkName;
  title.className = 'ingTitle';
  idCont.appendChild(img);
  idCont.appendChild(title);

  var mismatchCell = divCell(cell)
  mismatchCell.className = 'mismatch';

  var haveIng = divCell(mismatchCell);
  haveIng.className = 'misCell';
  var haveText = document.createElement('p');
  haveText.className = 'ingTitle'
  haveText.textContent = 'Matching Ingredients:';
  haveIng.appendChild(haveText);
  var missIng = divCell(mismatchCell);
  missIng.className = 'misCell';
  var missText = document.createElement('p');
  missText.className = 'ingTitle'
  missText.textContent = 'Missing Ingredients:'
  missIng.appendChild(missText);

  var missMatch = getMissMatch(drinkObj);
  var miss = document.createElement('p');
  var match = document.createElement('p');
  miss.textContent = missMatch.missing.join(', ');
  match.textContent = missMatch.matching.join(', ');
  miss.className = 'missingText';
  match.className = 'matchingText';
  missIng.appendChild(miss);
  haveIng.appendChild(match);

  var delCont = divCell(cell);
  var delButton = document.createElement('img');
  delButton.className = 'delButton';
  delButton.setAttribute('src', 'img/delIcon.png');
  delButton.addEventListener('click', function(){
    layout.content.removeChild(cell);
    // delDrink(drinkObj.drinkName);
  })
  delCont.appendChild(delButton);

  imgListener(img, drinkObj, cell);
}
function imgListener(img, drinkObj, cell){
  var imgOpen = false;
  var bufferCell;
  img.addEventListener('click', function(){
    if (!imgOpen){
      imgOpen = true;

      bufferCell = divCell(cell);
      bufferCell.className = 'buffer';

      var ingCell = divCell(bufferCell); // Render Ingredients
      ingCell.className = 'ingCell';
      var ingTitle = document.createElement('p');
      ingTitle.textContent = 'Ingredients:'
      ingTitle.className = 'ingTitle';
      ingCell.appendChild(ingTitle);
      var ingList = document.createElement('ul');
      ingList.className = 'descText';
      ingCell.appendChild(ingList);
      fillIngList(ingList, drinkObj); // Fill ingredient list

      var descCell = divCell(bufferCell); // Render Description
      descCell.className = 'descCell';
      var descTitle = document.createElement('p');
      descTitle.textContent = 'Recipe Description:'
      descTitle.className = 'ingTitle';
      descCell.appendChild(descTitle);
      var description = document.createElement('p');
      description.textContent = drinkObj.drinkRecipe;
      description.className = 'descText';
      descCell.appendChild(description);

      imgEl = document.createElement('input'); // Render image input box
      imgEl.type = 'text';
      imgEl.value = 'Enter new ' + drinkObj.drinkName + ' image location.';
      descCell.appendChild(imgEl);
      subEl = document.createElement('input')
      subEl.setAttribute('type', 'submit');
      subEl.setAttribute('value', 'Submit');
      subEl.addEventListener('click', function(){
        drinkObj.imageProperty = imgEl.value
        imgEl.value = '';
        updateDrinks();
        refreshDrinks(drinkArray);
      })
      descCell.appendChild(subEl);

    } else {
      cell.removeChild(bufferCell);
      imgOpen = false;
    }
  })
}
function fillIngList(target, objRef){
  objRef.ingredients.forEach(function(ingArrRef){
    var listEntry = document.createElement('li');
    listEntry.textContent = ingArrRef[0] + ', ' + ingArrRef[1];
    target.appendChild(listEntry);
  })
}
function refreshDrinks(array){
  if(layout.div.childNodes[0]){layout.div.removeChild(layout.content);}
  layout.content = document.createElement('div');
  renderFinder();
  array.forEach(function(drinkID){
    renderDrink(drinkID);
  })
}
function getMissMatch(drinkObj){
  var ingmatch = {matching: [], missing: []};
  drinkObj.ingredients.forEach(function(ingArr){
    var match = false
    ingArray.forEach(function(ingObj){
      if (ingArr[0].toLowerCase() === ingObj.ingName.toLowerCase()){match = true;}
    })
    if (match){
      ingmatch.matching.push(ingArr[0]);
    } else {
      ingmatch.missing.push(ingArr[0]);
    }
  })
  return ingmatch
}

// refreshDrinks(drinkArray);
<|endoftext|>


<commit_before>// Plugin to jQuery
(function($) {
	/*
	// Create a universal animation function that optimizes for the browsers capabilities
	$.fn.optAnimate = function(props, speed, easing, callback) {
		// If modernizr reports that the browser supports CSS animations, and the animateWithCss function has correctly been loaded/defined
		if (Modernizr.cssanimations && typeof($.fn.animateWithCss) == 'function') {
			return $(this).animateWithCss(props, speed, easing, callback);
		}
		else {
			return $(this).animate(props, speed, easing, callback);
		}
	};
	*/
})(jQuery);

// Bind events to be triggered BEFORE jQuery Mobile loads/executes
$(document).bind('mobileinit', function() {
	// Set jQuery mobile settings
	//$.mobile.touchOverflowEnabled = true;
});

// Bind events to be triggered on page initialization
$(document).bind('pageinit', function() {
	// Detect orientation change
	// Bind the event to the window
	$(window).bind('orientationchange', function(event){
		changeOrientation(event.orientation);
	});

	// Detect and mark the "middle" elements of the dashboard
	function detectMiddleElements() {
		// Grab the width of the entire dashboard
		var dashWidth = parseInt($('nav#dashboard').width());

		// Grab the percentage width of the first element
		var elemWidth = parseInt($('nav#dashboard ul#dashboard-mapps li').width());

		// Find the number of elements per row
		var elemPerRow = Math.floor(dashWidth / elemWidth);

		// Set the number of elements per row as a css class on the dashboard tag
		$('nav#dashboard').addClass(elemPerRow + '-per-row');

		// Calculate the middle-th element
		var middleCount = Math.ceil(elemPerRow / 2);

		// Create the nth-child expression
		var everyNthChild = elemPerRow + String('n+') + middleCount;
		console.log(elemPerRow);
		console.log(middleCount);
		console.log(everyNthChild);
		console.log(elemPerRow + 'n+' + middleCount);

		// Finally, set every middle-th element to have a class
		$('nav#dashboard ul#dashboard-mapps li:nth-child(' + everyNthChild +')').addClass('dash-middle-element');
	}

	// Get the device's OS and add it as a class to the HTML tag
	// To be used for OS-specific styling (trying to stay more true to the native styling)
	function deviceOS() {
		var deviceOS = '';

		// Get the data
		var devicePlatform = navigator.userAgent.match(/Android/i)
			|| navigator.userAgent.match(/iPod/i)
			|| navigator.userAgent.match(/iPad/i)
			|| navigator.userAgent.match(/iPhone/i)
			|| navigator.userAgent.match(/webOS/i)
			|| 'Other';

		if (devicePlatform == 'iPod' || devicePlatform == 'iPad' || devicePlatform == 'iPhone') {
			deviceOS = 'ios';
		}
		else if (devicePlatform == 'Android') {
			deviceOS = 'android';
		}
		else {
			deviceOS = devicePlatform.toLowerCase();
		}

		// Add the deviceOS as a CSS class to the HTML tag
		$('html').addClass(deviceOS);

		return deviceOS;
	}

	// Detect device and meta info and display it on the page
	function deviceInfo() {
		// Get the data
		var devicePlatform = deviceOS();
		var displayDensity = window.devicePixelRatio;

		// Display it by adding it to the mobile-info span
		$('#mobile-info').append('
Device Platform: ' + devicePlatform + '
');
		$('#mobile-info').append('
Display Density: ' + displayDensity + '
');

	}

	$('.info-button').click(function() {
		$('#hidden-info-div').animate({opacity: 'toggle', height: 'toggle', leaveTransforms: true, useTranslate3d: true}, 1000, 'easeOutExpo', function() {
			// Fix window height bugs by triggering an updatelayout and resize (repaint, please)
			$(window).trigger('resize');
			$(this).trigger('updatelayout');
		});
	});

	// Functions to run on orientation change
	function changeOrientation(orientation) {
		// Add the orientation as a CSS class to the HTML tag
		$('html').addClass(orientation);

		// Fire off some functions
		detectMiddleElements();
	}

	// Functions to run on page-load
	(function() {
		$(window).trigger('orientationchange');
		detectMiddleElements();
		deviceOS();
		deviceInfo();
	})();
});
<commit_msg>Removed the opacity animation from the footer slider<commit_after>// Plugin to jQuery
(function($) {
	/*
	// Create a universal animation function that optimizes for the browsers capabilities
	$.fn.optAnimate = function(props, speed, easing, callback) {
		// If modernizr reports that the browser supports CSS animations, and the animateWithCss function has correctly been loaded/defined
		if (Modernizr.cssanimations && typeof($.fn.animateWithCss) == 'function') {
			return $(this).animateWithCss(props, speed, easing, callback);
		}
		else {
			return $(this).animate(props, speed, easing, callback);
		}
	};
	*/
})(jQuery);

// Bind events to be triggered BEFORE jQuery Mobile loads/executes
$(document).bind('mobileinit', function() {
	// Set jQuery mobile settings
	//$.mobile.touchOverflowEnabled = true;
});

// Bind events to be triggered on page initialization
$(document).bind('pageinit', function() {
	// Detect orientation change
	// Bind the event to the window
	$(window).bind('orientationchange', function(event){
		changeOrientation(event.orientation);
	});

	// Detect and mark the "middle" elements of the dashboard
	function detectMiddleElements() {
		// Grab the width of the entire dashboard
		var dashWidth = parseInt($('nav#dashboard').width());

		// Grab the percentage width of the first element
		var elemWidth = parseInt($('nav#dashboard ul#dashboard-mapps li').width());

		// Find the number of elements per row
		var elemPerRow = Math.floor(dashWidth / elemWidth);

		// Set the number of elements per row as a css class on the dashboard tag
		$('nav#dashboard').addClass(elemPerRow + '-per-row');

		// Calculate the middle-th element
		var middleCount = Math.ceil(elemPerRow / 2);

		// Create the nth-child expression
		var everyNthChild = elemPerRow + String('n+') + middleCount;
		console.log(elemPerRow);
		console.log(middleCount);
		console.log(everyNthChild);
		console.log(elemPerRow + 'n+' + middleCount);

		// Finally, set every middle-th element to have a class
		$('nav#dashboard ul#dashboard-mapps li:nth-child(' + everyNthChild +')').addClass('dash-middle-element');
	}

	// Get the device's OS and add it as a class to the HTML tag
	// To be used for OS-specific styling (trying to stay more true to the native styling)
	function deviceOS() {
		var deviceOS = '';

		// Get the data
		var devicePlatform = navigator.userAgent.match(/Android/i)
			|| navigator.userAgent.match(/iPod/i)
			|| navigator.userAgent.match(/iPad/i)
			|| navigator.userAgent.match(/iPhone/i)
			|| navigator.userAgent.match(/webOS/i)
			|| 'Other';

		if (devicePlatform == 'iPod' || devicePlatform == 'iPad' || devicePlatform == 'iPhone') {
			deviceOS = 'ios';
		}
		else if (devicePlatform == 'Android') {
			deviceOS = 'android';
		}
		else {
			deviceOS = devicePlatform.toLowerCase();
		}

		// Add the deviceOS as a CSS class to the HTML tag
		$('html').addClass(deviceOS);

		return deviceOS;
	}

	// Detect device and meta info and display it on the page
	function deviceInfo() {
		// Get the data
		var devicePlatform = deviceOS();
		var displayDensity = window.devicePixelRatio;

		// Display it by adding it to the mobile-info span
		$('#mobile-info').append('
Device Platform: ' + devicePlatform + '
');
		$('#mobile-info').append('
Display Density: ' + displayDensity + '
');

	}

	$('.info-button').click(function() {
		$('#hidden-info-div').animate({ height: 'toggle', leaveTransforms: true, useTranslate3d: true}, 800, 'easeOutExpo', function() {
			// Fix window height bugs by triggering an updatelayout and resize (repaint, please)
			$(window).trigger('resize');
			$(this).trigger('updatelayout');
		});
	});

	// Functions to run on orientation change
	function changeOrientation(orientation) {
		// Add the orientation as a CSS class to the HTML tag
		$('html').addClass(orientation);

		// Fire off some functions
		detectMiddleElements();
	}

	// Functions to run on page-load
	(function() {
		$(window).trigger('orientationchange');
		detectMiddleElements();
		deviceOS();
		deviceInfo();
	})();
});
<|endoftext|>


<commit_before>;(function($){
/**
 * jqGrid extension for SubGrid Data
 * Tony Tomov tony@trirand.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid.extend({
setSubGrid : function () {
	return this.each(function (){
		var $t = this, cm;
		$t.p.colNames.unshift("");
		$t.p.colModel.unshift({name:'subgrid',width: $.browser.safari ?  $t.p.subGridWidth+$t.p.cellLayout : $t.p.subGridWidth,sortable: false,resizable:false,hidedlg:true,search:false,fixed:true});
		cm = $t.p.subGridModel;
		if(cm[0]) {
			cm[0].align = $.extend([],cm[0].align || []);
			for(i=0;i<cm[0].name.length;i++) { cm[0].align[i] = cm[0].align[i] || 'left';}
		}
	});
},
addSubGridCell :function (pos,iRow) {
	var prp='',gv,sid;
	this.each(function(){
		prp = this.formatCol(pos,iRow);
		gv = this.p.gridview;
		sid= this.p.id;
	});
	if( gv === false ){
		return "	";
	} else  {
		return "	";
	}
},
addSubGrid : function(t,pos) {
	return this.each(function(){
		var ts = this;
		if (!ts.grid ) { return; }
		var res,_id, pID,atd, nhc, subdata, bfsc;
		$("td:eq("+pos+")",t).click( function(e) {
			if($(this).hasClass("sgcollapsed")) {
				pID = ts.p.id;
				res = $(this).parent();
				atd = pos >=1 ? " 	":"";
				_id = $(res).attr("id");
				bfsc =true;
				if($.isFunction(ts.p.subGridBeforeExpand)) {
					bfsc = ts.p.subGridBeforeExpand(pID+"_"+_id,_id);
				}
				if(bfsc === false) {return false;}
				nhc = 0;
				$.each(ts.p.colModel,function(i,v){
					if(this.hidden === true || this.name == 'rn' || this.name == 'cb') {nhc++;}
				});
				subdata = "
"+atd+"
";
				$(this).parent().after( subdata+ "

" );
				if( $.isFunction(ts.p.subGridRowExpanded)) {
					ts.p.subGridRowExpanded(pID+"_"+ _id,_id);
				} else {
					populatesubgrid(res);
				}
				$(this).html("").removeClass("sgcollapsed").addClass("sgexpanded");
			} else if($(this).hasClass("sgexpanded")) {
				bfsc = true;
				if( $.isFunction(ts.p.subGridRowColapsed)) {
					res = $(this).parent();
					_id = $(res).attr("id");
					bfsc = ts.p.subGridRowColapsed(pID+"_"+_id,_id );
				};
				if(bfsc===false) {return false;}
				$(this).parent().next().remove(".ui-subgrid");
				$(this).html("").removeClass("sgexpanded").addClass("sgcollapsed");
			}
			return false;
		});
		//-------------------------
		var populatesubgrid = function( rd ) {
			var res,sid,dp, i, j;
			sid = $(rd).attr("id");
			dp = {nd_: (new Date().getTime())};
			dp[ts.p.prmNames['subgridid']]=sid;
			if(!ts.p.subGridModel[0]) { return false; }
			if(ts.p.subGridModel[0].params) {
				for(j=0; j < ts.p.subGridModel[0].params.length; j++) {
					for(i=0; i<ts.p.colModel.length; i++) {
						if(ts.p.colModel[i].name == ts.p.subGridModel[0].params[j]) {
							dp[ts.p.colModel[i].name]= $("td:eq("+i+")",rd).text().replace(/\&#160\;/ig,'');
						}
					}
				}
			}
			if(!ts.grid.hDiv.loading) {
				ts.grid.hDiv.loading = true;
				$("#load_"+ts.p.id).show();
				if(!ts.p.subgridtype) ts.p.subgridtype = ts.p.datatype;
				if($.isFunction(ts.p.subgridtype)) {
					ts.p.subgridtype(dp);
				} else {
					ts.p.subgridtype = ts.p.subgridtype.toLowerCase();
				}
				switch(ts.p.subgridtype) {
					case "xml":
					case "json":
					$.ajax($.extend({
						type:ts.p.mtype,
						url: ts.p.subGridUrl,
						dataType:ts.p.subgridtype,
						data: $.isFunction(ts.p.serializeSubGridData)? ts.p.serializeSubGridData(dp) : dp,
						complete: function(sxml) {
							if(ts.p.subgridtype == "xml")
								subGridXml(sxml.responseXML, sid);
							else {
								subGridJson($.jgrid.parse(sxml.responseText),sid);
							}
							sxml=null;
						}
					}, $.jgrid.ajaxOptions, ts.p.ajaxSubgridOptions || {}));
					break;
				}
			}
			return false;
		};
		var subGridCell = function(trdiv,cell,pos){
			var tddiv = $("	").html(cell);
			$(trdiv).append(tddiv);
		};
		var subGridXml = function(sjxml, sbid){
			var tddiv, i, cur, sgmap,
			dummy = $("

"),
			trdiv = $("

");
			for (i = 0; i<ts.p.subGridModel[0].name.length; i++) {
				tddiv = $("	");
				$(tddiv).html(ts.p.subGridModel[0].name[i]);
				$(tddiv).width( ts.p.subGridModel[0].width[i]);
				$(trdiv).append(tddiv);
			}
			$(dummy).append(trdiv);
			if (sjxml){
				sgmap = ts.p.xmlReader.subgrid;
				$(sgmap.root+" "+sgmap.row, sjxml).each( function(){
					trdiv = $("

");
					if(sgmap.repeatitems === true) {
						$(sgmap.cell,this).each( function(i) {
							subGridCell(trdiv, $(this).text() || ' ',i);
						});
					} else {
						var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
						if (f) {
							for (i=0;i<f.length;i++) {
								subGridCell(trdiv, $(f[i],this).text() || ' ',i);
							}
						}
					}
					$(dummy).append(trdiv);
				});
			}
			var pID = $("table:first",ts.grid.bDiv).attr("id")+"_";
			$("#"+pID+sbid).append(dummy);
			ts.grid.hDiv.loading = false;
			$("#load_"+ts.p.id).hide();
			return false;
		};
		var subGridJson = function(sjxml, sbid){
			var tddiv,result , i,cur, sgmap,
			dummy = $("

"),
			trdiv = $("

");
			for (i = 0; i<ts.p.subGridModel[0].name.length; i++) {
				tddiv = $("	");
				$(tddiv).html(ts.p.subGridModel[0].name[i]);
				$(tddiv).width( ts.p.subGridModel[0].width[i]);
				$(trdiv).append(tddiv);
			}
			$(dummy).append(trdiv);
			if (sjxml){
				sgmap = ts.p.jsonReader.subgrid;
				result = sjxml[sgmap.root];
				if ( typeof result !== 'undefined' ) {
					for (i=0;i<result.length;i++) {
						cur = result[i];
						trdiv = $("

");
						if(sgmap.repeatitems === true) {
							if(sgmap.cell) { cur=cur[sgmap.cell]; }
							for (var j=0;j<cur.length;j++) {
								subGridCell(trdiv, cur[j] || ' ',j);
							}
						} else {
							var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
							if(f.length) {
								for (var j=0;j<f.length;j++) {
									subGridCell(trdiv, cur[f[j]] || ' ',j);
								}
							}
						}
						$(dummy).append(trdiv);
					}
				}
			}
			var pID = $("table:first",ts.grid.bDiv).attr("id")+"_";
			$("#"+pID+sbid).append(dummy);
			ts.grid.hDiv.loading = false;
			$("#load_"+ts.p.id).hide();
			return false;
		};
		ts.subGridXml = function(xml,sid) {subGridXml(xml,sid);};
		ts.subGridJson = function(json,sid) {subGridJson(json,sid);};
	});
},
expandSubGridRow : function(rowid) {
	return this.each(function () {
		var $t = this;
		if(!$t.grid && !rowid) {return;}
		if($t.p.subGrid===true) {
			var rc = $(this).jqGrid("getInd",rowid,true);
			if(rc) {
				var sgc = $("td.sgcollapsed",rc)[0];
				if(sgc) {
					$(sgc).trigger("click");
				}
			}
		}
	});
},
collapseSubGridRow : function(rowid) {
	return this.each(function () {
		var $t = this;
		if(!$t.grid && !rowid) {return;}
		if($t.p.subGrid===true) {
			var rc = $(this).jqGrid("getInd",rowid,true);
			if(rc) {
				var sgc = $("td.sgexpanded",rc)[0];
				if(sgc) {
					$(sgc).trigger("click");
				}
			}
		}
	});
},
toggleSubGridRow : function(rowid) {
	return this.each(function () {
		var $t = this;
		if(!$t.grid && !rowid) {return;}
		if($t.p.subGrid===true) {
			var rc = $(this).jqGrid("getInd",rowid,true);
			if(rc) {
				var sgc = $("td.sgcollapsed",rc)[0];
				if(sgc) {
					$(sgc).trigger("click");
				} else {
					sgc = $("td.sgexpanded",rc)[0];
					if(sgc) {
						$(sgc).trigger("click");
					}
				}
			}
		}
	});
}
});
})(jQuery);
<commit_msg>JSLint fixes for subgrid<commit_after>;(function($){
/**
 * jqGrid extension for SubGrid Data
 * Tony Tomov tony@trirand.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid.extend({
setSubGrid : function () {
	return this.each(function (){
		var $t = this, cm;
		$t.p.colNames.unshift("");
		$t.p.colModel.unshift({name:'subgrid',width: $.browser.safari ?  $t.p.subGridWidth+$t.p.cellLayout : $t.p.subGridWidth,sortable: false,resizable:false,hidedlg:true,search:false,fixed:true});
		cm = $t.p.subGridModel;
		if(cm[0]) {
			cm[0].align = $.extend([],cm[0].align || []);
			for(i=0;i<cm[0].name.length;i++) { cm[0].align[i] = cm[0].align[i] || 'left';}
		}
	});
},
addSubGridCell :function (pos,iRow) {
	var prp='',gv,sid;
	this.each(function(){
		prp = this.formatCol(pos,iRow);
		gv = this.p.gridview;
		sid= this.p.id;
	});
	if( gv === false ){
		return "	";
	} else  {
		return "	";
	}
},
addSubGrid : function(t,pos) {
	return this.each(function(){
		var ts = this;
		if (!ts.grid ) { return; }
		var res,_id, pID,atd, nhc, subdata, bfsc;
		$("td:eq("+pos+")",t).click( function(e) {
			if($(this).hasClass("sgcollapsed")) {
				pID = ts.p.id;
				res = $(this).parent();
				atd = pos >=1 ? " 	":"";
				_id = $(res).attr("id");
				bfsc =true;
				if($.isFunction(ts.p.subGridBeforeExpand)) {
					bfsc = ts.p.subGridBeforeExpand(pID+"_"+_id,_id);
				}
				if(bfsc === false) {return false;}
				nhc = 0;
				$.each(ts.p.colModel,function(i,v){
					if(this.hidden === true || this.name == 'rn' || this.name == 'cb') {nhc++;}
				});
				subdata = "
"+atd+"
";
				$(this).parent().after( subdata+ "

" );
				if( $.isFunction(ts.p.subGridRowExpanded)) {
					ts.p.subGridRowExpanded(pID+"_"+ _id,_id);
				} else {
					populatesubgrid(res);
				}
				$(this).html("").removeClass("sgcollapsed").addClass("sgexpanded");
			} else if($(this).hasClass("sgexpanded")) {
				bfsc = true;
				if( $.isFunction(ts.p.subGridRowColapsed)) {
					res = $(this).parent();
					_id = $(res).attr("id");
					bfsc = ts.p.subGridRowColapsed(pID+"_"+_id,_id );
				}
				if(bfsc===false) {return false;}
				$(this).parent().next().remove(".ui-subgrid");
				$(this).html("").removeClass("sgexpanded").addClass("sgcollapsed");
			}
			return false;
		});
		//-------------------------
		var populatesubgrid = function( rd ) {
			var res,sid,dp, i, j;
			sid = $(rd).attr("id");
			dp = {nd_: (new Date().getTime())};
			dp[ts.p.prmNames.subgridid]=sid;
			if(!ts.p.subGridModel[0]) { return false; }
			if(ts.p.subGridModel[0].params) {
				for(j=0; j < ts.p.subGridModel[0].params.length; j++) {
					for(i=0; i<ts.p.colModel.length; i++) {
						if(ts.p.colModel[i].name == ts.p.subGridModel[0].params[j]) {
							dp[ts.p.colModel[i].name]= $("td:eq("+i+")",rd).text().replace(/\&#160\;/ig,'');
						}
					}
				}
			}
			if(!ts.grid.hDiv.loading) {
				ts.grid.hDiv.loading = true;
				$("#load_"+ts.p.id).show();
				if(!ts.p.subgridtype) { ts.p.subgridtype = ts.p.datatype; }
				if($.isFunction(ts.p.subgridtype)) {
					ts.p.subgridtype(dp);
				} else {
					ts.p.subgridtype = ts.p.subgridtype.toLowerCase();
				}
				switch(ts.p.subgridtype) {
					case "xml":
					case "json":
					$.ajax($.extend({
						type:ts.p.mtype,
						url: ts.p.subGridUrl,
						dataType:ts.p.subgridtype,
						data: $.isFunction(ts.p.serializeSubGridData)? ts.p.serializeSubGridData(dp) : dp,
						complete: function(sxml) {
							if(ts.p.subgridtype == "xml") {
								subGridXml(sxml.responseXML, sid);
							} else {
								subGridJson($.jgrid.parse(sxml.responseText),sid);
							}
							sxml=null;
						}
					}, $.jgrid.ajaxOptions, ts.p.ajaxSubgridOptions || {}));
					break;
				}
			}
			return false;
		};
		var subGridCell = function(trdiv,cell,pos){
			var tddiv = $("	").html(cell);
			$(trdiv).append(tddiv);
		};
		var subGridXml = function(sjxml, sbid){
			var tddiv, i, cur, sgmap,
			dummy = $("

"),
			trdiv = $("

");
			for (i = 0; i<ts.p.subGridModel[0].name.length; i++) {
				tddiv = $("	");
				$(tddiv).html(ts.p.subGridModel[0].name[i]);
				$(tddiv).width( ts.p.subGridModel[0].width[i]);
				$(trdiv).append(tddiv);
			}
			$(dummy).append(trdiv);
			if (sjxml){
				sgmap = ts.p.xmlReader.subgrid;
				$(sgmap.root+" "+sgmap.row, sjxml).each( function(){
					trdiv = $("

");
					if(sgmap.repeatitems === true) {
						$(sgmap.cell,this).each( function(i) {
							subGridCell(trdiv, $(this).text() || ' ',i);
						});
					} else {
						var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
						if (f) {
							for (i=0;i<f.length;i++) {
								subGridCell(trdiv, $(f[i],this).text() || ' ',i);
							}
						}
					}
					$(dummy).append(trdiv);
				});
			}
			var pID = $("table:first",ts.grid.bDiv).attr("id")+"_";
			$("#"+pID+sbid).append(dummy);
			ts.grid.hDiv.loading = false;
			$("#load_"+ts.p.id).hide();
			return false;
		};
		var subGridJson = function(sjxml, sbid){
			var tddiv,result , i,cur, sgmap,j,
			dummy = $("

"),
			trdiv = $("

");
			for (i = 0; i<ts.p.subGridModel[0].name.length; i++) {
				tddiv = $("	");
				$(tddiv).html(ts.p.subGridModel[0].name[i]);
				$(tddiv).width( ts.p.subGridModel[0].width[i]);
				$(trdiv).append(tddiv);
			}
			$(dummy).append(trdiv);
			if (sjxml){
				sgmap = ts.p.jsonReader.subgrid;
				result = sjxml[sgmap.root];
				if ( typeof result !== 'undefined' ) {
					for (i=0;i<result.length;i++) {
						cur = result[i];
						trdiv = $("

");
						if(sgmap.repeatitems === true) {
							if(sgmap.cell) { cur=cur[sgmap.cell]; }
							for (j=0;j<cur.length;j++) {
								subGridCell(trdiv, cur[j] || ' ',j);
							}
						} else {
							var f = ts.p.subGridModel[0].mapping || ts.p.subGridModel[0].name;
							if(f.length) {
								for (j=0;j<f.length;j++) {
									subGridCell(trdiv, cur[f[j]] || ' ',j);
								}
							}
						}
						$(dummy).append(trdiv);
					}
				}
			}
			var pID = $("table:first",ts.grid.bDiv).attr("id")+"_";
			$("#"+pID+sbid).append(dummy);
			ts.grid.hDiv.loading = false;
			$("#load_"+ts.p.id).hide();
			return false;
		};
		ts.subGridXml = function(xml,sid) {subGridXml(xml,sid);};
		ts.subGridJson = function(json,sid) {subGridJson(json,sid);};
	});
},
expandSubGridRow : function(rowid) {
	return this.each(function () {
		var $t = this;
		if(!$t.grid && !rowid) {return;}
		if($t.p.subGrid===true) {
			var rc = $(this).jqGrid("getInd",rowid,true);
			if(rc) {
				var sgc = $("td.sgcollapsed",rc)[0];
				if(sgc) {
					$(sgc).trigger("click");
				}
			}
		}
	});
},
collapseSubGridRow : function(rowid) {
	return this.each(function () {
		var $t = this;
		if(!$t.grid && !rowid) {return;}
		if($t.p.subGrid===true) {
			var rc = $(this).jqGrid("getInd",rowid,true);
			if(rc) {
				var sgc = $("td.sgexpanded",rc)[0];
				if(sgc) {
					$(sgc).trigger("click");
				}
			}
		}
	});
},
toggleSubGridRow : function(rowid) {
	return this.each(function () {
		var $t = this;
		if(!$t.grid && !rowid) {return;}
		if($t.p.subGrid===true) {
			var rc = $(this).jqGrid("getInd",rowid,true);
			if(rc) {
				var sgc = $("td.sgcollapsed",rc)[0];
				if(sgc) {
					$(sgc).trigger("click");
				} else {
					sgc = $("td.sgexpanded",rc)[0];
					if(sgc) {
						$(sgc).trigger("click");
					}
				}
			}
		}
	});
}
});
})(jQuery);
<|endoftext|>


<commit_before>

var folderAJAX = "./img/pictures/";
var folder = "img/pictures/";

$.ajax({
    url : folderAJAX,
    success: function (data) {
      console.log(data);
        $(data).find("a").attr("href", function (i, val) {
          console.log(data);
            if( val.match(/\.(jpe?g|png|gif)$/) ) {
                $("thumbContainer").append( "

" );
            }
        });
    }
});
<commit_msg>image gallery update15<commit_after>
$( document ).ready(function() {
var folderAJAX = "./img/pictures/";
var folder = "img/pictures/";

$.ajax({
    url : folderAJAX,
    success: function (data) {
      console.log(data);
        $(data).find("a").attr("href", function (i, val) {
          console.log("HI   -   " + data);
            if( val.match(/\.(jpe?g|png|gif)$/) ) {
                $("thumbContainer").append( "

" );
            }
        });
    }
});
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2016 Institut National de l'Information Geographique et Forestiere (IGN) France.
 * Released under the BSD license.
 */
/*---------------------------------------------------------
 *New Leaflet's class to support WMTS (based on L.TileLayer.WMS)
 */
 /* Updated by Olivier Potonniée to support Leaflet 1.0 */

 var matrixIds3857= new Array(22);
 for (var i= 0; i<22; i++) {
   matrixIds3857[i]= {
       identifier    : "" + i,
       topLeftCorner : new L.LatLng(20037508,-20037508)
   };
 }

L.TileLayer.WMTS = L.TileLayer.extend({

  defaultWmtsParams: {
    service: 'WMTS',
    request: 'GetTile',
    version: '1.0.0',
    layer: '',
    style: '',
    tilematrixSet: '',
    format: 'image/jpeg'
  },

  initialize: function (url, options) { // (String, Object)

    this._url = url;

    // detecting retina displays, adjusting tileSize and zoom levels
    if (options.detectRetina && Browser.retina && options.maxZoom > 0) {

      options.tileSize = Math.floor(options.tileSize / 2);

      if (!options.zoomReverse) {
        options.zoomOffset++;
        options.maxZoom--;
      } else {
        options.zoomOffset--;
        options.minZoom++;
      }

      options.minZoom = Math.max(0, options.minZoom);
    }

    if (typeof options.subdomains === 'string') {
      options.subdomains = options.subdomains.split('');
    }

    //------------------vv WMTS vv-----------------------
    var wmtsParams = L.extend({}, this.defaultWmtsParams),
      tileSize = options.tileSize || this.options.tileSize;
    if (options.detectRetina && L.Browser.retina) {
      wmtsParams.width = wmtsParams.height = tileSize * 2;
    } else {
      wmtsParams.width = wmtsParams.height = tileSize;
    }
    for (var i in options) {
      // all keys that are not TileLayer options go to WMTS params
      if (!this.options.hasOwnProperty(i) && i!="matrixIds") {
        wmtsParams[i] = options[i];
      }
    }
    this.wmtsParams = wmtsParams;
    this.matrixIds = options.matrixIds ?
    options.matrixIds : matrixIds3857;
    //------------------^^ WMTS ^^-----------------------

    options = L.Util.setOptions(this, options);
    // for https://github.com/Leaflet/Leaflet/issues/137
    if (!L.Browser.android) {
      this.on('tileunload', this._onTileRemove);
    }
  },

  onAdd: function (map) {
    L.TileLayer.prototype.onAdd.call(this, map);
  },

  getTileUrl: function (tilePoint) { // (Point) -> String
    var map = this._map;
    var zoom = tilePoint.z;
    crs = map.options.crs;
    tileSize = this.options.tileSize;
    nwPoint = tilePoint.multiplyBy(tileSize);
    //+/-1 pour être dans la tuile
    nwPoint.x+=1;
    nwPoint.y-=1;
    sePoint = nwPoint.add(new L.Point(tileSize, tileSize));
    nw = crs.project(map.unproject(nwPoint, zoom));
    se = crs.project(map.unproject(sePoint, zoom));
    tilewidth = se.x-nw.x;
    ident = this.matrixIds[zoom].identifier;
    X0 = this.matrixIds[zoom].topLeftCorner.lng;
    Y0 = this.matrixIds[zoom].topLeftCorner.lat;
    tilecol=Math.floor((nw.x-X0)/tilewidth);
    tilerow=-Math.floor((nw.y-Y0)/tilewidth);
    url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
    return url + L.Util.getParamString(this.wmtsParams, url) + "&tilematrix=" + ident + "&tilerow=" + tilerow +"&tilecol=" + tilecol ;
  },

  setParams: function (params, noRedraw) {
    L.extend(this.wmtsParams, params);
    if (!noRedraw) {
      this.redraw();
    }
    return this;
  }
});

L.tileLayer.wmts = function (url, options) {
  return new L.TileLayer.WMTS(url, options);
};

/* Fin / End
 *---------------------------------------------------------*/
<commit_msg>skip attribution param in wmts requests<commit_after>/*
 * Copyright (c) 2008-2016 Institut National de l'Information Geographique et Forestiere (IGN) France.
 * Released under the BSD license.
 */
/*---------------------------------------------------------
 *New Leaflet's class to support WMTS (based on L.TileLayer.WMS)
 */
 /* Updated by Olivier Potonniée to support Leaflet 1.0 */

 var matrixIds3857= new Array(22);
 for (var i= 0; i<22; i++) {
   matrixIds3857[i]= {
       identifier    : "" + i,
       topLeftCorner : new L.LatLng(20037508,-20037508)
   };
 }

L.TileLayer.WMTS = L.TileLayer.extend({

  defaultWmtsParams: {
    service: 'WMTS',
    request: 'GetTile',
    version: '1.0.0',
    layer: '',
    style: '',
    tilematrixSet: '',
    format: 'image/jpeg'
  },

  initialize: function (url, options) { // (String, Object)

    this._url = url;

    // detecting retina displays, adjusting tileSize and zoom levels
    if (options.detectRetina && Browser.retina && options.maxZoom > 0) {

      options.tileSize = Math.floor(options.tileSize / 2);

      if (!options.zoomReverse) {
        options.zoomOffset++;
        options.maxZoom--;
      } else {
        options.zoomOffset--;
        options.minZoom++;
      }

      options.minZoom = Math.max(0, options.minZoom);
    }

    if (typeof options.subdomains === 'string') {
      options.subdomains = options.subdomains.split('');
    }

    //------------------vv WMTS vv-----------------------
    var wmtsParams = L.extend({}, this.defaultWmtsParams),
      tileSize = options.tileSize || this.options.tileSize;
    if (options.detectRetina && L.Browser.retina) {
      wmtsParams.width = wmtsParams.height = tileSize * 2;
    } else {
      wmtsParams.width = wmtsParams.height = tileSize;
    }
    for (var i in options) {
      // all keys that are not TileLayer or attribution options go to WMTS params
      if (!this.options.hasOwnProperty(i) && i!="matrixIds" && i!="attribution") {
        wmtsParams[i] = options[i];
      }
    }
    this.wmtsParams = wmtsParams;
    this.matrixIds = options.matrixIds ?
    options.matrixIds : matrixIds3857;
    //------------------^^ WMTS ^^-----------------------

    options = L.Util.setOptions(this, options);
    // for https://github.com/Leaflet/Leaflet/issues/137
    if (!L.Browser.android) {
      this.on('tileunload', this._onTileRemove);
    }
  },

  onAdd: function (map) {
    L.TileLayer.prototype.onAdd.call(this, map);
  },

  getTileUrl: function (tilePoint) { // (Point) -> String
    var map = this._map;
    var zoom = tilePoint.z;
    crs = map.options.crs;
    tileSize = this.options.tileSize;
    nwPoint = tilePoint.multiplyBy(tileSize);
    //+/-1 pour être dans la tuile
    nwPoint.x+=1;
    nwPoint.y-=1;
    sePoint = nwPoint.add(new L.Point(tileSize, tileSize));
    nw = crs.project(map.unproject(nwPoint, zoom));
    se = crs.project(map.unproject(sePoint, zoom));
    tilewidth = se.x-nw.x;
    ident = this.matrixIds[zoom].identifier;
    X0 = this.matrixIds[zoom].topLeftCorner.lng;
    Y0 = this.matrixIds[zoom].topLeftCorner.lat;
    tilecol=Math.floor((nw.x-X0)/tilewidth);
    tilerow=-Math.floor((nw.y-Y0)/tilewidth);
    url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
    return url + L.Util.getParamString(this.wmtsParams, url) + "&tilematrix=" + ident + "&tilerow=" + tilerow +"&tilecol=" + tilecol ;
  },

  setParams: function (params, noRedraw) {
    L.extend(this.wmtsParams, params);
    if (!noRedraw) {
      this.redraw();
    }
    return this;
  }
});

L.tileLayer.wmts = function (url, options) {
  return new L.TileLayer.WMTS(url, options);
};

/* Fin / End
 *---------------------------------------------------------*/
<|endoftext|>


<commit_before>var Player = function()
{
	this._quad = Quad2D.new();

	extend(this, this._quad);

	this.setOffset(0.5, 1);
	this.setTexture("textures/character/character_walk.png");
	this.setToTexture();
	this.setTranslation(0, 0, 1);
	this.spawn("Default");

	this._moveSpeed = 275;
	this._movementMargin = 3;
	this._moveTarget = {
		x: 0,
		y: 0
	}

	var frames = [];

	for (var i = 0; i < 16; ++i)
	{
		frames.push({
			x: i*190,
			y: 0,
			width: 190,
			height: 181
		});
	}

	this._animation = new SpriteAnimation(this, frames);
	this._animation.setSpeed(80);
	this._animation.start();
	this._animation.setLoop(true);

	this.setScale(0.75, 0.75);
	this.setShader("shaders/animation.fx");

	this._xscale = 1;
	this._wobble = 0;

	this._position = {
		x: 0,
		y: 0
	}

	this.update = function(dt)
	{
		if (Mouse.isDown(0))
		{
			this._moveTarget = Mouse.position(Mouse.Relative);
		}

		var direction = Math.atan2(this._moveTarget.y - this._position.y, this._moveTarget.x - this._position.x);
		var movement = {
			x: Math.cos(direction) * dt * this._moveSpeed,
			y: Math.sin(direction) * dt * this._moveSpeed
		}

		this.setScale(this._xscale * Math.abs(movement.x)/movement.x, 1);

		if (Math.distance(this._moveTarget.x, this._moveTarget.y, this._position.x, this._position.y) > this._movementMargin)
		{
			this._wobble += dt*10;
			this._position.x += movement.x;
			this._position.y += movement.y;

			var translation = this.translation();

			this.setTranslation(this._position.x, this._position.y + Math.abs(Math.sin(this._wobble))*12, 360 + this._position.y+8);
			this.setRotation(0,0,Math.sin(this._wobble*1.1)/15);
		}
		else
		{
			this._animation.setFrame(0);
			this.setRotation(0,0,0);
			this._wobble = 0;
		}

		this._animation.update(dt);
	}
}<commit_msg>Bound clamping<commit_after>var Player = function()
{
	this._quad = Quad2D.new();

	extend(this, this._quad);

	this.setOffset(0.5, 1);
	this.setTexture("textures/character/character_walk.png");
	this.setToTexture();
	this.setTranslation(0, 0, 1);
	this.spawn("Default");

	this._moveSpeed = 275;
	this._movementMargin = 3;
	this._moveTarget = {
		x: 0,
		y: 0
	}

	var frames = [];

	for (var i = 0; i < 16; ++i)
	{
		frames.push({
			x: i*190,
			y: 0,
			width: 190,
			height: 181
		});
	}

	this._animation = new SpriteAnimation(this, frames);
	this._animation.setSpeed(80);
	this._animation.start();
	this._animation.setLoop(true);

	this.setScale(0.75, 0.75);
	this.setShader("shaders/animation.fx");

	this._xscale = 1;
	this._wobble = 0;

	this._position = {
		x: 0,
		y: 0
	}

	this.update = function(dt)
	{
		if (Mouse.isDown(0))
		{
			this._moveTarget = Mouse.position(Mouse.Relative);
		}

		var direction = Math.atan2(this._moveTarget.y - this._position.y, this._moveTarget.x - this._position.x);
		var movement = {
			x: Math.cos(direction) * dt * this._moveSpeed,
			y: Math.sin(direction) * dt * this._moveSpeed
		}

		this.setScale(this._xscale * Math.abs(movement.x)/movement.x, 1);

		if (Math.distance(this._moveTarget.x, this._moveTarget.y, this._position.x, this._position.y) > this._movementMargin)
		{
			this._wobble += dt*10;
			this._position.x += movement.x;
			this._position.y += movement.y;

			while (this._position.x - this.size().w / 2 < -(RenderSettings.resolution().w / 2))
			{
				this._position.x += 1;
			}

			while (this._position.x + this.size().w / 2 > (RenderSettings.resolution().w / 2))
			{
				this._position.x -= 1;
			}

			while (this._position.y - this.size().h < -(RenderSettings.resolution().h / 2))
			{
				this._position.y += 1;
			}

			while (this._position.y > (RenderSettings.resolution().h / 2))
			{
				this._position.y -= 1;
			}

			var translation = this.translation();

			this.setTranslation(this._position.x, this._position.y + Math.abs(Math.sin(this._wobble))*12, 360 + this._position.y+8);
			this.setRotation(0,0,Math.sin(this._wobble*1.1)/15);
		}
		else
		{
			this._animation.setFrame(0);
			this.setRotation(0,0,0);
			this._wobble = 0;
		}

		this._animation.update(dt);
	}
}<|endoftext|>


<commit_before>(function(module) {
  var restaurantObj = {};

  restaurantObj.requestRepos = function(location, term, callback) {
    $.when(
      $.get('/yelp/v3/businesses/search?term=' + term + '&location=' + location + '&radius=3218&categories=restaurants&price=1&is_closed=true', function(data) {
        restaurantObj.allRepos = data;
        restaurantObj.allRepos.businesses.forEach(function(options) {
          obj.results.push(new Opt(options.name, options.image_url, options.is_closed, options.address1, options.url));
        });
        console.log(restaurantObj.allRepos);
        obj.results.forEach(function(result){
          $('#results').append(result.toHTML());
        });
      })
    ).done(callback);
  };

  restaurantObj.withTheAttribute = function(attr) {
    return restaurantObj.allRepos.filter(function(aRepo) {
      return aRepo[attr];
    });
  };

  module.restaurantObj = restaurantObj;

})(window);
<commit_msg>working on adding rating to query<commit_after>(function(module) {
  var restaurantObj = {};

  restaurantObj.requestRepos = function(location, term, callback) {
    $.when(
      $.get('/yelp/v3/businesses/search?term=' + term + '&location=' + location + '&radius=3218&categories=restaurants&price=1&is_closed=true&rating=5', function(data) {
        restaurantObj.allRepos = data;
        restaurantObj.allRepos.businesses.forEach(function(options) {
          obj.results.push(new Opt(options.name, options.image_url, options.is_closed, options.address1, options.url));
        });
        console.log(restaurantObj.allRepos);
        obj.results.forEach(function(result){
          $('#results').append(result.toHTML());
        });
      })
    ).done(callback);
  };

  restaurantObj.withTheAttribute = function(attr) {
    return restaurantObj.allRepos.filter(function(aRepo) {
      return aRepo[attr];
    });
  };

  module.restaurantObj = restaurantObj;

})(window);
<|endoftext|>


<commit_before>/**
 * ownCloud - Notifications
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Tom Needham <tom@owncloud.com>
 * @copyright Tom Needham 2015
 */

(function() {

	/**
	 * Initialise the notification
	 */
	var Notif = function(jsonData){
		// TODO handle defaults
		this.app = jsonData.app;
		this.user = jsonData.user;
		this.timestamp = moment(jsonData.datetime).format('X');
		this.object_type = jsonData.object_type;
		this.object_id = jsonData.object_id;
		this.subject = jsonData.subject;
		this.message = jsonData.message;
		this.link = jsonData.link;
		this.actions = jsonData.actions; // TODO some parsing here?
		this.notification_id = jsonData.notification_id;
	};

	Notif.prototype = {

		app: null,

		user: null,

		timestamp: null,

		object_type: null,

		object_id: null,

		subject: null,

		message: null,

		link: null,

		actions: [],

		notification_id: null,

		getSubject: function() {
			return this.subject;
		},

		getTimestamp: function() {
			return this.timestamp;
		},

		getObjectId: function() {
			return this.object_id;
		},

		getLink: function() {
			return this.link;
		},

		getActions: function() {
			return this.actions;
		},

		getId: function() {
			return this.notification_id;
		},

		getMessage: function() {
			return this.message;
		},

		getEl: function() {
			return $('div.notification[data-id='+escapeHTML(this.getId())+']');
		},

		getApp: function() {
			return this.app;
		},

		/**
		 * Generates the HTML for the notification
		 */
		renderElement: function() {
			// FIXME: use handlebars template
			var el = $('

');
			el.attr('data-id', escapeHTML(this.getId()));
			el.attr('data-timestamp', escapeHTML(this.getTimestamp()));

			if (this.getLink()) {
				el.append(' '+escapeHTML(this.getSubject())+'');
			} else {
				el.append('
 '+escapeHTML(this.getSubject())+'
');
			}
			el.append('
'+escapeHTML(this.getMessage())+'
');
			// Add actions
			var actions = $('

');
			var actionsData = this.getActions();
			_.each(actionsData, function(actionData) {
				// FIXME: use handlebars template
				actions.append(
					'<button class="action-button' + (actionData.primary ? ' primary': '') + '" data-type="' + escapeHTML(actionData.type) + '" ' +
					'data-href="'+escapeHTML(actionData.link)+'">'+escapeHTML(actionData.label)+'</button>'
				);
				// TODO create event handler on click for given action type
			});
			el.append(actions);
			el.append('

');
			return el;
		},

		/**
		 * Register notification Binds
		 */
		bindNotificationEvents: function() {

		}

	};

	OCA.Notifications.Notif = Notif;

})();
<commit_msg>Limit messages to 100 chars soft and 120 chars hard<commit_after>/**
 * ownCloud - Notifications
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Tom Needham <tom@owncloud.com>
 * @copyright Tom Needham 2015
 */

(function() {

	/**
	 * Initialise the notification
	 */
	var Notif = function(jsonData){
		// TODO handle defaults
		this.app = jsonData.app;
		this.user = jsonData.user;
		this.timestamp = moment(jsonData.datetime).format('X');
		this.object_type = jsonData.object_type;
		this.object_id = jsonData.object_id;
		this.subject = jsonData.subject;
		this.message = jsonData.message;
		this.link = jsonData.link;
		this.actions = jsonData.actions; // TODO some parsing here?
		this.notification_id = jsonData.notification_id;
	};

	Notif.prototype = {

		app: null,

		user: null,

		timestamp: null,

		object_type: null,

		object_id: null,

		subject: null,

		message: null,

		link: null,

		actions: [],

		notification_id: null,

		getSubject: function() {
			return this.subject;
		},

		getTimestamp: function() {
			return this.timestamp;
		},

		getObjectId: function() {
			return this.object_id;
		},

		getLink: function() {
			return this.link;
		},

		getActions: function() {
			return this.actions;
		},

		getId: function() {
			return this.notification_id;
		},

		getMessage: function() {
			var message = this.message;

			/**
			 * Trim on word end after 100 chars or hard 120 chars
			 */
			if (message.length > 120) {
				var spacePosition = message.indexOf(' ', 100);
				if (spacePosition !== -1 && spacePosition <= 120) {
					message = message.substring(0, spacePosition);
				} else {
					message = message.substring(0, 120);
				}
				message += t('notifications', '…');
			}

			message = escapeHTML(message);
			message = message.replace(new RegExp("\n", 'g'), ' ');

			return message;
		},

		getEl: function() {
			return $('div.notification[data-id='+escapeHTML(this.getId())+']');
		},

		getApp: function() {
			return this.app;
		},

		/**
		 * Generates the HTML for the notification
		 */
		renderElement: function() {
			// FIXME: use handlebars template
			var el = $('

');
			el.attr('data-id', escapeHTML(this.getId()));
			el.attr('data-timestamp', escapeHTML(this.getTimestamp()));

			if (this.getLink()) {
				el.append(' '+escapeHTML(this.getSubject())+'');
			} else {
				el.append('
 '+escapeHTML(this.getSubject())+'
');
			}
			el.append('
'+this.getMessage()+'
');
			// Add actions
			var actions = $('

');
			var actionsData = this.getActions();
			_.each(actionsData, function(actionData) {
				// FIXME: use handlebars template
				actions.append(
					'<button class="action-button' + (actionData.primary ? ' primary': '') + '" data-type="' + escapeHTML(actionData.type) + '" ' +
					'data-href="'+escapeHTML(actionData.link)+'">'+escapeHTML(actionData.label)+'</button>'
				);
				// TODO create event handler on click for given action type
			});
			el.append(actions);
			el.append('

');
			return el;
		},

		/**
		 * Register notification Binds
		 */
		bindNotificationEvents: function() {

		}

	};

	OCA.Notifications.Notif = Notif;

})();
<|endoftext|>


<commit_before>function Oscilloscope(analyser,width,height) {
	this.analyser = analyser;
	this.data = new Uint8Array(analyser.frequencyBinCount);
	this.width = width;
	this.height = height;
}

Oscilloscope.prototype.draw = function (context) {
	var data = this.data;
	var quarterHeight = this.height/4;
	var scaling = this.height/256;

	this.analyser.getByteTimeDomainData(data);
	context.strokeStyle = "red";
	context.lineWidth = 1;
	context.fillStyle="#004737";
	context.fillRect(0,0,this.width, this.height);
	context.beginPath();
	context.moveTo(0,0);
	context.lineTo(this.width,0);
	context.stroke();
	context.moveTo(0,this.height);
	context.lineTo(this.width,this.height);
	context.stroke();
	context.save();
	context.strokeStyle = "#006644";
	context.beginPath();
	if (context.setLineDash)
		context.setLineDash([5]);
	context.moveTo(0,quarterHeight);
	context.lineTo(this.width,quarterHeight);
	context.stroke();
	context.moveTo(0,quarterHeight*3);
	context.lineTo(this.width,quarterHeight*3);
	context.stroke();

	context.restore();
	context.beginPath();
	context.strokeStyle = "blue";
	context.moveTo(0,quarterHeight*2);
	context.lineTo(this.width,quarterHeight*2);
	context.stroke();

	context.strokeStyle = "white";

	context.beginPath();
	context.moveTo(0,(256-data[0])*scaling);

	var zeroCross = findFirstPositiveZeroCrossing(data, this.width);
	if (zeroCross==0)
		zeroCross=1;

	for (var i=zeroCross, j=0; (j<(this.width+zeroCross)&&(i<data.length)); i++, j++)
		context.lineTo(j,(256-data[i])*scaling);

	context.stroke();
}

var MINVAL = 134;  // 128 == zero.  MINVAL is the "minimum detected signal" level.

function findFirstPositiveZeroCrossing(buf, buflen) {
  var i = 0;
  var last_zero = -1;
  var t;

  // advance until we're zero or negative
  while (i<buflen && (buf[i] > 128 ) )
    i++;

  if (i>=buflen)
    return 0;

  // advance until we're above MINVAL, keeping track of last zero.
  while (i<buflen && ((t=buf[i]) < MINVAL )) {
    if (t >= 128) {
      if (last_zero == -1)
        last_zero = i;
    } else
      last_zero = -1;
    i++;
  }

  // we may have jumped over MINVAL in one sample.
  if (last_zero == -1)
    last_zero = i;

  if (i==buflen)  // We didn't find any positive zero crossings
    return 0;

  // The first sample might be a zero.  If so, return it.
  if (last_zero == 0)
    return 0;

  return last_zero;
}

<commit_msg>was drawing more than necessary.<commit_after>function Oscilloscope(analyser,width,height) {
	this.analyser = analyser;
	this.data = new Uint8Array(analyser.frequencyBinCount);
	this.width = width;
	this.height = height;
}

Oscilloscope.prototype.draw = function (context) {
	var data = this.data;
	var quarterHeight = this.height/4;
	var scaling = this.height/256;

	this.analyser.getByteTimeDomainData(data);
	context.strokeStyle = "red";
	context.lineWidth = 1;
	context.fillStyle="#004737";
	context.fillRect(0,0,this.width, this.height);
	context.beginPath();
	context.moveTo(0,0);
	context.lineTo(this.width,0);
	context.stroke();
	context.moveTo(0,this.height);
	context.lineTo(this.width,this.height);
	context.stroke();
	context.save();
	context.strokeStyle = "#006644";
	context.beginPath();
	if (context.setLineDash)
		context.setLineDash([5]);
	context.moveTo(0,quarterHeight);
	context.lineTo(this.width,quarterHeight);
	context.stroke();
	context.moveTo(0,quarterHeight*3);
	context.lineTo(this.width,quarterHeight*3);
	context.stroke();

	context.restore();
	context.beginPath();
	context.strokeStyle = "blue";
	context.moveTo(0,quarterHeight*2);
	context.lineTo(this.width,quarterHeight*2);
	context.stroke();

	context.strokeStyle = "white";

	context.beginPath();
	context.moveTo(0,(256-data[0])*scaling);

	var zeroCross = findFirstPositiveZeroCrossing(data, this.width);
	if (zeroCross==0)
		zeroCross=1;

	for (var i=zeroCross, j=0; (j<this.width)&&(i<data.length); i++, j++)
		context.lineTo(j,(256-data[i])*scaling);

	context.stroke();
}

var MINVAL = 134;  // 128 == zero.  MINVAL is the "minimum detected signal" level.

function findFirstPositiveZeroCrossing(buf, buflen) {
  var i = 0;
  var last_zero = -1;
  var t;

  // advance until we're zero or negative
  while (i<buflen && (buf[i] > 128 ) )
    i++;

  if (i>=buflen)
    return 0;

  // advance until we're above MINVAL, keeping track of last zero.
  while (i<buflen && ((t=buf[i]) < MINVAL )) {
    if (t >= 128) {
      if (last_zero == -1)
        last_zero = i;
    } else
      last_zero = -1;
    i++;
  }

  // we may have jumped over MINVAL in one sample.
  if (last_zero == -1)
    last_zero = i;

  if (i==buflen)  // We didn't find any positive zero crossings
    return 0;

  // The first sample might be a zero.  If so, return it.
  if (last_zero == 0)
    return 0;

  return last_zero;
}

<|endoftext|>