<commit_before>var elasticsearch = require('elasticsearch');

exports.sitemap = function sitemap(req, res) {
    var es_client = req.app.get('es_client');
    var host_base = req.headers.host;
    var catalog = req.params.catalog;
    var offset = req.param('offset');

    var query = {
        index:'assets',
        size:20000,
        from:0,
        body:{}
    };

    if(offset && offset != undefined) {
        query.from = parseInt(offset) * 20000;
    }

    if(catalog && catalog != undefined) {
      query.body.filter = {
          and: []
      };

      query.body.filter.and.push({
        query: {
            match: {
                catalog: catalog
            }
        }
      });
    }

    es_client.search(query).then(function(search_result) {
        var sitemap = '<?xml version="1.0" encoding="UTF-8"?>\n \
                    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n \
                            xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"\n \
                            xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">\n';

        for(var i=0; i < search_result.hits.hits.length; ++i) {
            var source = search_result.hits.hits[i]._source;
            var catalog = source.catalog;
            var title = source.short_title || '';
            var description = source.description || '';
            var id = source.id;
            var url = 'http://' + host_base + '/' + catalog + '/' + id;

            var sitemap_entry = '<url>\n \
                <loc>' + url + '</loc>\n \
                <image:image>\n \
                  <image:loc>http://' + url + '/image/1200</image:loc>\n \
                  <image:title><![CDATA[' + title + ']]></image:title> \n \
                  <image:caption><![CDATA[' + description + ']]></image:caption> \n \
                </image:image>\n \
            </url>\n';

            sitemap += sitemap_entry;
        }

        sitemap += '</urlset>';
        res.header('Content-type', 'text/xml; charset=utf-8');
        res.send(sitemap);
    });
};
<commit_msg>Added proper filename for images for sitemap<commit_after>var elasticsearch = require('elasticsearch');
var querystring = require('querystring');

exports.sitemap = function sitemap(req, res) {
    var es_client = req.app.get('es_client');
    var host_base = req.headers.host;
    var catalog = req.params.catalog;
    var offset = req.param('offset');

    var query = {
        index:'assets',
        size:20000,
        from:0,
        body:{}
    };

    if(offset && offset != undefined) {
        query.from = parseInt(offset) * 20000;
    }

    if(catalog && catalog != undefined) {
      query.body.filter = {
          and: []
      };

      query.body.filter.and.push({
        query: {
            match: {
                catalog: catalog
            }
        }
      });
    }

    es_client.search(query).then(function(search_result) {
        var sitemap = '<?xml version="1.0" encoding="UTF-8"?>\n \
                    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n \
                            xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"\n \
                            xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">\n';

        for(var i=0; i < search_result.hits.hits.length; ++i) {
            var source = search_result.hits.hits[i]._source;
            var catalog = source.catalog;
            var title = source.short_title || '';
            var encoded_title = querystring.escape(title);
            var description = source.description || '';
            var id = source.id;
            var url = 'http://' + host_base + '/' + catalog + '/' + id;

            var sitemap_entry = '<url>\n \
                <loc>' + url + '</loc>\n \
                <image:image>\n \
                  <image:loc>http://' + url + '/image/1200/' + encoded_title + '.jpg</image:loc>\n \
                  <image:title><![CDATA[' + title + ']]></image:title> \n \
                  <image:caption><![CDATA[' + description + ']]></image:caption> \n \
                </image:image>\n \
            </url>\n';

            sitemap += sitemap_entry;
        }

        sitemap += '</urlset>';
        res.header('Content-type', 'text/xml; charset=utf-8');
        res.send(sitemap);
    });
};
<|endoftext|>


<commit_before>/* global Promise */

function isContext(potential) {
	'use strict';
	switch (true) {
		case (typeof potential === 'string'):
		case (Array.isArray(potential)):
		case Node && potential instanceof Node:
		case NodeList && potential instanceof NodeList:
			return true;

		case typeof potential !== 'object':
			return false;

		case potential.include !== undefined:
		case potential.exclude !== undefined:
		case typeof potential.length === 'number':
			return true;

		default:
			return false;
	}
}

/**
 * Normalize the optional params of axe.run()
 * @param  {object}   context
 * @param  {object}   options
 * @param  {Function} callback
 * @return {object}            With 3 keys: context, options, callback
 */
function normalizeRunParams(context, options, callback) {
	var typeErr = new TypeError('axe.run arguments are invalid');
	var noop = function () {};

	// Determine the context
	if (!isContext(context)) {
		if (callback !== undefined) {
			// Either context is invalid or there are too many params
			throw typeErr;
		}
		// Set default and shift one over
		callback = options;
		options = context;
		context = document;
	}

	// Determine the options
	if (typeof options !== 'object') {
		if (callback !== undefined) {
			// Either options is invalid or there are too many params
			throw typeErr;
		}
		// Set default and shift one over
		callback = options;
		options = {};
	}

	// Set the callback or noop;
	if (typeof callback === 'function' || callback === undefined) {
		callback = callback || noop;
	} else {
		throw typeErr;
	}
	return {
		context: context,
		options: options,
		callback: callback
	};
}

/**
 * Runs a number of rules against the provided HTML page and returns the
 * resulting issue list
 *
 * @param  {Object}   context  (optional) Defines the scope of the analysis
 * @param  {Object}   options  (optional) Set of options passed into rules or checks
 * @param  {Function} callback (optional) The callback when axe is done, given 2 params:
 *                             - Error    If any errors occured, otherwise null
 *                             - Results  The results object / array, or undefined on error
 * @return {Promise}           Resolves with the axe results. Only available when natively supported
 */
axe.run = function (context, options, callback) {
	if (!axe._audit) {
		throw new Error('No audit configured');
	}
	var args = normalizeRunParams(context, options, callback);
	context = args.context;
	options = args.options;
	callback = args.callback;

	// set defaults:
	options.reporter = options.reporter || 'v1';

	var p;
	var reject = noop;
	var resolve = noop;

	if (window.Promise && callback === noop) {
		p = new Promise(function (_resolve, _reject) {
			reject = _reject;
			resolve = _resolve;
		});
	}

	axe._runRules(context, options, function (rawResults) {
		var respond = function (results) {
			callback(null, results);
			resolve(results);
		};

		try {
			var reporter = axe.getReporter(options.reporter);
			var results = reporter(rawResults, respond);
			if (results !== undefined) {
				respond(results);
			}
		} catch (err) {
			callback(err);
			reject(err);
		}
	}, function (err) {
		callback(err);
		reject(err);
	});

	return p;
};<commit_msg>reworked normalizeRunParams to pass linter<commit_after>/* global Promise */

function isContext(potential) {
	'use strict';
	switch (true) {
		case (typeof potential === 'string'):
		case (Array.isArray(potential)):
		case Node && potential instanceof Node:
		case NodeList && potential instanceof NodeList:
			return true;

		case typeof potential !== 'object':
			return false;

		case potential.include !== undefined:
		case potential.exclude !== undefined:
		case typeof potential.length === 'number':
			return true;

		default:
			return false;
	}
}

var noop = function () {};

/**
 * Normalize the optional params of axe.run()
 * @param  {object}   context
 * @param  {object}   options
 * @param  {Function} callback
 * @return {object}            With 3 keys: context, options, callback
 */
function normalizeRunParams(context, options, callback) {
	'use strict';
	let typeErr = new TypeError('axe.run arguments are invalid');

	// Determine the context
	if (!isContext(context)) {
		if (callback !== undefined) {
			// Either context is invalid or there are too many params
			throw typeErr;
		}
		// Set default and shift one over
		callback = options;
		options = context;
		context = document;
	}

	// Determine the options
	if (typeof options !== 'object') {
		if (callback !== undefined) {
			// Either options is invalid or there are too many params
			throw typeErr;
		}
		// Set default and shift one over
		callback = options;
		options = {};
	}

	// Set the callback or noop;
	if (typeof callback !== 'function' && callback !== undefined) {
		throw typeErr;
	}

	return {
		context: context,
		options: options,
		callback: callback || noop
	};
}

/**
 * Runs a number of rules against the provided HTML page and returns the
 * resulting issue list
 *
 * @param  {Object}   context  (optional) Defines the scope of the analysis
 * @param  {Object}   options  (optional) Set of options passed into rules or checks
 * @param  {Function} callback (optional) The callback when axe is done, given 2 params:
 *                             - Error    If any errors occured, otherwise null
 *                             - Results  The results object / array, or undefined on error
 * @return {Promise}           Resolves with the axe results. Only available when natively supported
 */
axe.run = function (context, options, callback) {
	'use strict';
	if (!axe._audit) {
		throw new Error('No audit configured');
	}

	let args = normalizeRunParams(context, options, callback);
	context = args.context;
	options = args.options;
	callback = args.callback;

	// set defaults:
	options.reporter = options.reporter || 'v1';

	let p;
	let reject = noop;
	let resolve = noop;

	if (window.Promise && callback === noop) {
		p = new Promise(function (_resolve, _reject) {
			reject = _reject;
			resolve = _resolve;
		});
	}

	axe._runRules(context, options, function (rawResults) {
		let respond = function (results) {
			callback(null, results);
			resolve(results);
		};

		try {
			let reporter = axe.getReporter(options.reporter);
			let results = reporter(rawResults, respond);
			if (results !== undefined) {
				respond(results);
			}
		} catch (err) {
			callback(err);
			reject(err);
		}
	}, function (err) {
		callback(err);
		reject(err);
	});

	return p;
};<|endoftext|>


<commit_before>var request = require( 'request' );
var async = require( 'async' );
var _ = require( 'underscore' );
var moment = require( 'moment' );
var parseString = require('xml2js').parseString;
var apiRequest = require( "./utils" ).apiRequest;
var convertXML = require( "./utils" ).convertXML;

module.exports = function ( apiKey ) {

    if ( !apiKey ) {
        throw new Error( "CTA Bustracker requires an API key" );
    }

    var apiUrl = "http://www.ctabustracker.com/bustime/api/v1";

    var baseOptions = {
        qs: {
            key: apiKey
        },
        method: "GET"
    };

    return {
        getTime: function ( cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/gettime";

            var makeRequest = function ( done ) {
                return apiRequest( options, done );
            };

            async.waterfall( [ makeRequest, convertXML ],
                function ( err, data ) {

                    if ( err ) {
                        return cb( err );
                    }
                    return cb( null, data );

                } );
        },
        getVehiclesById: function ( vehicleIds, cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/getvehicles";
            options.qs.vid = vehicleIds.join( "," );

            var makeRequest = function ( done ) {
                return apiRequest( options, done );
            };

            async.waterfall( [ makeRequest, convertXML ],
                function ( err, data ) {

                    if ( err ) {
                        return cb( err );
                    }
                    return cb( null, data );

                } );
        },
        getVehiclesByRoute: function ( routeIds, cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/getvehicles";
            options.qs.rt = routeIds.join( "," );

            var makeRequest = function ( done ) {
                return apiRequest( options, done );
            };

            async.waterfall( [ makeRequest, convertXML ],
                function ( err, data ) {

                    if ( err ) {
                        return cb( err );
                    }
                    return cb( null, data );

                } );
        }
    };

};
<commit_msg>Refactor makeRequest<commit_after>var request = require( 'request' );
var async = require( 'async' );
var _ = require( 'underscore' );
var moment = require( 'moment' );
var parseString = require('xml2js').parseString;
var apiRequest = require( "./utils" ).apiRequest;
var convertXML = require( "./utils" ).convertXML;

module.exports = function ( apiKey ) {

    if ( !apiKey ) {
        throw new Error( "CTA Bustracker requires an API key" );
    }

    var apiUrl = "http://www.ctabustracker.com/bustime/api/v1";

    var baseOptions = {
        qs: {
            key: apiKey
        },
        method: "GET"
    };

    var requestFactory = function ( options ) {
        return function ( done ) {
            return apiRequest( options, done );
        };
    };

    return {
        getTime: function ( cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/gettime";

            var makeRequest = requestFactory( options );

            async.waterfall( [ makeRequest, convertXML ],
                function ( err, data ) {

                    if ( err ) {
                        return cb( err );
                    }
                    return cb( null, data );

                } );
        },
        getVehiclesById: function ( vehicleIds, cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/getvehicles";
            options.qs.vid = vehicleIds.join( "," );

            var makeRequest = requestFactory( options );

            async.waterfall( [ makeRequest, convertXML ],
                function ( err, data ) {

                    if ( err ) {
                        return cb( err );
                    }
                    return cb( null, data );

                } );
        },
        getVehiclesByRoute: function ( routeIds, cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/getvehicles";
            options.qs.rt = routeIds.join( "," );

            var makeRequest = requestFactory( options );

            async.waterfall( [ makeRequest, convertXML ],
                function ( err, data ) {

                    if ( err ) {
                        return cb( err );
                    }
                    return cb( null, data );

                } );
        },
        getRoutes: function ( cb ) {
            var options = _.clone( baseOptions );
            options.url = apiUrl + "/getroutes";

            var makeRequest = requestFactory( options );
        }
    };

};
<|endoftext|>


<commit_before>/*
 * Copyright 2005-2012 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Toggles a tab to show / hide and changes the source image to properly reflect this
// change. Returns false to avoid post. Example usage:
// onclick="javascript: return toggleTab(document, this, ${currentTabIndex}) }
function toggleTab(doc, tabKey) {
	if (doc.forms[0].elements['tabStates(' + tabKey + ')'].value == 'CLOSE') {
        showTab(doc, tabKey);
    } else {
        hideTab(doc, tabKey);
	}
	return false;
}

/** expands all tabs by unhiding them. */
function expandAllTab() {
	doToAllTabs(showTab);
	return false;
	}

/** collapses all tab by hiding them. */
function collapseAllTab() {
	doToAllTabs(hideTab);
	return false;
}

/** executes a function on all tabs.  The function will be passed a document & partial tab name. */
function doToAllTabs(func) {
	var elements = document.getElementsByTagName('div');

	for (var x in elements) {
		if (elements[x].id && elements[x].id.substring(0, 4) === 'tab-'
			&& elements[x].id.substring(elements[x].id.length - 4, elements[x].id.length) === '-div') {
			func(document, elements[x].id.substring(4, elements[x].id.length - 4));
		}
	}
	return false;
}

function showTab(doc, tabKey) {
    if (!doc.getElementById('tab-' + tabKey + '-div') || !doc.getElementById('tab-' + tabKey + '-imageToggle')) {
		return false;
	}

    // replaced 'block' with '' to make budgetExpensesRow.tag happy.
    doc.getElementById('tab-' + tabKey + '-div').style.display = '';
    doc.forms[0].elements['tabStates(' + tabKey + ')'].value = 'OPEN';
    var image = doc.getElementById('tab-' + tabKey + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-hide.gif';
    image.alt = image.alt.replace(/^show/, 'hide');
    image.alt = image.alt.replace(/^open/, 'close');
    image.title = image.title.replace(/^show/, 'hide');
    image.title = image.title.replace(/^open/, 'close');
    return false;
}

function hideTab(doc, tabKey) {
    if (!doc.getElementById('tab-' + tabKey + '-div') || !doc.getElementById('tab-' + tabKey + '-imageToggle')) {
		return false;
	}

    doc.getElementById('tab-' + tabKey + '-div').style.display = 'none';
    doc.forms[0].elements['tabStates(' + tabKey + ')'].value = 'CLOSE';
    var image = doc.getElementById('tab-' + tabKey + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-show.gif';
    image.alt = image.alt.replace(/^hide/, 'show');
    image.alt = image.alt.replace(/^close/, 'open');
    image.title = image.title.replace(/^hide/, 'show');
    image.title = image.title.replace(/^close/, 'open');
    return false;
}

var formHasAlreadyBeenSubmitted = false;
var excludeSubmitRestriction = false;

function hasFormAlreadyBeenSubmitted() {
//	alert( "submitting form" );
	try {
		// save the current scroll position
		saveScrollPosition();
	} catch ( ex ) {
		// do nothing - don't want to stop submit
	}

	if ( document.getElementById( "formComplete" ) ) {
	    if (formHasAlreadyBeenSubmitted && !excludeSubmitRestriction) {
	       alert("Page already being processed by the server.");
	       return false;
	    } else {
	       formHasAlreadyBeenSubmitted = true;
	       return true;
	    }
	    excludeSubmitRestriction = false;
    } else {
	       alert("Page has not finished loading.");
	       return false;
	}
}

// Called when we want to submit the form from a field event and
// want focus to be placed on the next field according to the current tab order
// when the page refreshes
function setFieldToFocusAndSubmit(triggerElement) {
	if(document.forms[0].fieldNameToFocusOnAfterSubmit) {
		if (document.forms.length > 0) {
			var nextTabField;
			var field = document.forms[0];
			for (i = 0; i < field.length; i++) {
				if (field.elements[i].tabIndex > triggerElement.tabIndex) {
					if (nextTabField) {
						if (field.elements[i].tabIndex < nextTabField.tabIndex) {
					       nextTabField = field.elements[i];
			         	}
					}
		       	    else {
				       nextTabField = field.elements[i];
			        }
				}
			}

	        if (nextTabField) {
	        	document.forms[0].fieldNameToFocusOnAfterSubmit.value = nextTabField.name;
	        }
		}
	}

    document.forms[0].submit();
}

function submitForm() {
    document.forms[0].submit();
}

function resetScrollPosition() {
	window.scrollTo(0,0);
	parent.window.scrollTo(0,0);
}

function saveScrollPosition() {
//	alert( document.forms[0].formKey );
	if ( document.forms[0].formKey ) {
		formKey = document.forms[0].formKey.value;
		if( document.documentElement ) {
			x = Math.max(parent.document.documentElement.scrollLeft, parent.document.body.scrollLeft);
		  	y = Math.max(parent.document.documentElement.scrollTop, parent.document.body.scrollTop);
		} else if( document.body && typeof document.body.scrollTop != "undefined" ) {
			x = parent.document.body.scrollLeft;
		  	y = parent.document.body.scrollTop;
		} else if ( typeof window.pageXOffset != "undefined" ) {
			x = parent.window.pageXOffset;
		  	y = parent.window.pageYOffset;
		}
		document.cookie = "KulScrollPos"+formKey+"="+x+","+y+"; path="+document.location.pathname;
	}
	// test read cookie back
//	matchResult = document.cookie.match(new RegExp("KulScrollPos"+formKey+"=([^;]+);?"));
//	if ( matchResult ) {
//		alert( "Cookie: " + matchResult[1] );
//	}
}

function restoreScrollPosition() {
    if ( document.forms[0].formKey ) {
        formKey = document.forms[0].formKey.value;
        var cookieName = "KulScrollPos"+formKey;
        var matchResult = document.cookie.match(new RegExp(cookieName+"=([^;]+);?"));
        if ( matchResult ) {
            var coords = matchResult[1].split( ',' );
            window.scrollTo(coords[0],coords[1]);
            parent.window.scrollTo(coords[0],coords[1]);
            expireCookie( cookieName );
            return true;
        } else { // check for entry before form key set
        	cookieName = "KulScrollPos";
	        var matchResult = document.cookie.match(new RegExp(cookieName+"=([^;]+);?"));
	        if ( matchResult ) {
	            var coords = matchResult[1].split( ',' );
	            window.scrollTo(coords[0],coords[1]);
	            parent.window.scrollTo(coords[0],coords[1]);
	            expireCookie( cookieName );
	            return true;
	        } //else {
	        	//no match for cookie... new screen???
	        	//resetScrollPosition();
	        //}

        }
    }
    return false;
}

function expireCookie( cookieName ) {
	var date = new Date();
	date.setTime( date.getTime() - 60000 );
	document.cookie = cookieName+"=0,0; expires="+date.toGMTString()+"; path="+document.location.pathname;
}

/* script to prevent the return key from submitting a form unless the user is on a button or on a link. fix for KULFDBCK-555 */
function isReturnKeyAllowed(buttonPrefix , event) {
	/* use IE naming first then firefox. */
    var elemType = event.srcElement ? event.srcElement.type : event.target.type;
    if (elemType != null && elemType.toLowerCase() == 'textarea') {
      // KULEDOCS-1728: textareas need to have the return key enabled
      return true;
    }
	var initiator = event.srcElement ? event.srcElement.name : event.target.name;
	var key = event.keyCode;
	/* initiator is undefined check is to prevent return from doing anything if not in a form field since the initiator is undefined */
	/* 13 is return key code */
	/* length > 0 check is to allow user to hit return on links */
	if ( key == 13 ) {
		if( initiator == undefined || ( initiator.indexOf(buttonPrefix) != 0 && initiator.length > 0) ) {
		  // disallow enter key from fields that dont match prefix.
		  return false;
		}
	}
    return true;
}

//The following javascript is intended to resize the route log iframe
// to stay at an appropriate height based on the size of the documents
// contents contained in the iframe.
//  NOTE: this will only work when the domain serving the content of kuali
//         is the same as the domain serving the content of workflow.
var routeLogResizeTimer = ""; // holds the timer for the  route log iframe resizer
var currentHeight = 500; // holds the current height of the iframe
var safari = navigator.userAgent.toLowerCase().indexOf('safari');

function setRouteLogIframeDimensions() {
  var routeLogFrame = document.getElementById("routeLogIFrame");
  var routeLogFrame = document.getElementById("routeLogIFrame");
  var routeLogFrameWin = window.frames["routeLogIFrame"];
  var frameDocHeight = 0;
  try {
    frameDocHeight = routeLogFrameWin.document.documentElement.scrollHeight;
  } catch ( e ) {
    // unable to set due to cross-domain scripting
    frameDocHeight = 0;
  }

  if ( frameDocHeight > 0 ) {
	  if (routeLogFrame && routeLogFrameWin) {

	    if ((Math.abs(frameDocHeight - currentHeight)) > 30 ) {
	      if (safari > -1) {
	        if ((Math.abs(frameDocHeight - currentHeight)) > 59 ) {
	          routeLogFrame.style.height = (frameDocHeight + 30) + "px";
	          currentHeight = frameDocHeight;
	        }
	      } else {
	        routeLogFrame.style.height = (frameDocHeight + 30) + "px";
	        currentHeight = frameDocHeight;
	      }
	    }
	  }
  }

	    if (routeLogResizeTimer == "" ) {
	      routeLogResizeTimer = setInterval("resizeTheRouteLogFrame()",300);
	    }
	  }

function resizeTheRouteLogFrame() {
  setRouteLogIframeDimensions();
}

// should be in rice for direct inquiry
 function inquiryPop(boClassName, inquiryParameters){
  parameterPairs = inquiryParameters.split(",");
  queryString="businessObjectClassName="+boClassName+"&methodToCall=start"
  for (i in parameterPairs) {

    parameters = parameterPairs[i].split(":");
  	if (document.forms[0].elements[parameters[0]].value=="")
  	{
  		alert("Please enter a value in the appropriate field.");
  		//queryString=queryString+"&"+parameters[1]+"=directInquiryParameterNotSpecified";
		return false;
  	} else {
    	queryString=queryString+"&"+parameters[1]+"="+document.forms[0].elements[parameters[0]].value;
  	}
  }
  url=window.location.href
  pathname=window.location.pathname
  idx1=url.indexOf(pathname);
  idx2=url.indexOf("/",idx1+1);
  baseUrl=url.substr(0,idx2)
  window.open(baseUrl+"/kr/directInquiry.do?"+queryString, "_blank", "width=640, height=600, scrollbars=yes");
}

function textAreaPop(textAreaName, htmlFormAction, textAreaLabel, docFormKey, textAreaReadOnly, textAreaMaxLength) {

	if (textAreaReadOnly === null || textAreaReadOnly === undefined) {
		textAreaReadOnly = false;
	}

	if (textAreaMaxLength === null || textAreaMaxLength === undefined) {
		textAreaMaxLength = "";
	}

	var documentWebScope="session"
	window.open("updateTextArea.do?textAreaFieldName="+textAreaName+"&htmlFormAction="+htmlFormAction+"&textAreaFieldLabel="+textAreaLabel+"&docFormKey="+docFormKey+"&documentWebScope="+documentWebScope+"&textAreaReadOnly="+textAreaReadOnly+"&textAreaMaxLength="+textAreaMaxLength, "_blank", "width=650, height=650, scrollbars=yes");
}

function setTextArea(textAreaName) {
  document.getElementById(textAreaName).value = window.opener.document.getElementById(textAreaName).value;
}

function textLimit(taElement, maxlen)
{
	var fieldValue = taElement.value;
    if (fieldValue.length > maxlen)
    {
	    taElement.value = taElement.value.substr(0, maxlen);
    }
}

function postValueToParentWindow(textAreaName) {
  window.opener.document.getElementById(textAreaName).value = document.getElementById(textAreaName).value;
  self.close();
}

function showHide(showId,hideId){
  var style_sheet = getStyleObject(showId);
  if (style_sheet)
  {
	changeObjectVisibility(showId, "block");
	changeObjectVisibility(hideId, "none");
  }
  else
  {
    alert("sorry, this only works in browsers that do Dynamic HTML");
  }
}

function changeObjectVisibility(objectId, newVisibility) {
    // first get the object's stylesheet
    var styleObject = getStyleObject(objectId);

    // then if we find a stylesheet, set its visibility
    // as requested
    //
    if (styleObject) {
		styleObject.display = newVisibility;
	return true;
    } else {
	return false;
    }
}

function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  //
  if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {
	return document.all(objectId).style;
   }
   else if (document.layers && document.layers[objectId]) {
	return document.layers[objectId];
   } else {
	return false;
   }
}

// used on multiple value lookup pages to support the select/deselect all on page functions
function setAllMultipleValueLookuResults(checked) {
	for (i = 0; i < kualiElements.length; i++) {
		if (kualiElements[i].type == 'checkbox' && kualiElements[i].name.match('^selectedObjId-') == 'selectedObjId-') {
			kualiElements[i].checked = checked;
		}
	}
}
function placeFocus() {
	if (document.forms.length > 0) {
	  var fieldNameToFocus;
	  if (document.forms[0].fieldNameToFocusOnAfterSubmit) {
	    fieldNameToFocus = document.forms[0].fieldNameToFocusOnAfterSubmit.value;
	  }

	  var focusSet = false;
	  var field = document.forms[0];
	  for (i = 0; i < field.length; i++) {
		if (fieldNameToFocus) {
	  	  if (field.elements[i].name == fieldNameToFocus) {
			  document.forms[0].elements[i].focus();
			  focusSet = true;
		  }
		}
		else if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea")) {
		  document.forms[0].elements[i].focus();
		  focusSet = true;
		}

		if (focusSet) {
			break;
		}
	  }
   }
}
<commit_msg>KULRICE-5687 - Fixing path used on servers with /kr/ already included (so as not to include it twice).<commit_after>/*
 * Copyright 2005-2012 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Toggles a tab to show / hide and changes the source image to properly reflect this
// change. Returns false to avoid post. Example usage:
// onclick="javascript: return toggleTab(document, this, ${currentTabIndex}) }
function toggleTab(doc, tabKey) {
	if (doc.forms[0].elements['tabStates(' + tabKey + ')'].value == 'CLOSE') {
        showTab(doc, tabKey);
    } else {
        hideTab(doc, tabKey);
	}
	return false;
}

/** expands all tabs by unhiding them. */
function expandAllTab() {
	doToAllTabs(showTab);
	return false;
	}

/** collapses all tab by hiding them. */
function collapseAllTab() {
	doToAllTabs(hideTab);
	return false;
}

/** executes a function on all tabs.  The function will be passed a document & partial tab name. */
function doToAllTabs(func) {
	var elements = document.getElementsByTagName('div');

	for (var x in elements) {
		if (elements[x].id && elements[x].id.substring(0, 4) === 'tab-'
			&& elements[x].id.substring(elements[x].id.length - 4, elements[x].id.length) === '-div') {
			func(document, elements[x].id.substring(4, elements[x].id.length - 4));
		}
	}
	return false;
}

function showTab(doc, tabKey) {
    if (!doc.getElementById('tab-' + tabKey + '-div') || !doc.getElementById('tab-' + tabKey + '-imageToggle')) {
		return false;
	}

    // replaced 'block' with '' to make budgetExpensesRow.tag happy.
    doc.getElementById('tab-' + tabKey + '-div').style.display = '';
    doc.forms[0].elements['tabStates(' + tabKey + ')'].value = 'OPEN';
    var image = doc.getElementById('tab-' + tabKey + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-hide.gif';
    image.alt = image.alt.replace(/^show/, 'hide');
    image.alt = image.alt.replace(/^open/, 'close');
    image.title = image.title.replace(/^show/, 'hide');
    image.title = image.title.replace(/^open/, 'close');
    return false;
}

function hideTab(doc, tabKey) {
    if (!doc.getElementById('tab-' + tabKey + '-div') || !doc.getElementById('tab-' + tabKey + '-imageToggle')) {
		return false;
	}

    doc.getElementById('tab-' + tabKey + '-div').style.display = 'none';
    doc.forms[0].elements['tabStates(' + tabKey + ')'].value = 'CLOSE';
    var image = doc.getElementById('tab-' + tabKey + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-show.gif';
    image.alt = image.alt.replace(/^hide/, 'show');
    image.alt = image.alt.replace(/^close/, 'open');
    image.title = image.title.replace(/^hide/, 'show');
    image.title = image.title.replace(/^close/, 'open');
    return false;
}

var formHasAlreadyBeenSubmitted = false;
var excludeSubmitRestriction = false;

function hasFormAlreadyBeenSubmitted() {
//	alert( "submitting form" );
	try {
		// save the current scroll position
		saveScrollPosition();
	} catch ( ex ) {
		// do nothing - don't want to stop submit
	}

	if ( document.getElementById( "formComplete" ) ) {
	    if (formHasAlreadyBeenSubmitted && !excludeSubmitRestriction) {
	       alert("Page already being processed by the server.");
	       return false;
	    } else {
	       formHasAlreadyBeenSubmitted = true;
	       return true;
	    }
	    excludeSubmitRestriction = false;
    } else {
	       alert("Page has not finished loading.");
	       return false;
	}
}

// Called when we want to submit the form from a field event and
// want focus to be placed on the next field according to the current tab order
// when the page refreshes
function setFieldToFocusAndSubmit(triggerElement) {
	if(document.forms[0].fieldNameToFocusOnAfterSubmit) {
		if (document.forms.length > 0) {
			var nextTabField;
			var field = document.forms[0];
			for (i = 0; i < field.length; i++) {
				if (field.elements[i].tabIndex > triggerElement.tabIndex) {
					if (nextTabField) {
						if (field.elements[i].tabIndex < nextTabField.tabIndex) {
					       nextTabField = field.elements[i];
			         	}
					}
		       	    else {
				       nextTabField = field.elements[i];
			        }
				}
			}

	        if (nextTabField) {
	        	document.forms[0].fieldNameToFocusOnAfterSubmit.value = nextTabField.name;
	        }
		}
	}

    document.forms[0].submit();
}

function submitForm() {
    document.forms[0].submit();
}

function resetScrollPosition() {
	window.scrollTo(0,0);
	parent.window.scrollTo(0,0);
}

function saveScrollPosition() {
//	alert( document.forms[0].formKey );
	if ( document.forms[0].formKey ) {
		formKey = document.forms[0].formKey.value;
		if( document.documentElement ) {
			x = Math.max(parent.document.documentElement.scrollLeft, parent.document.body.scrollLeft);
		  	y = Math.max(parent.document.documentElement.scrollTop, parent.document.body.scrollTop);
		} else if( document.body && typeof document.body.scrollTop != "undefined" ) {
			x = parent.document.body.scrollLeft;
		  	y = parent.document.body.scrollTop;
		} else if ( typeof window.pageXOffset != "undefined" ) {
			x = parent.window.pageXOffset;
		  	y = parent.window.pageYOffset;
		}
		document.cookie = "KulScrollPos"+formKey+"="+x+","+y+"; path="+document.location.pathname;
	}
	// test read cookie back
//	matchResult = document.cookie.match(new RegExp("KulScrollPos"+formKey+"=([^;]+);?"));
//	if ( matchResult ) {
//		alert( "Cookie: " + matchResult[1] );
//	}
}

function restoreScrollPosition() {
    if ( document.forms[0].formKey ) {
        formKey = document.forms[0].formKey.value;
        var cookieName = "KulScrollPos"+formKey;
        var matchResult = document.cookie.match(new RegExp(cookieName+"=([^;]+);?"));
        if ( matchResult ) {
            var coords = matchResult[1].split( ',' );
            window.scrollTo(coords[0],coords[1]);
            parent.window.scrollTo(coords[0],coords[1]);
            expireCookie( cookieName );
            return true;
        } else { // check for entry before form key set
        	cookieName = "KulScrollPos";
	        var matchResult = document.cookie.match(new RegExp(cookieName+"=([^;]+);?"));
	        if ( matchResult ) {
	            var coords = matchResult[1].split( ',' );
	            window.scrollTo(coords[0],coords[1]);
	            parent.window.scrollTo(coords[0],coords[1]);
	            expireCookie( cookieName );
	            return true;
	        } //else {
	        	//no match for cookie... new screen???
	        	//resetScrollPosition();
	        //}

        }
    }
    return false;
}

function expireCookie( cookieName ) {
	var date = new Date();
	date.setTime( date.getTime() - 60000 );
	document.cookie = cookieName+"=0,0; expires="+date.toGMTString()+"; path="+document.location.pathname;
}

/* script to prevent the return key from submitting a form unless the user is on a button or on a link. fix for KULFDBCK-555 */
function isReturnKeyAllowed(buttonPrefix , event) {
	/* use IE naming first then firefox. */
    var elemType = event.srcElement ? event.srcElement.type : event.target.type;
    if (elemType != null && elemType.toLowerCase() == 'textarea') {
      // KULEDOCS-1728: textareas need to have the return key enabled
      return true;
    }
	var initiator = event.srcElement ? event.srcElement.name : event.target.name;
	var key = event.keyCode;
	/* initiator is undefined check is to prevent return from doing anything if not in a form field since the initiator is undefined */
	/* 13 is return key code */
	/* length > 0 check is to allow user to hit return on links */
	if ( key == 13 ) {
		if( initiator == undefined || ( initiator.indexOf(buttonPrefix) != 0 && initiator.length > 0) ) {
		  // disallow enter key from fields that dont match prefix.
		  return false;
		}
	}
    return true;
}

//The following javascript is intended to resize the route log iframe
// to stay at an appropriate height based on the size of the documents
// contents contained in the iframe.
//  NOTE: this will only work when the domain serving the content of kuali
//         is the same as the domain serving the content of workflow.
var routeLogResizeTimer = ""; // holds the timer for the  route log iframe resizer
var currentHeight = 500; // holds the current height of the iframe
var safari = navigator.userAgent.toLowerCase().indexOf('safari');

function setRouteLogIframeDimensions() {
  var routeLogFrame = document.getElementById("routeLogIFrame");
  var routeLogFrame = document.getElementById("routeLogIFrame");
  var routeLogFrameWin = window.frames["routeLogIFrame"];
  var frameDocHeight = 0;
  try {
    frameDocHeight = routeLogFrameWin.document.documentElement.scrollHeight;
  } catch ( e ) {
    // unable to set due to cross-domain scripting
    frameDocHeight = 0;
  }

  if ( frameDocHeight > 0 ) {
	  if (routeLogFrame && routeLogFrameWin) {

	    if ((Math.abs(frameDocHeight - currentHeight)) > 30 ) {
	      if (safari > -1) {
	        if ((Math.abs(frameDocHeight - currentHeight)) > 59 ) {
	          routeLogFrame.style.height = (frameDocHeight + 30) + "px";
	          currentHeight = frameDocHeight;
	        }
	      } else {
	        routeLogFrame.style.height = (frameDocHeight + 30) + "px";
	        currentHeight = frameDocHeight;
	      }
	    }
	  }
  }

	    if (routeLogResizeTimer == "" ) {
	      routeLogResizeTimer = setInterval("resizeTheRouteLogFrame()",300);
	    }
	  }

function resizeTheRouteLogFrame() {
  setRouteLogIframeDimensions();
}

// should be in rice for direct inquiry
 function inquiryPop(boClassName, inquiryParameters){
  parameterPairs = inquiryParameters.split(",");
  queryString="businessObjectClassName="+boClassName+"&methodToCall=start"
  for (i in parameterPairs) {

    parameters = parameterPairs[i].split(":");
  	if (document.forms[0].elements[parameters[0]].value=="")
  	{
  		alert("Please enter a value in the appropriate field.");
  		//queryString=queryString+"&"+parameters[1]+"=directInquiryParameterNotSpecified";
		return false;
  	} else {
    	queryString=queryString+"&"+parameters[1]+"="+document.forms[0].elements[parameters[0]].value;
  	}
  }
  url=window.location.href
  pathname=window.location.pathname
  idx1=url.indexOf(pathname);
  idx2=url.indexOf("/",idx1+1);
  baseUrl=url.substr(0,idx2)

  if (baseUrl.length > 3 && baseUrl.substr(baseUrl.length - 3)=="/kr") {
    window.open(baseUrl+"/directInquiry.do?"+queryString, "_blank", "width=640, height=600, scrollbars=yes");
  }
  else {
    window.open(baseUrl+"/kr/directInquiry.do?"+queryString, "_blank", "width=640, height=600, scrollbars=yes");
  }
}

function textAreaPop(textAreaName, htmlFormAction, textAreaLabel, docFormKey, textAreaReadOnly, textAreaMaxLength) {

	if (textAreaReadOnly === null || textAreaReadOnly === undefined) {
		textAreaReadOnly = false;
	}

	if (textAreaMaxLength === null || textAreaMaxLength === undefined) {
		textAreaMaxLength = "";
	}

	var documentWebScope="session"
	window.open("updateTextArea.do?textAreaFieldName="+textAreaName+"&htmlFormAction="+htmlFormAction+"&textAreaFieldLabel="+textAreaLabel+"&docFormKey="+docFormKey+"&documentWebScope="+documentWebScope+"&textAreaReadOnly="+textAreaReadOnly+"&textAreaMaxLength="+textAreaMaxLength, "_blank", "width=650, height=650, scrollbars=yes");
}

function setTextArea(textAreaName) {
  document.getElementById(textAreaName).value = window.opener.document.getElementById(textAreaName).value;
}

function textLimit(taElement, maxlen)
{
	var fieldValue = taElement.value;
    if (fieldValue.length > maxlen)
    {
	    taElement.value = taElement.value.substr(0, maxlen);
    }
}

function postValueToParentWindow(textAreaName) {
  window.opener.document.getElementById(textAreaName).value = document.getElementById(textAreaName).value;
  self.close();
}

function showHide(showId,hideId){
  var style_sheet = getStyleObject(showId);
  if (style_sheet)
  {
	changeObjectVisibility(showId, "block");
	changeObjectVisibility(hideId, "none");
  }
  else
  {
    alert("sorry, this only works in browsers that do Dynamic HTML");
  }
}

function changeObjectVisibility(objectId, newVisibility) {
    // first get the object's stylesheet
    var styleObject = getStyleObject(objectId);

    // then if we find a stylesheet, set its visibility
    // as requested
    //
    if (styleObject) {
		styleObject.display = newVisibility;
	return true;
    } else {
	return false;
    }
}

function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  //
  if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {
	return document.all(objectId).style;
   }
   else if (document.layers && document.layers[objectId]) {
	return document.layers[objectId];
   } else {
	return false;
   }
}

// used on multiple value lookup pages to support the select/deselect all on page functions
function setAllMultipleValueLookuResults(checked) {
	for (i = 0; i < kualiElements.length; i++) {
		if (kualiElements[i].type == 'checkbox' && kualiElements[i].name.match('^selectedObjId-') == 'selectedObjId-') {
			kualiElements[i].checked = checked;
		}
	}
}
function placeFocus() {
	if (document.forms.length > 0) {
	  var fieldNameToFocus;
	  if (document.forms[0].fieldNameToFocusOnAfterSubmit) {
	    fieldNameToFocus = document.forms[0].fieldNameToFocusOnAfterSubmit.value;
	  }

	  var focusSet = false;
	  var field = document.forms[0];
	  for (i = 0; i < field.length; i++) {
		if (fieldNameToFocus) {
	  	  if (field.elements[i].name == fieldNameToFocus) {
			  document.forms[0].elements[i].focus();
			  focusSet = true;
		  }
		}
		else if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea")) {
		  document.forms[0].elements[i].focus();
		  focusSet = true;
		}

		if (focusSet) {
			break;
		}
	  }
   }
}
<|endoftext|>


<commit_before>dojo.provide("dojox.lang.aspect");

(function(){
	var d = dojo, aop = dojox.lang.aspect, ap = Array.prototype,
		contextStack = [], context;

	// this class implements a topic-based double-linked list
	var Advice = function(){
		this.next_before = this.prev_before =
		this.next_around = this.prev_around =
		this.next_afterReturning = this.prev_afterReturning =
		this.next_afterThrowing = this.prev_afterThrowing =
			this;
		this.counter = 0;
	};
	d.extend(Advice, {
		add: function(advice){
			var dyn = d.isFunction(advice),
				node = {advice: advice, dynamic: dyn};
			this._add(node, "before", "", dyn, advice);
			this._add(node, "around", "", dyn, advice);
			this._add(node, "after", "Returning", dyn, advice);
			this._add(node, "after", "Throwing", dyn, advice);
			++this.counter;
			return node;
		},
		_add: function(node, topic, subtopic, dyn, advice){
			var full = topic + subtopic;
			if(dyn || advice[topic] || (subtopic && advice[full])){
				var next = "next_" + full, prev = "prev_" + full;
				(node[prev] = this[prev])[next] = node;
				(node[next] = this)[prev] = node;
			}
		},
		remove: function(node){
			this._remove(node, "before");
			this._remove(node, "around");
			this._remove(node, "afterReturning");
			this._remove(node, "afterThrowing");
			--this.counter;
		},
		_remove: function(node, topic){
			var next = "next_" + topic, prev = "prev_" + topic;
			if(node[next]){
				node[next][prev] = node[prev];
				node[prev][next] = node[next];
			}
		},
		isEmpty: function(){
			return !this.counter;
		}
	});

	var getDispatcher = function(){

		return function(){

			var self = arguments.callee,	// the join point
				advices = self.advices,		// list of advices for this joinpoint
				ret, i, a, e, t;

			// push context
			if(context){ contextStack.push(context); }
			context = {
				instance: this,					// object instance
				joinPoint: self,				// join point
				depth: contextStack.length,		// current level of depth starting from 0
				around: advices.prev_around,	// pointer to the current around advice
				dynAdvices: [],					// array of dynamic advices if any
				dynIndex: 0						// index of a dynamic advice
			};

			try{
				// process before events
				for(i = advices.prev_before; i != advices; i = i.prev_before){
					if(i.dynamic){
						// instantiate a dynamic advice
						context.dynAdvices.push(a = new i.advice(context));
						if(t = a.before){
							t.apply(a, arguments);
						}
					}else{
						t = i.advice;
						t.before.apply(t, arguments);
					}
				}

				// process around and after events
				try{
					// call the around advice or the original method
					ret = aop.proceed.apply(null, arguments);
				}catch(e){
					// process after throwing and after events
					context.dynIndex = context.dynAdvices.length;
					for(i = advices.next_afterThrowing; i != advices; i = i.next_afterThrowing){
						a = i.dynamic ? context.dynAdvices[--context.dynIndex] : i.advice;
						if(t = a.afterThrowing){
							t.call(a, e);
						}
						if(t = a.after){
							t.call(a);
						}
					}
					// continue the exception processing
					throw e;
				}
				// process after returning and after events
				context.dynIndex = context.dynAdvices.length;
				for(i = advices.next_afterReturning; i != advices; i = i.next_afterReturning){
					a = i.dynamic ? context.dynAdvices[--context.dynIndex] : i.advice;
					if(t = a.afterReturning){
						t.call(a, ret);
					}
					if(t = a.after){
						t.call(a);
					}
				}
				// process dojo.connect() listeners
				var ls = self._listeners;
				for(i in ls){
					if(!(i in ap)){
						ls[i].apply(this, arguments);
					}
				}
			}finally{
				// destroy dynamic advices
				for(i = 0; i < context.dynAdvices.length; ++i){
					a = context.dynAdvices[i];
					if(a.destroy){
						a.destroy();
					}
				}
				// pop context
				context = contextStack.length ? contextStack.pop() : null;
			}

			return ret;
		};
	};

	aop.advise = function(/*Object*/ obj,
						/*String|RegExp|Array*/ method,
						/*Object|Function|Array*/ advice
						){
		// summary:
		//		Attach AOP-style advices to a method.
		//
		// description:
		//		Attaches AOP-style advices to a method. Can attach several
		//		advices at once and operate on several methods of an object.
		//		The latter is achieved when a RegExp is specified as
		//		a method name, or an array of strings and regular expressions
		//		is used. In this case all functional methods that
		//		satisfy the RegExp condition are processed. This function
		//		returns a handle, which can be used to unadvise, or null,
		//		if advising has failed.
		//
		//		This function is a convenience wrapper for
		//		dojox.lang.aspect.adviseRaw().
		//
		// obj:
		//		A source object for the advised function. Cannot be a DOM node.
		//		If this object is a constructor, its prototype is advised.
		//
		// method:
		//		A string name of the function in obj. In case of RegExp all
		//		methods of obj matching the regular expression are advised.
		//
		// advice:
		//		An object, which defines advises, or a function, which
		//		returns such object, or an array of previous items.
		//		The advice object can define following member functions:
		//		before, around, afterReturning, afterThrowing, after.
		//		If the function is supplied, it is called with a context
		//		object once per call to create a temporary advice object, which
		//		is destroyed after the processing. The temporary advice object
		//		can implement a destroy() method, if it wants to be called when
		//		not needed.

		if(typeof obj != "object"){
			obj = obj.prototype;
		}

		var methods = [];
		if(!(method instanceof Array)){
			method = [method];
		}

		// identify advised methods
		for(var j = 0; j < method.length; ++j){
			var t = method[j];
			if(t instanceof RegExp){
				for(var i in obj){
					if(d.isFunction(obj[i]) && t.test(i)){
						methods.push(i);
					}
				}
			}else{
				if(d.isFunction(obj[t])){
					methods.push(t);
				}
			}
		}

		if(!d.isArray(advice)){ advice = [advice]; }

		return aop.adviseRaw(obj, methods, advice);	// Object
	};

	aop.adviseRaw = function(/*Object*/ obj,
						/*Array*/ methods,
						/*Array*/ advices
						){
		// summary:
		//		Attach AOP-style advices to a method.
		//
		// description:
		//		Attaches AOP-style advices to a method. Can attach several
		//		advices at once and operate on several methods of the object.
		//		The latter is achieved when a RegExp is specified as
		//		a method name. In this case all functional methods that
		//		satisfy the RegExp condition are processed. This function
		//		returns a handle, which can be used to unadvise, or null,
		//		if advising has failed.
		//
		// obj:
		//		A source object for the advised function.
		//		Cannot be a DOM node.
		//
		// methods:
		//		An array of method names (strings) to be advised.
		//
		// advices:
		//		An array of advices represented by objects or functions that
		//		return such objects on demand during the event processing.
		//		The advice object can define following member functions:
		//		before, around, afterReturning, afterThrowing, after.
		//		If the function is supplied, it is called with a context
		//		object once per call to create a temporary advice object, which
		//		is destroyed after the processing. The temporary advice object
		//		can implement a destroy() method, if it wants to be called when
		//		not needed.

		if(!methods.length || !advices.length){ return null; }

		// attach advices
		var m = {}, al = advices.length;
		for(var i = methods.length - 1; i >= 0; --i){
			var name = methods[i], o = obj[name], ao = new Array(al), t = o.advices;
			// create a stub, if needed
			if(!t){
				var x = obj[name] = getDispatcher();
				x.target = o.target || o;
				x.targetName = name;
				x._listeners = o._listeners || [];
				x.advices = new Advice;
				t = x.advices;
			}
			// attach advices
			for(var j = 0; j < al; ++j){
				ao[j] = t.add(advices[j]);
			}
			m[name] = ao;
		}

		return [obj, m];	// Object
	};

	aop.unadvise = function(/*Object*/ handle){
		// summary:
		//		Detach previously attached AOP-style advices.
		//
		// handle:
		//		The object returned by dojox.lang.aspect.advise().

		if(!handle){ return; }
		var obj = handle[0], methods = handle[1];
		for(var name in methods){
			var o = obj[name], t = o.advices, ao = methods[name];
			for(var i = ao.length - 1; i >= 0; --i){
				t.remove(ao[i]);
			}
			if(t.isEmpty()){
				// check if we can remove all stubs
				var empty = true, ls = o._listeners;
				if(ls.length){
					for(i in ls){
						if(!(i in ap)){
							empty = false;
							break;
						}
					}
				}
				if(empty){
					// revert to the original method
					obj[name] = o.target;
				}else{
					// replace with the dojo.connect() stub
					var x = obj[name] = d._listener.getDispatcher();
					x.target = o.target;
					x._listeners = ls;
				}
			}
		}
	};

	aop.getContext = function(){
		// summary:
		//		Returns the context information for the advice in effect.

		return context;
	};

	aop.getContextStack = function(){
		// summary:
		//		Returns the context stack, which reflects executing advices
		//		up to this point. The array is ordered from oldest to newest.
		//		In order to get the active context use dojox.lang.aspect.getContext().

		return contextStack;	// Array
	};

	aop.proceed = function(){
		// summary:
		//		Call the original function (or the next level around advice) in an around advice code.
		//
		// description:
		//		Calls the original function (or the next level around advice).
		//		Accepts and passes on any number of arguments, and returns a value.
		//		This function is valid only in the content of around calls.

		var joinPoint = context.joinPoint, advices = joinPoint.advices;
		for(var c = context.around; c != advices; c = context.around){
			context.around = c.prev_around;	// advance the pointer
			if(c.dynamic){
				var a = context.dynAdvices[context.dynIndex++], t = a.around;
				if(t){
					return t.apply(a, arguments);
				}
			}else{
				return c.advice.around.apply(c.advice, arguments);
			}
		}
		return joinPoint.target.apply(context.instance, arguments);
	};
})();

/*
Advice = {
	before: function(arguments){...},
	around: function(arguments){...returns value...},
	afterReturning: function(ret){...},
	afterThrowing: function(event){...},
	after: function(){...}
};

Context = {
	instance:  ..., // the instance we operate on
	joinPoint: ...,	// Object (see below)
	depth:     ...	// current depth of the context stack
};

JoinPoint = {
	target:     ...,	// the original function being wrapped
	targetName: ...		// name of the method
};
*/
<commit_msg>dojox.lang.aspect: improving the performance without around advices. !strict<commit_after>dojo.provide("dojox.lang.aspect");

(function(){
	var d = dojo, aop = dojox.lang.aspect, ap = Array.prototype,
		contextStack = [], context;

	// this class implements a topic-based double-linked list
	var Advice = function(){
		this.next_before = this.prev_before =
		this.next_around = this.prev_around =
		this.next_afterReturning = this.prev_afterReturning =
		this.next_afterThrowing = this.prev_afterThrowing =
			this;
		this.counter = 0;
	};
	d.extend(Advice, {
		add: function(advice){
			var dyn = d.isFunction(advice),
				node = {advice: advice, dynamic: dyn};
			this._add(node, "before", "", dyn, advice);
			this._add(node, "around", "", dyn, advice);
			this._add(node, "after", "Returning", dyn, advice);
			this._add(node, "after", "Throwing", dyn, advice);
			++this.counter;
			return node;
		},
		_add: function(node, topic, subtopic, dyn, advice){
			var full = topic + subtopic;
			if(dyn || advice[topic] || (subtopic && advice[full])){
				var next = "next_" + full, prev = "prev_" + full;
				(node[prev] = this[prev])[next] = node;
				(node[next] = this)[prev] = node;
			}
		},
		remove: function(node){
			this._remove(node, "before");
			this._remove(node, "around");
			this._remove(node, "afterReturning");
			this._remove(node, "afterThrowing");
			--this.counter;
		},
		_remove: function(node, topic){
			var next = "next_" + topic, prev = "prev_" + topic;
			if(node[next]){
				node[next][prev] = node[prev];
				node[prev][next] = node[next];
			}
		},
		isEmpty: function(){
			return !this.counter;
		}
	});

	var getDispatcher = function(){

		return function(){

			var self = arguments.callee,	// the join point
				advices = self.advices,		// list of advices for this joinpoint
				ret, i, a, e, t;

			// push context
			if(context){ contextStack.push(context); }
			context = {
				instance: this,					// object instance
				joinPoint: self,				// join point
				depth: contextStack.length,		// current level of depth starting from 0
				around: advices.prev_around,	// pointer to the current around advice
				dynAdvices: [],					// array of dynamic advices if any
				dynIndex: 0						// index of a dynamic advice
			};

			try{
				// process before events
				for(i = advices.prev_before; i != advices; i = i.prev_before){
					if(i.dynamic){
						// instantiate a dynamic advice
						context.dynAdvices.push(a = new i.advice(context));
						if(t = a.before){
							t.apply(a, arguments);
						}
					}else{
						t = i.advice;
						t.before.apply(t, arguments);
					}
				}

				// process around and after events
				try{
					// call the around advice or the original method
					ret = (advices.prev_around == advices ? self.target : aop.proceed).apply(this, arguments);
				}catch(e){
					// process after throwing and after events
					context.dynIndex = context.dynAdvices.length;
					for(i = advices.next_afterThrowing; i != advices; i = i.next_afterThrowing){
						a = i.dynamic ? context.dynAdvices[--context.dynIndex] : i.advice;
						if(t = a.afterThrowing){
							t.call(a, e);
						}
						if(t = a.after){
							t.call(a);
						}
					}
					// continue the exception processing
					throw e;
				}
				// process after returning and after events
				context.dynIndex = context.dynAdvices.length;
				for(i = advices.next_afterReturning; i != advices; i = i.next_afterReturning){
					a = i.dynamic ? context.dynAdvices[--context.dynIndex] : i.advice;
					if(t = a.afterReturning){
						t.call(a, ret);
					}
					if(t = a.after){
						t.call(a);
					}
				}
				// process dojo.connect() listeners
				var ls = self._listeners;
				for(i in ls){
					if(!(i in ap)){
						ls[i].apply(this, arguments);
					}
				}
			}finally{
				// destroy dynamic advices
				for(i = 0; i < context.dynAdvices.length; ++i){
					a = context.dynAdvices[i];
					if(a.destroy){
						a.destroy();
					}
				}
				// pop context
				context = contextStack.length ? contextStack.pop() : null;
			}

			return ret;
		};
	};

	aop.advise = function(/*Object*/ obj,
						/*String|RegExp|Array*/ method,
						/*Object|Function|Array*/ advice
						){
		// summary:
		//		Attach AOP-style advices to a method.
		//
		// description:
		//		Attaches AOP-style advices to a method. Can attach several
		//		advices at once and operate on several methods of an object.
		//		The latter is achieved when a RegExp is specified as
		//		a method name, or an array of strings and regular expressions
		//		is used. In this case all functional methods that
		//		satisfy the RegExp condition are processed. This function
		//		returns a handle, which can be used to unadvise, or null,
		//		if advising has failed.
		//
		//		This function is a convenience wrapper for
		//		dojox.lang.aspect.adviseRaw().
		//
		// obj:
		//		A source object for the advised function. Cannot be a DOM node.
		//		If this object is a constructor, its prototype is advised.
		//
		// method:
		//		A string name of the function in obj. In case of RegExp all
		//		methods of obj matching the regular expression are advised.
		//
		// advice:
		//		An object, which defines advises, or a function, which
		//		returns such object, or an array of previous items.
		//		The advice object can define following member functions:
		//		before, around, afterReturning, afterThrowing, after.
		//		If the function is supplied, it is called with a context
		//		object once per call to create a temporary advice object, which
		//		is destroyed after the processing. The temporary advice object
		//		can implement a destroy() method, if it wants to be called when
		//		not needed.

		if(typeof obj != "object"){
			obj = obj.prototype;
		}

		var methods = [];
		if(!(method instanceof Array)){
			method = [method];
		}

		// identify advised methods
		for(var j = 0; j < method.length; ++j){
			var t = method[j];
			if(t instanceof RegExp){
				for(var i in obj){
					if(d.isFunction(obj[i]) && t.test(i)){
						methods.push(i);
					}
				}
			}else{
				if(d.isFunction(obj[t])){
					methods.push(t);
				}
			}
		}

		if(!d.isArray(advice)){ advice = [advice]; }

		return aop.adviseRaw(obj, methods, advice);	// Object
	};

	aop.adviseRaw = function(/*Object*/ obj,
						/*Array*/ methods,
						/*Array*/ advices
						){
		// summary:
		//		Attach AOP-style advices to a method.
		//
		// description:
		//		Attaches AOP-style advices to a method. Can attach several
		//		advices at once and operate on several methods of the object.
		//		The latter is achieved when a RegExp is specified as
		//		a method name. In this case all functional methods that
		//		satisfy the RegExp condition are processed. This function
		//		returns a handle, which can be used to unadvise, or null,
		//		if advising has failed.
		//
		// obj:
		//		A source object for the advised function.
		//		Cannot be a DOM node.
		//
		// methods:
		//		An array of method names (strings) to be advised.
		//
		// advices:
		//		An array of advices represented by objects or functions that
		//		return such objects on demand during the event processing.
		//		The advice object can define following member functions:
		//		before, around, afterReturning, afterThrowing, after.
		//		If the function is supplied, it is called with a context
		//		object once per call to create a temporary advice object, which
		//		is destroyed after the processing. The temporary advice object
		//		can implement a destroy() method, if it wants to be called when
		//		not needed.

		if(!methods.length || !advices.length){ return null; }

		// attach advices
		var m = {}, al = advices.length;
		for(var i = methods.length - 1; i >= 0; --i){
			var name = methods[i], o = obj[name], ao = new Array(al), t = o.advices;
			// create a stub, if needed
			if(!t){
				var x = obj[name] = getDispatcher();
				x.target = o.target || o;
				x.targetName = name;
				x._listeners = o._listeners || [];
				x.advices = new Advice;
				t = x.advices;
			}
			// attach advices
			for(var j = 0; j < al; ++j){
				ao[j] = t.add(advices[j]);
			}
			m[name] = ao;
		}

		return [obj, m];	// Object
	};

	aop.unadvise = function(/*Object*/ handle){
		// summary:
		//		Detach previously attached AOP-style advices.
		//
		// handle:
		//		The object returned by dojox.lang.aspect.advise().

		if(!handle){ return; }
		var obj = handle[0], methods = handle[1];
		for(var name in methods){
			var o = obj[name], t = o.advices, ao = methods[name];
			for(var i = ao.length - 1; i >= 0; --i){
				t.remove(ao[i]);
			}
			if(t.isEmpty()){
				// check if we can remove all stubs
				var empty = true, ls = o._listeners;
				if(ls.length){
					for(i in ls){
						if(!(i in ap)){
							empty = false;
							break;
						}
					}
				}
				if(empty){
					// revert to the original method
					obj[name] = o.target;
				}else{
					// replace with the dojo.connect() stub
					var x = obj[name] = d._listener.getDispatcher();
					x.target = o.target;
					x._listeners = ls;
				}
			}
		}
	};

	aop.getContext = function(){
		// summary:
		//		Returns the context information for the advice in effect.

		return context;
	};

	aop.getContextStack = function(){
		// summary:
		//		Returns the context stack, which reflects executing advices
		//		up to this point. The array is ordered from oldest to newest.
		//		In order to get the active context use dojox.lang.aspect.getContext().

		return contextStack;	// Array
	};

	aop.proceed = function(){
		// summary:
		//		Call the original function (or the next level around advice) in an around advice code.
		//
		// description:
		//		Calls the original function (or the next level around advice).
		//		Accepts and passes on any number of arguments, and returns a value.
		//		This function is valid only in the content of around calls.

		var joinPoint = context.joinPoint, advices = joinPoint.advices;
		for(var c = context.around; c != advices; c = context.around){
			context.around = c.prev_around;	// advance the pointer
			if(c.dynamic){
				var a = context.dynAdvices[context.dynIndex++], t = a.around;
				if(t){
					return t.apply(a, arguments);
				}
			}else{
				return c.advice.around.apply(c.advice, arguments);
			}
		}
		return joinPoint.target.apply(context.instance, arguments);
	};
})();

/*
Advice = {
	before: function(arguments){...},
	around: function(arguments){...returns value...},
	afterReturning: function(ret){...},
	afterThrowing: function(event){...},
	after: function(){...}
};

Context = {
	instance:  ..., // the instance we operate on
	joinPoint: ...,	// Object (see below)
	depth:     ...	// current depth of the context stack
};

JoinPoint = {
	target:     ...,	// the original function being wrapped
	targetName: ...		// name of the method
};
*/
<|endoftext|>


<commit_before>// geonames Array autocompleter based on scriptaculous Autocompleter.Base
//
// The constructor takes following parameters:
// - id of the monitored textbox
// - id of the autocompletion menu
// - callback prefix
// - options block
//
Autocompleter.Geocode = Class.create(Autocompleter.Base, {
  initialize: function(element, update, serviceCallbackPrefix, options) {
    this.baseInitialize(element, update, options);
    this.serviceCallbackPrefix = serviceCallbackPrefix || '';
    this.options.keepFocus = (typeof this.options.keepFocus == 'undefined') ? true : this.options.keepFocus;
    // if the element has class geonames, we use this service, else we use nominatim (http://wiki.openstreetmap.org/wiki/Nominatim)
    if ($(element).hasClassName('geonames')) {
      this.service = 'geonames';
    } else {
      this.service = 'nominatim';
    }
    // the 'no result' translated string is found as a dataset of the input element
    this.noresult = $(element).getAttribute('data-noresult');
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var request = '';
    if (this.service === 'geonames') {
      request = 'http://api.geonames.org/searchJSON?maxRows=10&featureClass=P&featureClass=T' +
                '&username=c2corg&callback=' + this.serviceCallbackPrefix +
                '.handleJSON&lang=' + document.documentElement.lang + '&name_startsWith=' +
                encodeURIComponent(this.getToken());
    } else {
      request = 'http://nominatim.openstreetmap.org/search?format=json&limit=10&json_callback=' +
                this.serviceCallbackPrefix + '.handleJSON&email=dev@campto' + 'camp.org&q=' +
                encodeURIComponent(this.getToken());
    }

    this.getJSON(request);

  },

  handleJSON: function(json) {
    if (this.service === 'geonames') { // geonames
      if (json.totalResultsCount > 0) {
        var ul = '
';
        var place;
        for (place in json.geonames) {
          if (json.geonames.hasOwnProperty(place)) {
            ul += '
' + json.geonames[place].name + '
[' + json.geonames[place].adminName1 +
                  ' - ' + json.geonames[place].countryName + ']
';
          }
        }
        this.updateChoices(ul + '
');
      } else {
        this.updateChoices('

' + this.noresult + '

');
      }

    } else { // nominatim
      if (json.size() > 0) {
        var ul = '
';
        var place;
        for (place in json) {
          if (json.hasOwnProperty(place)) {
            ul += '
' +
                  json[place].display_name + '
';
          }
        }
        this.updateChoices(ul + '
');
      } else {
        this.updateChoices('

' + this.noresult + '

');
      }
    }
  },

  // asynchrously load script to call the geonames.org JSON webservice
  getJSON: function(url) {
    var a = document.createElement('script'), h = document.getElementsByTagName('head')[0];
    a.async = 1;
    a.src = url;
    h.appendChild(a);
  },

  // Base.Autocompleter puts back focus to the input element after element selection
  // which we don't want in mobile version
  // so the following function is basic copy/paste with juste the possibility to
  // disable focus() with options
  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;

    if (this.options.keepFocus) {
      this.element.focus();
    }

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  }
});

(function() {

"use strict";

window.C2C = window.C2C || {};

C2C.geo = C2C.geo || {};

C2C.geo.update_around_on_select_change = function(elt) {
  var index = $(elt + '_sel').options.selectedIndex;

  // reset fields and hide all inner spans
  $(elt + '_lat').value = '';
  $(elt + '_lon').value = '';
  $(elt + '_range_span').show();
  $(elt + '_geocode',
    elt + '_geolocation_not_supported',
    elt + '_geolocation_waiting',
    elt + '_geolocation_failed').invoke('hide');

  if (index === 0)
  {
    $(elt + '_span').hide();
  }
  else
  {
    // display high level span
    $(elt + '_span').show();

    // display only relevant inner span
    if (index === 1) { // geocode autocompleter
      $(elt + '_geocode').show();
    } else if (index === 2) { // user geolocalization
      $(elt + '_range_span').hide();
      // detect geolocation correctly
      // https://github.com/Modernizr/Modernizr/blob/633a5ac/modernizr.js#L478-490
      if ('geolocation' in navigator) {
        $(elt + '_geolocation_waiting').show();
        navigator.geolocation.getCurrentPosition(
          function(position) {
            $(elt + '_geolocation_waiting').hide();
            $(elt + '_range_span').show();
            $(elt + '_lat').value = position.coords.latitude;
            $(elt + '_lon').value = position.coords.longitude;
          },
          function(error) {
            $(elt + '_geolocation_waiting').hide();
            $(elt + '_geolocation_' + (error.code === 1 ? 'denied' : 'failed')).show();
          });
      } else {
        // geolocation not supported by browser
        $(elt + '_geolocation_not_supported').show();
      }
    }
  }
};

var mobile = $$('html')[0].hasClassName('mobile');
$$('.geocode_auto_complete').each(function(obj) {
  var name = obj.id;
  C2C.geo[name] = new Autocompleter.Geocode(name,
                    name + '_auto_complete',
                    'C2C.geo.' + name, {
                      minChars: 3, indicator: 'indicator',
                      keepFocus: !mobile,
                      afterUpdateElement: function(inputField, selectedItem) {
                        $(name + '_lat').value = selectedItem.getAttribute('data-lat');
                        $(name + '_lon').value = selectedItem.getAttribute('data-lon');
                      }
                    });
  if (mobile) {
    var offset;
    obj.observe('focus', function(event) {
      // save current page offset
      offset = window.pageYOffset;
      window.scrollTo(0, 1);
      // move indicator to one better location
      $('indicator').addClassName('auto_complete_pos');
    }).observe('blur', function(event) {
      // scroll back to where we were before selecting input
      window.scrollTo(0, offset);
      // reset indicator position
       $('indicator').removeClassName('auto_complete_pos');
    });
  }
});

})();
<commit_msg>indent<commit_after>// geonames Array autocompleter based on scriptaculous Autocompleter.Base
//
// The constructor takes following parameters:
// - id of the monitored textbox
// - id of the autocompletion menu
// - callback prefix
// - options block
//
Autocompleter.Geocode = Class.create(Autocompleter.Base, {
  initialize: function(element, update, serviceCallbackPrefix, options) {
    this.baseInitialize(element, update, options);
    this.serviceCallbackPrefix = serviceCallbackPrefix || '';
    this.options.keepFocus = (typeof this.options.keepFocus == 'undefined') ? true : this.options.keepFocus;
    // if the element has class geonames, we use this service, else we use nominatim (http://wiki.openstreetmap.org/wiki/Nominatim)
    if ($(element).hasClassName('geonames')) {
      this.service = 'geonames';
    } else {
      this.service = 'nominatim';
    }
    // the 'no result' translated string is found as a dataset of the input element
    this.noresult = $(element).getAttribute('data-noresult');
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var request = '';
    if (this.service === 'geonames') {
      request = 'http://api.geonames.org/searchJSON?maxRows=10&featureClass=P&featureClass=T' +
                '&username=c2corg&callback=' + this.serviceCallbackPrefix +
                '.handleJSON&lang=' + document.documentElement.lang + '&name_startsWith=' +
                encodeURIComponent(this.getToken());
    } else {
      request = 'http://nominatim.openstreetmap.org/search?format=json&limit=10&json_callback=' +
                this.serviceCallbackPrefix + '.handleJSON&email=dev@campto' + 'camp.org&q=' +
                encodeURIComponent(this.getToken());
    }

    this.getJSON(request);

  },

  handleJSON: function(json) {
    if (this.service === 'geonames') { // geonames
      if (json.totalResultsCount > 0) {
        var ul = '
';
        var place;
        for (place in json.geonames) {
          if (json.geonames.hasOwnProperty(place)) {
            ul += '
' + json.geonames[place].name + '
[' + json.geonames[place].adminName1 +
                  ' - ' + json.geonames[place].countryName + ']
';
          }
        }
        this.updateChoices(ul + '
');
      } else {
        this.updateChoices('

' + this.noresult + '

');
      }

    } else { // nominatim
      if (json.size() > 0) {
        var ul = '
';
        var place;
        for (place in json) {
          if (json.hasOwnProperty(place)) {
            ul += '
' +
                  json[place].display_name + '
';
          }
        }
        this.updateChoices(ul + '
');
      } else {
        this.updateChoices('

' + this.noresult + '

');
      }
    }
  },

  // asynchrously load script to call the geonames.org JSON webservice
  getJSON: function(url) {
    var a = document.createElement('script'), h = document.getElementsByTagName('head')[0];
    a.async = 1;
    a.src = url;
    h.appendChild(a);
  },

  // Base.Autocompleter puts back focus to the input element after element selection
  // which we don't want in mobile version
  // so the following function is basic copy/paste with juste the possibility to
  // disable focus() with options
  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;

    if (this.options.keepFocus) {
      this.element.focus();
    }

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  }
});

(function(C2C) {

  "use strict";

  C2C.geo = C2C.geo || {};

  C2C.geo.update_around_on_select_change = function(elt) {
    var index = $(elt + '_sel').options.selectedIndex;

    // reset fields and hide all inner spans
    $(elt + '_lat').value = '';
    $(elt + '_lon').value = '';
    $(elt + '_range_span').show();
    $(elt + '_geocode',
      elt + '_geolocation_not_supported',
      elt + '_geolocation_waiting',
      elt + '_geolocation_failed').invoke('hide');

    if (index === 0) {
      $(elt + '_span').hide();
    } else {
      // display high level span
      $(elt + '_span').show();

      // display only relevant inner span
      if (index === 1) { // geocode autocompleter
        $(elt + '_geocode').show();
      } else if (index === 2) { // user geolocalization
        $(elt + '_range_span').hide();
        // detect geolocation correctly
        // https://github.com/Modernizr/Modernizr/blob/633a5ac/modernizr.js#L478-490
        if ('geolocation' in navigator) {
          $(elt + '_geolocation_waiting').show();
          navigator.geolocation.getCurrentPosition(
            function(position) {
              $(elt + '_geolocation_waiting').hide();
              $(elt + '_range_span').show();
              $(elt + '_lat').value = position.coords.latitude;
              $(elt + '_lon').value = position.coords.longitude;
            },
            function(error) {
              $(elt + '_geolocation_waiting').hide();
              $(elt + '_geolocation_' + (error.code === 1 ? 'denied' : 'failed')).show();
            });
        } else {
          // geolocation not supported by browser
          $(elt + '_geolocation_not_supported').show();
        }
      }
    }
  };

  var mobile = $$('html')[0].hasClassName('mobile');
  $$('.geocode_auto_complete').each(function(obj) {
    var name = obj.id;
    C2C.geo[name] = new Autocompleter.Geocode(name,
                      name + '_auto_complete',
                      'C2C.geo.' + name, {
                        minChars: 3, indicator: 'indicator',
                        keepFocus: !mobile,
                        afterUpdateElement: function(inputField, selectedItem) {
                          $(name + '_lat').value = selectedItem.getAttribute('data-lat');
                          $(name + '_lon').value = selectedItem.getAttribute('data-lon');
                        }
                      });
    if (mobile) {
      var offset;
      obj.observe('focus', function(event) {
        // save current page offset
        offset = window.pageYOffset;
        window.scrollTo(0, 1);
        // move indicator to one better location
        $('indicator').addClassName('auto_complete_pos');
      }).observe('blur', function(event) {
        // scroll back to where we were before selecting input
        window.scrollTo(0, offset);
        // reset indicator position
        $('indicator').removeClassName('auto_complete_pos');
      });
    }
  });

})(window.C2C = window.C2C || {});
<|endoftext|>


<commit_before>

Doms.loaders['[YKS]/Interface/ShowCase'] = {
    "class": "ShowCase",
    "match": false,
    "descr": "A cool showcase",
    "deps" : ["[YKS]/Math/Matrix", "[YKS]/Math/Matrix.Functions", "[YKS]/Canvas/Canvas", "[YKS]/Canvas/Projection", "[YKS]/Math/Functions"]
};

Doms.loaders['[YKS]/Interface/Switcher'] = {
    "class": "Switcher",
    "match": false
};

Doms.loaders['[YKS]/Utilities/Imgs/Thumbnailer.avatar'] = {
    "class": "Thumbnailer",
    "match": false,
    "descr": "A tiny image thumbnailer"
};

<commit_msg>Js: headers upgrade<commit_after><|endoftext|>


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

var util = require('../common/util.js');

function Query(namespace, kinds) {
  this.namespace = namespace;
  this.kinds = kinds;

  this.filters = [];
  this.orders = [];
  this.groupByVal = [];
  this.selectVal = [];

  // pagination
  this.startVal = null;
  this.limitVal = -1;
  this.offsetVal = -1;
}

Query.prototype.filter = function(filter, value) {
  // TODO(jbd): Add filter validation.
  var q = util.extend(this, new Query());
  filter = filter.trim();
  var fieldName = filter.replace(/[>|<|=|>=|<=]*$/, '').trim(),
      op = filter.substr(fieldName.length, filter.length).trim();
  q.filters = q.filters || [];
  q.filters.push({ name: fieldName, op: op, val: value });
  return q;
};

Query.prototype.hasAncestor = function(key) {
  var q = util.extend(this, new Query());
  this.filters.push({ name: '__key__', op: 'HAS_ANCESTOR', val: key });
  return q;
};

Query.prototype.order = function(order) {
  var q = util.extend(this, new Query());
  var sign = order[0],
      fieldName = order.substr(1);
  if (sign != '-' && sign != '+' ) {
    throw new Error('Invalid order pattern, either should be "+fieldName" or "-fieldName".')
  }
  q.orders = q.orders || [];
  q.orders.push({ name: fieldName, sign: sign });
  return q;
};

Query.prototype.groupBy = function(fieldNames) {
  var q = util.extend(this, new Query());
  q.groupByVal = fieldNames;
  return q;
};

Query.prototype.select = function(fieldNames) {
  var q = util.extend(this, new Query());
  q.selectVal = fieldNames;
  return q;
};

Query.prototype.start = function(start) {
  var q = util.extend(this, new Query());
  q.startVal = start;
  return q;
}

Query.prototype.limit = function(n) {
  var q = util.extend(this, new Query());
  q.limitVal = n;
  return q;
};

Query.prototype.offset = function(n) {
  var q = util.extend(this, new Query());
  q.offsetVal = n;
  return q;
};

/**
 * Exports Query.
 */
module.exports.Query = Query;<commit_msg>datastore: Arrayize input field names.<commit_after>/**
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var util = require('../common/util.js');

function Query(namespace, kinds) {
  this.namespace = namespace;
  this.kinds = kinds;

  this.filters = [];
  this.orders = [];
  this.groupByVal = [];
  this.selectVal = [];

  // pagination
  this.startVal = null;
  this.limitVal = -1;
  this.offsetVal = -1;
}

Query.prototype.filter = function(filter, value) {
  // TODO(jbd): Add filter validation.
  var q = util.extend(this, new Query());
  filter = filter.trim();
  var fieldName = filter.replace(/[>|<|=|>=|<=]*$/, '').trim(),
      op = filter.substr(fieldName.length, filter.length).trim();
  q.filters = q.filters || [];
  q.filters.push({ name: fieldName, op: op, val: value });
  return q;
};

Query.prototype.hasAncestor = function(key) {
  var q = util.extend(this, new Query());
  this.filters.push({ name: '__key__', op: 'HAS_ANCESTOR', val: key });
  return q;
};

Query.prototype.order = function(order) {
  var q = util.extend(this, new Query());
  var sign = order[0],
      fieldName = order.substr(1);
  if (sign != '-' && sign != '+' ) {
    throw new Error('Invalid order pattern, either should be "+fieldName" or "-fieldName".')
  }
  q.orders = q.orders || [];
  q.orders.push({ name: fieldName, sign: sign });
  return q;
};

Query.prototype.groupBy = function(fieldNames) {
  var fields = util.arrayize(fieldNames);
  var q = util.extend(this, new Query());
  q.groupByVal = fields;
  return q;
};

Query.prototype.select = function(fieldNames) {
  var q = util.extend(this, new Query());
  q.selectVal = fieldNames;
  return q;
};

Query.prototype.start = function(start) {
  var q = util.extend(this, new Query());
  q.startVal = start;
  return q;
}

Query.prototype.limit = function(n) {
  var q = util.extend(this, new Query());
  q.limitVal = n;
  return q;
};

Query.prototype.offset = function(n) {
  var q = util.extend(this, new Query());
  q.offsetVal = n;
  return q;
};

/**
 * Exports Query.
 */
module.exports.Query = Query;<|endoftext|>